The fifteenth batch
[alt-git.git] / builtin / bisect.c
blobdabce9b542b1e001daea083b6e2bff4d5cf9d460
1 #include "builtin.h"
2 #include "copy.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "hex.h"
6 #include "object-name.h"
7 #include "parse-options.h"
8 #include "bisect.h"
9 #include "refs.h"
10 #include "strvec.h"
11 #include "run-command.h"
12 #include "oid-array.h"
13 #include "path.h"
14 #include "prompt.h"
15 #include "quote.h"
16 #include "revision.h"
18 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
19 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
20 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
21 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
22 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
23 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
24 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
26 #define BUILTIN_GIT_BISECT_START_USAGE \
27 N_("git bisect start [--term-(new|bad)=<term> --term-(old|good)=<term>]" \
28 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
29 " [<pathspec>...]")
30 #define BUILTIN_GIT_BISECT_STATE_USAGE \
31 N_("git bisect (good|bad) [<rev>...]")
32 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
33 "git bisect terms [--term-good | --term-bad]"
34 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
35 N_("git bisect skip [(<rev>|<range>)...]")
36 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
37 "git bisect next"
38 #define BUILTIN_GIT_BISECT_RESET_USAGE \
39 N_("git bisect reset [<commit>]")
40 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
41 "git bisect visualize"
42 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
43 N_("git bisect replay <logfile>")
44 #define BUILTIN_GIT_BISECT_LOG_USAGE \
45 "git bisect log"
46 #define BUILTIN_GIT_BISECT_RUN_USAGE \
47 N_("git bisect run <cmd> [<arg>...]")
49 static const char * const git_bisect_usage[] = {
50 BUILTIN_GIT_BISECT_START_USAGE,
51 BUILTIN_GIT_BISECT_STATE_USAGE,
52 BUILTIN_GIT_BISECT_TERMS_USAGE,
53 BUILTIN_GIT_BISECT_SKIP_USAGE,
54 BUILTIN_GIT_BISECT_NEXT_USAGE,
55 BUILTIN_GIT_BISECT_RESET_USAGE,
56 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
57 BUILTIN_GIT_BISECT_REPLAY_USAGE,
58 BUILTIN_GIT_BISECT_LOG_USAGE,
59 BUILTIN_GIT_BISECT_RUN_USAGE,
60 NULL
63 struct add_bisect_ref_data {
64 struct rev_info *revs;
65 unsigned int object_flags;
68 struct bisect_terms {
69 char *term_good;
70 char *term_bad;
73 static void free_terms(struct bisect_terms *terms)
75 FREE_AND_NULL(terms->term_good);
76 FREE_AND_NULL(terms->term_bad);
79 static void set_terms(struct bisect_terms *terms, const char *bad,
80 const char *good)
82 free((void *)terms->term_good);
83 terms->term_good = xstrdup(good);
84 free((void *)terms->term_bad);
85 terms->term_bad = xstrdup(bad);
88 static const char vocab_bad[] = "bad|new";
89 static const char vocab_good[] = "good|old";
91 static int bisect_autostart(struct bisect_terms *terms);
94 * Check whether the string `term` belongs to the set of strings
95 * included in the variable arguments.
97 LAST_ARG_MUST_BE_NULL
98 static int one_of(const char *term, ...)
100 int res = 0;
101 va_list matches;
102 const char *match;
104 va_start(matches, term);
105 while (!res && (match = va_arg(matches, const char *)))
106 res = !strcmp(term, match);
107 va_end(matches);
109 return res;
113 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
114 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
115 * that indicate special success.
118 static int is_bisect_success(enum bisect_error res)
120 return !res ||
121 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
122 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
125 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
127 FILE *fp = NULL;
128 int res = 0;
130 if (strcmp(mode, "w") && strcmp(mode, "a"))
131 BUG("write-in-file does not support '%s' mode", mode);
132 fp = fopen(path, mode);
133 if (!fp)
134 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
135 res = vfprintf(fp, format, args);
137 if (res < 0) {
138 int saved_errno = errno;
139 fclose(fp);
140 errno = saved_errno;
141 return error_errno(_("could not write to file '%s'"), path);
144 return fclose(fp);
147 __attribute__((format (printf, 2, 3)))
148 static int write_to_file(const char *path, const char *format, ...)
150 int res;
151 va_list args;
153 va_start(args, format);
154 res = write_in_file(path, "w", format, args);
155 va_end(args);
157 return res;
160 __attribute__((format (printf, 2, 3)))
161 static int append_to_file(const char *path, const char *format, ...)
163 int res;
164 va_list args;
166 va_start(args, format);
167 res = write_in_file(path, "a", format, args);
168 va_end(args);
170 return res;
173 static int print_file_to_stdout(const char *path)
175 int fd = open(path, O_RDONLY);
176 int ret = 0;
178 if (fd < 0)
179 return error_errno(_("cannot open file '%s' for reading"), path);
180 if (copy_fd(fd, 1) < 0)
181 ret = error_errno(_("failed to read '%s'"), path);
182 close(fd);
183 return ret;
186 static int check_term_format(const char *term, const char *orig_term)
188 int res;
189 char *new_term = xstrfmt("refs/bisect/%s", term);
191 res = check_refname_format(new_term, 0);
192 free(new_term);
194 if (res)
195 return error(_("'%s' is not a valid term"), term);
197 if (one_of(term, "help", "start", "skip", "next", "reset",
198 "visualize", "view", "replay", "log", "run", "terms", NULL))
199 return error(_("can't use the builtin command '%s' as a term"), term);
202 * In theory, nothing prevents swapping completely good and bad,
203 * but this situation could be confusing and hasn't been tested
204 * enough. Forbid it for now.
207 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
208 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
209 return error(_("can't change the meaning of the term '%s'"), term);
211 return 0;
214 static int write_terms(const char *bad, const char *good)
216 int res;
218 if (!strcmp(bad, good))
219 return error(_("please use two different terms"));
221 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
222 return -1;
224 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
226 return res;
229 static int bisect_reset(const char *commit)
231 struct strbuf branch = STRBUF_INIT;
233 if (!commit) {
234 if (!strbuf_read_file(&branch, git_path_bisect_start(), 0))
235 printf(_("We are not bisecting.\n"));
236 else
237 strbuf_rtrim(&branch);
238 } else {
239 struct object_id oid;
241 if (repo_get_oid_commit(the_repository, commit, &oid))
242 return error(_("'%s' is not a valid commit"), commit);
243 strbuf_addstr(&branch, commit);
246 if (branch.len && !refs_ref_exists(get_main_ref_store(the_repository), "BISECT_HEAD")) {
247 struct child_process cmd = CHILD_PROCESS_INIT;
249 cmd.git_cmd = 1;
250 strvec_pushl(&cmd.args, "checkout", "--ignore-other-worktrees",
251 branch.buf, "--", NULL);
252 if (run_command(&cmd)) {
253 error(_("could not check out original"
254 " HEAD '%s'. Try 'git bisect"
255 " reset <commit>'."), branch.buf);
256 strbuf_release(&branch);
257 return -1;
261 strbuf_release(&branch);
262 return bisect_clean_state();
265 static void log_commit(FILE *fp,
266 const char *fmt, const char *state,
267 struct commit *commit)
269 struct pretty_print_context pp = {0};
270 struct strbuf commit_msg = STRBUF_INIT;
271 char *label = xstrfmt(fmt, state);
273 repo_format_commit_message(the_repository, commit, "%s", &commit_msg,
274 &pp);
276 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
277 commit_msg.buf);
279 strbuf_release(&commit_msg);
280 free(label);
283 static int bisect_write(const char *state, const char *rev,
284 const struct bisect_terms *terms, int nolog)
286 struct strbuf tag = STRBUF_INIT;
287 struct object_id oid;
288 struct commit *commit;
289 FILE *fp = NULL;
290 int res = 0;
292 if (!strcmp(state, terms->term_bad)) {
293 strbuf_addf(&tag, "refs/bisect/%s", state);
294 } else if (one_of(state, terms->term_good, "skip", NULL)) {
295 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
296 } else {
297 res = error(_("Bad bisect_write argument: %s"), state);
298 goto finish;
301 if (repo_get_oid(the_repository, rev, &oid)) {
302 res = error(_("couldn't get the oid of the rev '%s'"), rev);
303 goto finish;
306 if (refs_update_ref(get_main_ref_store(the_repository), NULL, tag.buf, &oid, NULL, 0,
307 UPDATE_REFS_MSG_ON_ERR)) {
308 res = -1;
309 goto finish;
312 fp = fopen(git_path_bisect_log(), "a");
313 if (!fp) {
314 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
315 goto finish;
318 commit = lookup_commit_reference(the_repository, &oid);
319 log_commit(fp, "%s", state, commit);
321 if (!nolog)
322 fprintf(fp, "git bisect %s %s\n", state, rev);
324 finish:
325 if (fp)
326 fclose(fp);
327 strbuf_release(&tag);
328 return res;
331 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
333 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
335 if (one_of(cmd, "skip", "start", "terms", NULL))
336 return 0;
338 if (has_term_file && strcmp(cmd, terms->term_bad) &&
339 strcmp(cmd, terms->term_good))
340 return error(_("Invalid command: you're currently in a "
341 "%s/%s bisect"), terms->term_bad,
342 terms->term_good);
344 if (!has_term_file) {
345 if (one_of(cmd, "bad", "good", NULL)) {
346 set_terms(terms, "bad", "good");
347 return write_terms(terms->term_bad, terms->term_good);
349 if (one_of(cmd, "new", "old", NULL)) {
350 set_terms(terms, "new", "old");
351 return write_terms(terms->term_bad, terms->term_good);
355 return 0;
358 static int inc_nr(const char *refname UNUSED,
359 const struct object_id *oid UNUSED,
360 int flag UNUSED, void *cb_data)
362 unsigned int *nr = (unsigned int *)cb_data;
363 (*nr)++;
364 return 0;
367 static const char need_bad_and_good_revision_warning[] =
368 N_("You 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 const char need_bisect_start_warning[] =
372 N_("You need to start by \"git bisect start\".\n"
373 "You then need to give me at least one %s and %s revision.\n"
374 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
376 static int decide_next(const struct bisect_terms *terms,
377 const char *current_term, int missing_good,
378 int missing_bad)
380 if (!missing_good && !missing_bad)
381 return 0;
382 if (!current_term)
383 return -1;
385 if (missing_good && !missing_bad &&
386 !strcmp(current_term, terms->term_good)) {
387 char *yesno;
389 * have bad (or new) but not good (or old). We could bisect
390 * although this is less optimum.
392 warning(_("bisecting only with a %s commit"), terms->term_bad);
393 if (!isatty(0))
394 return 0;
396 * TRANSLATORS: Make sure to include [Y] and [n] in your
397 * translation. The program will only accept English input
398 * at this point.
400 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
401 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
402 return -1;
403 return 0;
406 if (!is_empty_or_missing_file(git_path_bisect_start()))
407 return error(_(need_bad_and_good_revision_warning),
408 vocab_bad, vocab_good, vocab_bad, vocab_good);
409 else
410 return error(_(need_bisect_start_warning),
411 vocab_good, vocab_bad, vocab_good, vocab_bad);
414 static void bisect_status(struct bisect_state *state,
415 const struct bisect_terms *terms)
417 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
418 char *good_glob = xstrfmt("%s-*", terms->term_good);
420 if (refs_ref_exists(get_main_ref_store(the_repository), bad_ref))
421 state->nr_bad = 1;
423 refs_for_each_glob_ref_in(get_main_ref_store(the_repository), inc_nr,
424 good_glob, "refs/bisect/",
425 (void *) &state->nr_good);
427 free(good_glob);
428 free(bad_ref);
431 __attribute__((format (printf, 1, 2)))
432 static void bisect_log_printf(const char *fmt, ...)
434 struct strbuf buf = STRBUF_INIT;
435 va_list ap;
437 va_start(ap, fmt);
438 strbuf_vaddf(&buf, fmt, ap);
439 va_end(ap);
441 printf("%s", buf.buf);
442 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
444 strbuf_release(&buf);
447 static void bisect_print_status(const struct bisect_terms *terms)
449 struct bisect_state state = { 0 };
451 bisect_status(&state, terms);
453 /* If we had both, we'd already be started, and shouldn't get here. */
454 if (state.nr_good && state.nr_bad)
455 return;
457 if (!state.nr_good && !state.nr_bad)
458 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
459 else if (state.nr_good)
460 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
461 "status: waiting for bad commit, %d good commits known\n",
462 state.nr_good), state.nr_good);
463 else
464 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
467 static int bisect_next_check(const struct bisect_terms *terms,
468 const char *current_term)
470 struct bisect_state state = { 0 };
471 bisect_status(&state, terms);
472 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
475 static int get_terms(struct bisect_terms *terms)
477 struct strbuf str = STRBUF_INIT;
478 FILE *fp = NULL;
479 int res = 0;
481 fp = fopen(git_path_bisect_terms(), "r");
482 if (!fp) {
483 res = -1;
484 goto finish;
487 free_terms(terms);
488 strbuf_getline_lf(&str, fp);
489 terms->term_bad = strbuf_detach(&str, NULL);
490 strbuf_getline_lf(&str, fp);
491 terms->term_good = strbuf_detach(&str, NULL);
493 finish:
494 if (fp)
495 fclose(fp);
496 strbuf_release(&str);
497 return res;
500 static int bisect_terms(struct bisect_terms *terms, const char *option)
502 if (get_terms(terms))
503 return error(_("no terms defined"));
505 if (!option) {
506 printf(_("Your current terms are %s for the old state\n"
507 "and %s for the new state.\n"),
508 terms->term_good, terms->term_bad);
509 return 0;
511 if (one_of(option, "--term-good", "--term-old", NULL))
512 printf("%s\n", terms->term_good);
513 else if (one_of(option, "--term-bad", "--term-new", NULL))
514 printf("%s\n", terms->term_bad);
515 else
516 return error(_("invalid argument %s for 'git bisect terms'.\n"
517 "Supported options are: "
518 "--term-good|--term-old and "
519 "--term-bad|--term-new."), option);
521 return 0;
524 static int bisect_append_log_quoted(const char **argv)
526 int res = 0;
527 FILE *fp = fopen(git_path_bisect_log(), "a");
528 struct strbuf orig_args = STRBUF_INIT;
530 if (!fp)
531 return -1;
533 if (fprintf(fp, "git bisect start") < 1) {
534 res = -1;
535 goto finish;
538 sq_quote_argv(&orig_args, argv);
539 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
540 res = -1;
542 finish:
543 fclose(fp);
544 strbuf_release(&orig_args);
545 return res;
548 static int add_bisect_ref(const char *refname, const struct object_id *oid,
549 int flags UNUSED, void *cb)
551 struct add_bisect_ref_data *data = cb;
553 add_pending_oid(data->revs, refname, oid, data->object_flags);
555 return 0;
558 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
560 int res = 0;
561 struct add_bisect_ref_data cb = { revs };
562 char *good = xstrfmt("%s-*", terms->term_good);
565 * We cannot use terms->term_bad directly in
566 * for_each_glob_ref_in() and we have to append a '*' to it,
567 * otherwise for_each_glob_ref_in() will append '/' and '*'.
569 char *bad = xstrfmt("%s*", terms->term_bad);
572 * It is important to reset the flags used by revision walks
573 * as the previous call to bisect_next_all() in turn
574 * sets up a revision walk.
576 reset_revision_walk();
577 repo_init_revisions(the_repository, revs, NULL);
578 setup_revisions(0, NULL, revs, NULL);
579 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
580 add_bisect_ref, bad, "refs/bisect/", &cb);
581 cb.object_flags = UNINTERESTING;
582 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
583 add_bisect_ref, good, "refs/bisect/", &cb);
584 if (prepare_revision_walk(revs))
585 res = error(_("revision walk setup failed\n"));
587 free(good);
588 free(bad);
589 return res;
592 static int bisect_skipped_commits(struct bisect_terms *terms)
594 int res;
595 FILE *fp = NULL;
596 struct rev_info revs;
597 struct commit *commit;
598 struct pretty_print_context pp = {0};
599 struct strbuf commit_name = STRBUF_INIT;
601 res = prepare_revs(terms, &revs);
602 if (res)
603 return res;
605 fp = fopen(git_path_bisect_log(), "a");
606 if (!fp)
607 return error_errno(_("could not open '%s' for appending"),
608 git_path_bisect_log());
610 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
611 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
613 while ((commit = get_revision(&revs)) != NULL) {
614 strbuf_reset(&commit_name);
615 repo_format_commit_message(the_repository, commit, "%s",
616 &commit_name, &pp);
617 fprintf(fp, "# possible first %s commit: [%s] %s\n",
618 terms->term_bad, oid_to_hex(&commit->object.oid),
619 commit_name.buf);
623 * Reset the flags used by revision walks in case
624 * there is another revision walk after this one.
626 reset_revision_walk();
628 strbuf_release(&commit_name);
629 release_revisions(&revs);
630 fclose(fp);
631 return 0;
634 static int bisect_successful(struct bisect_terms *terms)
636 struct object_id oid;
637 struct commit *commit;
638 struct pretty_print_context pp = {0};
639 struct strbuf commit_name = STRBUF_INIT;
640 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
641 int res;
643 refs_read_ref(get_main_ref_store(the_repository), bad_ref, &oid);
644 commit = lookup_commit_reference_by_name(bad_ref);
645 repo_format_commit_message(the_repository, commit, "%s", &commit_name,
646 &pp);
648 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
649 terms->term_bad, oid_to_hex(&commit->object.oid),
650 commit_name.buf);
652 strbuf_release(&commit_name);
653 free(bad_ref);
654 return res;
657 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
659 enum bisect_error res;
661 if (bisect_autostart(terms))
662 return BISECT_FAILED;
664 if (bisect_next_check(terms, terms->term_good))
665 return BISECT_FAILED;
667 /* Perform all bisection computation */
668 res = bisect_next_all(the_repository, prefix);
670 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
671 res = bisect_successful(terms);
672 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
673 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
674 res = bisect_skipped_commits(terms);
675 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
677 return res;
680 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
682 if (bisect_next_check(terms, NULL)) {
683 bisect_print_status(terms);
684 return BISECT_OK;
687 return bisect_next(terms, prefix);
690 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
691 const char **argv)
693 int no_checkout = 0;
694 int first_parent_only = 0;
695 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
696 int flags, pathspec_pos;
697 enum bisect_error res = BISECT_OK;
698 struct string_list revs = STRING_LIST_INIT_DUP;
699 struct string_list states = STRING_LIST_INIT_DUP;
700 struct strbuf start_head = STRBUF_INIT;
701 struct strbuf bisect_names = STRBUF_INIT;
702 struct object_id head_oid;
703 struct object_id oid;
704 const char *head;
706 if (is_bare_repository())
707 no_checkout = 1;
710 * Check for one bad and then some good revisions
712 for (i = 0; i < argc; i++) {
713 if (!strcmp(argv[i], "--")) {
714 has_double_dash = 1;
715 break;
719 for (i = 0; i < argc; i++) {
720 const char *arg = argv[i];
721 if (!strcmp(argv[i], "--")) {
722 break;
723 } else if (!strcmp(arg, "--no-checkout")) {
724 no_checkout = 1;
725 } else if (!strcmp(arg, "--first-parent")) {
726 first_parent_only = 1;
727 } else if (!strcmp(arg, "--term-good") ||
728 !strcmp(arg, "--term-old")) {
729 i++;
730 if (argc <= i)
731 return error(_("'' is not a valid term"));
732 must_write_terms = 1;
733 free((void *) terms->term_good);
734 terms->term_good = xstrdup(argv[i]);
735 } else if (skip_prefix(arg, "--term-good=", &arg) ||
736 skip_prefix(arg, "--term-old=", &arg)) {
737 must_write_terms = 1;
738 free((void *) terms->term_good);
739 terms->term_good = xstrdup(arg);
740 } else if (!strcmp(arg, "--term-bad") ||
741 !strcmp(arg, "--term-new")) {
742 i++;
743 if (argc <= i)
744 return error(_("'' is not a valid term"));
745 must_write_terms = 1;
746 free((void *) terms->term_bad);
747 terms->term_bad = xstrdup(argv[i]);
748 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
749 skip_prefix(arg, "--term-new=", &arg)) {
750 must_write_terms = 1;
751 free((void *) terms->term_bad);
752 terms->term_bad = xstrdup(arg);
753 } else if (starts_with(arg, "--")) {
754 return error(_("unrecognized option: '%s'"), arg);
755 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
756 string_list_append(&revs, oid_to_hex(&oid));
757 } else if (has_double_dash) {
758 die(_("'%s' does not appear to be a valid "
759 "revision"), arg);
760 } else {
761 break;
764 pathspec_pos = i;
767 * The user ran "git bisect start <sha1> <sha1>", hence did not
768 * explicitly specify the terms, but we are already starting to
769 * set references named with the default terms, and won't be able
770 * to change afterwards.
772 if (revs.nr)
773 must_write_terms = 1;
774 for (i = 0; i < revs.nr; i++) {
775 if (bad_seen) {
776 string_list_append(&states, terms->term_good);
777 } else {
778 bad_seen = 1;
779 string_list_append(&states, terms->term_bad);
784 * Verify HEAD
786 head = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
787 "HEAD", 0, &head_oid, &flags);
788 if (!head)
789 if (repo_get_oid(the_repository, "HEAD", &head_oid))
790 return error(_("bad HEAD - I need a HEAD"));
793 * Check if we are bisecting
795 if (!is_empty_or_missing_file(git_path_bisect_start())) {
796 /* Reset to the rev from where we started */
797 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
798 strbuf_trim(&start_head);
799 if (!no_checkout) {
800 struct child_process cmd = CHILD_PROCESS_INIT;
802 cmd.git_cmd = 1;
803 strvec_pushl(&cmd.args, "checkout", start_head.buf,
804 "--", NULL);
805 if (run_command(&cmd)) {
806 res = error(_("checking out '%s' failed."
807 " Try 'git bisect start "
808 "<valid-branch>'."),
809 start_head.buf);
810 goto finish;
813 } else {
814 /* Get the rev from where we start. */
815 if (!repo_get_oid(the_repository, head, &head_oid) &&
816 !starts_with(head, "refs/heads/")) {
817 strbuf_reset(&start_head);
818 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
819 } else if (!repo_get_oid(the_repository, head, &head_oid) &&
820 skip_prefix(head, "refs/heads/", &head)) {
821 strbuf_addstr(&start_head, head);
822 } else {
823 return error(_("bad HEAD - strange symbolic ref"));
828 * Get rid of any old bisect state.
830 if (bisect_clean_state())
831 return BISECT_FAILED;
834 * Write new start state
836 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
838 if (first_parent_only)
839 write_file(git_path_bisect_first_parent(), "\n");
841 if (no_checkout) {
842 if (repo_get_oid(the_repository, start_head.buf, &oid) < 0) {
843 res = error(_("invalid ref: '%s'"), start_head.buf);
844 goto finish;
846 if (refs_update_ref(get_main_ref_store(the_repository), NULL, "BISECT_HEAD", &oid, NULL, 0,
847 UPDATE_REFS_MSG_ON_ERR)) {
848 res = BISECT_FAILED;
849 goto finish;
853 if (pathspec_pos < argc - 1)
854 sq_quote_argv(&bisect_names, argv + pathspec_pos);
855 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
857 for (i = 0; i < states.nr; i++)
858 if (bisect_write(states.items[i].string,
859 revs.items[i].string, terms, 1)) {
860 res = BISECT_FAILED;
861 goto finish;
864 if (must_write_terms && write_terms(terms->term_bad,
865 terms->term_good)) {
866 res = BISECT_FAILED;
867 goto finish;
870 res = bisect_append_log_quoted(argv);
871 if (res)
872 res = BISECT_FAILED;
874 finish:
875 string_list_clear(&revs, 0);
876 string_list_clear(&states, 0);
877 strbuf_release(&start_head);
878 strbuf_release(&bisect_names);
879 if (res)
880 return res;
882 res = bisect_auto_next(terms, NULL);
883 if (!is_bisect_success(res))
884 bisect_clean_state();
885 return res;
888 static inline int file_is_not_empty(const char *path)
890 return !is_empty_or_missing_file(path);
893 static int bisect_autostart(struct bisect_terms *terms)
895 int res;
896 const char *yesno;
898 if (file_is_not_empty(git_path_bisect_start()))
899 return 0;
901 fprintf_ln(stderr, _("You need to start by \"git bisect "
902 "start\"\n"));
904 if (!isatty(STDIN_FILENO))
905 return -1;
908 * TRANSLATORS: Make sure to include [Y] and [n] in your
909 * translation. The program will only accept English input
910 * at this point.
912 yesno = git_prompt(_("Do you want me to do it for you "
913 "[Y/n]? "), PROMPT_ECHO);
914 res = tolower(*yesno) == 'n' ?
915 -1 : bisect_start(terms, 0, empty_strvec);
917 return res;
920 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
921 const char **argv)
923 const char *state;
924 int i, verify_expected = 1;
925 struct object_id oid, expected;
926 struct oid_array revs = OID_ARRAY_INIT;
928 if (!argc)
929 return error(_("Please call `--bisect-state` with at least one argument"));
931 if (bisect_autostart(terms))
932 return BISECT_FAILED;
934 state = argv[0];
935 if (check_and_set_terms(terms, state) ||
936 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
937 return BISECT_FAILED;
939 argv++;
940 argc--;
941 if (argc > 1 && !strcmp(state, terms->term_bad))
942 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
944 if (argc == 0) {
945 const char *head = "BISECT_HEAD";
946 enum get_oid_result res_head = repo_get_oid(the_repository,
947 head, &oid);
949 if (res_head == MISSING_OBJECT) {
950 head = "HEAD";
951 res_head = repo_get_oid(the_repository, head, &oid);
954 if (res_head)
955 error(_("Bad rev input: %s"), head);
956 oid_array_append(&revs, &oid);
960 * All input revs must be checked before executing bisect_write()
961 * to discard junk revs.
964 for (; argc; argc--, argv++) {
965 struct commit *commit;
967 if (repo_get_oid(the_repository, *argv, &oid)){
968 error(_("Bad rev input: %s"), *argv);
969 oid_array_clear(&revs);
970 return BISECT_FAILED;
973 commit = lookup_commit_reference(the_repository, &oid);
974 if (!commit)
975 die(_("Bad rev input (not a commit): %s"), *argv);
977 oid_array_append(&revs, &commit->object.oid);
980 if (refs_read_ref(get_main_ref_store(the_repository), "BISECT_EXPECTED_REV", &expected))
981 verify_expected = 0; /* Ignore invalid file contents */
983 for (i = 0; i < revs.nr; i++) {
984 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
985 oid_array_clear(&revs);
986 return BISECT_FAILED;
988 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
989 unlink_or_warn(git_path_bisect_ancestors_ok());
990 refs_delete_ref(get_main_ref_store(the_repository),
991 NULL, "BISECT_EXPECTED_REV", NULL,
992 REF_NO_DEREF);
993 verify_expected = 0;
997 oid_array_clear(&revs);
998 return bisect_auto_next(terms, NULL);
1001 static enum bisect_error bisect_log(void)
1003 int fd, status;
1004 const char* filename = git_path_bisect_log();
1006 if (is_empty_or_missing_file(filename))
1007 return error(_("We are not bisecting."));
1009 fd = open(filename, O_RDONLY);
1010 if (fd < 0)
1011 return BISECT_FAILED;
1013 status = copy_fd(fd, STDOUT_FILENO);
1014 close(fd);
1015 return status ? BISECT_FAILED : BISECT_OK;
1018 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1020 const char *p = line->buf + strspn(line->buf, " \t");
1021 char *word_end, *rev;
1023 if ((!skip_prefix(p, "git bisect", &p) &&
1024 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1025 return 0;
1026 p += strspn(p, " \t");
1028 word_end = (char *)p + strcspn(p, " \t");
1029 rev = word_end + strspn(word_end, " \t");
1030 *word_end = '\0'; /* NUL-terminate the word */
1032 get_terms(terms);
1033 if (check_and_set_terms(terms, p))
1034 return -1;
1036 if (!strcmp(p, "start")) {
1037 struct strvec argv = STRVEC_INIT;
1038 int res;
1039 sq_dequote_to_strvec(rev, &argv);
1040 res = bisect_start(terms, argv.nr, argv.v);
1041 strvec_clear(&argv);
1042 return res;
1045 if (one_of(p, terms->term_good,
1046 terms->term_bad, "skip", NULL))
1047 return bisect_write(p, rev, terms, 0);
1049 if (!strcmp(p, "terms")) {
1050 struct strvec argv = STRVEC_INIT;
1051 int res;
1052 sq_dequote_to_strvec(rev, &argv);
1053 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1054 strvec_clear(&argv);
1055 return res;
1057 error(_("'%s'?? what are you talking about?"), p);
1059 return -1;
1062 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1064 FILE *fp = NULL;
1065 enum bisect_error res = BISECT_OK;
1066 struct strbuf line = STRBUF_INIT;
1068 if (is_empty_or_missing_file(filename))
1069 return error(_("cannot read file '%s' for replaying"), filename);
1071 if (bisect_reset(NULL))
1072 return BISECT_FAILED;
1074 fp = fopen(filename, "r");
1075 if (!fp)
1076 return BISECT_FAILED;
1078 while ((strbuf_getline(&line, fp) != EOF) && !res)
1079 res = process_replay_line(terms, &line);
1081 strbuf_release(&line);
1082 fclose(fp);
1084 if (res)
1085 return BISECT_FAILED;
1087 return bisect_auto_next(terms, NULL);
1090 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1091 const char **argv)
1093 int i;
1094 enum bisect_error res;
1095 struct strvec argv_state = STRVEC_INIT;
1097 strvec_push(&argv_state, "skip");
1099 for (i = 0; i < argc; i++) {
1100 const char *dotdot = strstr(argv[i], "..");
1102 if (dotdot) {
1103 struct rev_info revs;
1104 struct commit *commit;
1106 repo_init_revisions(the_repository, &revs, NULL);
1107 setup_revisions(2, argv + i - 1, &revs, NULL);
1109 if (prepare_revision_walk(&revs))
1110 die(_("revision walk setup failed\n"));
1111 while ((commit = get_revision(&revs)) != NULL)
1112 strvec_push(&argv_state,
1113 oid_to_hex(&commit->object.oid));
1115 reset_revision_walk();
1116 release_revisions(&revs);
1117 } else {
1118 strvec_push(&argv_state, argv[i]);
1121 res = bisect_state(terms, argv_state.nr, argv_state.v);
1123 strvec_clear(&argv_state);
1124 return res;
1127 static int bisect_visualize(struct bisect_terms *terms, int argc,
1128 const char **argv)
1130 struct child_process cmd = CHILD_PROCESS_INIT;
1131 struct strbuf sb = STRBUF_INIT;
1133 if (bisect_next_check(terms, NULL) != 0)
1134 return BISECT_FAILED;
1136 cmd.no_stdin = 1;
1137 if (!argc) {
1138 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1139 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1140 strvec_push(&cmd.args, "gitk");
1141 } else {
1142 strvec_push(&cmd.args, "log");
1143 cmd.git_cmd = 1;
1145 } else {
1146 if (argv[0][0] == '-') {
1147 strvec_push(&cmd.args, "log");
1148 cmd.git_cmd = 1;
1149 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1150 cmd.git_cmd = 1;
1152 strvec_pushv(&cmd.args, argv);
1155 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1157 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1158 sq_dequote_to_strvec(sb.buf, &cmd.args);
1159 strbuf_release(&sb);
1161 return run_command(&cmd);
1164 static int get_first_good(const char *refname UNUSED,
1165 const struct object_id *oid,
1166 int flag UNUSED, void *cb_data)
1168 oidcpy(cb_data, oid);
1169 return 1;
1172 static int do_bisect_run(const char *command)
1174 struct child_process cmd = CHILD_PROCESS_INIT;
1176 printf(_("running %s\n"), command);
1177 cmd.use_shell = 1;
1178 strvec_push(&cmd.args, command);
1179 return run_command(&cmd);
1182 static int verify_good(const struct bisect_terms *terms, const char *command)
1184 int rc;
1185 enum bisect_error res;
1186 struct object_id good_rev;
1187 struct object_id current_rev;
1188 char *good_glob = xstrfmt("%s-*", terms->term_good);
1189 int no_checkout = refs_ref_exists(get_main_ref_store(the_repository),
1190 "BISECT_HEAD");
1192 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
1193 get_first_good, good_glob, "refs/bisect/",
1194 &good_rev);
1195 free(good_glob);
1197 if (refs_read_ref(get_main_ref_store(the_repository), no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1198 return -1;
1200 res = bisect_checkout(&good_rev, no_checkout);
1201 if (res != BISECT_OK)
1202 return -1;
1204 rc = do_bisect_run(command);
1206 res = bisect_checkout(&current_rev, no_checkout);
1207 if (res != BISECT_OK)
1208 return -1;
1210 return rc;
1213 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1215 int res = BISECT_OK;
1216 struct strbuf command = STRBUF_INIT;
1217 const char *new_state;
1218 int temporary_stdout_fd, saved_stdout;
1219 int is_first_run = 1;
1221 if (bisect_next_check(terms, NULL))
1222 return BISECT_FAILED;
1224 if (!argc) {
1225 error(_("bisect run failed: no command provided."));
1226 return BISECT_FAILED;
1229 sq_quote_argv(&command, argv);
1230 strbuf_ltrim(&command);
1231 while (1) {
1232 res = do_bisect_run(command.buf);
1235 * Exit code 126 and 127 can either come from the shell
1236 * if it was unable to execute or even find the script,
1237 * or from the script itself. Check with a known-good
1238 * revision to avoid trashing the bisect run due to a
1239 * missing or non-executable script.
1241 if (is_first_run && (res == 126 || res == 127)) {
1242 int rc = verify_good(terms, command.buf);
1243 is_first_run = 0;
1244 if (rc < 0 || 128 <= rc) {
1245 error(_("unable to verify %s on good"
1246 " revision"), command.buf);
1247 res = BISECT_FAILED;
1248 break;
1250 if (rc == res) {
1251 error(_("bogus exit code %d for good revision"),
1252 rc);
1253 res = BISECT_FAILED;
1254 break;
1258 if (res < 0 || 128 <= res) {
1259 error(_("bisect run failed: exit code %d from"
1260 " %s is < 0 or >= 128"), res, command.buf);
1261 break;
1264 if (res == 125)
1265 new_state = "skip";
1266 else if (!res)
1267 new_state = terms->term_good;
1268 else
1269 new_state = terms->term_bad;
1271 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1273 if (temporary_stdout_fd < 0) {
1274 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1275 break;
1278 fflush(stdout);
1279 saved_stdout = dup(1);
1280 dup2(temporary_stdout_fd, 1);
1282 res = bisect_state(terms, 1, &new_state);
1284 fflush(stdout);
1285 dup2(saved_stdout, 1);
1286 close(saved_stdout);
1287 close(temporary_stdout_fd);
1289 print_file_to_stdout(git_path_bisect_run());
1291 if (res == BISECT_ONLY_SKIPPED_LEFT)
1292 error(_("bisect run cannot continue any more"));
1293 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1294 puts(_("bisect run success"));
1295 res = BISECT_OK;
1296 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1297 puts(_("bisect found first bad commit"));
1298 res = BISECT_OK;
1299 } else if (res) {
1300 error(_("bisect run failed: 'git bisect %s'"
1301 " exited with error code %d"), new_state, res);
1302 } else {
1303 continue;
1305 break;
1308 strbuf_release(&command);
1309 return res;
1312 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1314 if (argc > 1)
1315 return error(_("'%s' requires either no argument or a commit"),
1316 "git bisect reset");
1317 return bisect_reset(argc ? argv[0] : NULL);
1320 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1322 int res;
1323 struct bisect_terms terms = { 0 };
1325 if (argc > 1)
1326 return error(_("'%s' requires 0 or 1 argument"),
1327 "git bisect terms");
1328 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1329 free_terms(&terms);
1330 return res;
1333 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1335 int res;
1336 struct bisect_terms terms = { 0 };
1338 set_terms(&terms, "bad", "good");
1339 res = bisect_start(&terms, argc, argv);
1340 free_terms(&terms);
1341 return res;
1344 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1346 int res;
1347 struct bisect_terms terms = { 0 };
1349 if (argc)
1350 return error(_("'%s' requires 0 arguments"),
1351 "git bisect next");
1352 get_terms(&terms);
1353 res = bisect_next(&terms, prefix);
1354 free_terms(&terms);
1355 return res;
1358 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1360 return bisect_log();
1363 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1365 int res;
1366 struct bisect_terms terms = { 0 };
1368 if (argc != 1)
1369 return error(_("no logfile given"));
1370 set_terms(&terms, "bad", "good");
1371 res = bisect_replay(&terms, argv[0]);
1372 free_terms(&terms);
1373 return res;
1376 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1378 int res;
1379 struct bisect_terms terms = { 0 };
1381 set_terms(&terms, "bad", "good");
1382 get_terms(&terms);
1383 res = bisect_skip(&terms, argc, argv);
1384 free_terms(&terms);
1385 return res;
1388 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1390 int res;
1391 struct bisect_terms terms = { 0 };
1393 get_terms(&terms);
1394 res = bisect_visualize(&terms, argc, argv);
1395 free_terms(&terms);
1396 return res;
1399 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1401 int res;
1402 struct bisect_terms terms = { 0 };
1404 if (!argc)
1405 return error(_("'%s' failed: no command provided."), "git bisect run");
1406 get_terms(&terms);
1407 res = bisect_run(&terms, argc, argv);
1408 free_terms(&terms);
1409 return res;
1412 int cmd_bisect(int argc, const char **argv, const char *prefix)
1414 int res = 0;
1415 parse_opt_subcommand_fn *fn = NULL;
1416 struct option options[] = {
1417 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1418 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1419 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1420 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1421 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1422 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1423 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1424 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1425 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1426 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1427 OPT_END()
1429 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1430 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1432 if (!fn) {
1433 struct bisect_terms terms = { 0 };
1435 if (!argc)
1436 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1438 set_terms(&terms, "bad", "good");
1439 get_terms(&terms);
1440 if (check_and_set_terms(&terms, argv[0]))
1441 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1442 options, argv[0]);
1443 res = bisect_state(&terms, argc, argv);
1444 free_terms(&terms);
1445 } else {
1446 argc--;
1447 argv++;
1448 res = fn(argc, argv, prefix);
1451 return is_bisect_success(res) ? 0 : -res;