Merge branch 'jk/commit-use-no-divider-with-interpret-trailers'
[alt-git.git] / builtin / bisect.c
blob4812450c393da3e2df36521c5f0295ad48e65fe2
1 #include "builtin.h"
2 #include "cache.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "object-name.h"
8 #include "parse-options.h"
9 #include "bisect.h"
10 #include "refs.h"
11 #include "dir.h"
12 #include "strvec.h"
13 #include "run-command.h"
14 #include "oid-array.h"
15 #include "prompt.h"
16 #include "quote.h"
17 #include "revision.h"
18 #include "wrapper.h"
20 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
21 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
22 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
23 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
24 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
25 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
26 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
27 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
29 #define BUILTIN_GIT_BISECT_START_USAGE \
30 N_("git bisect start [--term-{new,bad}=<term> --term-{old,good}=<term>]" \
31 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
32 " [<pathspec>...]")
33 #define BUILTIN_GIT_BISECT_STATE_USAGE \
34 N_("git bisect (good|bad) [<rev>...]")
35 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
36 "git bisect terms [--term-good | --term-bad]"
37 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
38 N_("git bisect skip [(<rev>|<range>)...]")
39 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
40 "git bisect next"
41 #define BUILTIN_GIT_BISECT_RESET_USAGE \
42 N_("git bisect reset [<commit>]")
43 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
44 "git bisect visualize"
45 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
46 N_("git bisect replay <logfile>")
47 #define BUILTIN_GIT_BISECT_LOG_USAGE \
48 "git bisect log"
49 #define BUILTIN_GIT_BISECT_RUN_USAGE \
50 N_("git bisect run <cmd>...")
52 static const char * const git_bisect_usage[] = {
53 BUILTIN_GIT_BISECT_START_USAGE,
54 BUILTIN_GIT_BISECT_STATE_USAGE,
55 BUILTIN_GIT_BISECT_TERMS_USAGE,
56 BUILTIN_GIT_BISECT_SKIP_USAGE,
57 BUILTIN_GIT_BISECT_NEXT_USAGE,
58 BUILTIN_GIT_BISECT_RESET_USAGE,
59 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
60 BUILTIN_GIT_BISECT_REPLAY_USAGE,
61 BUILTIN_GIT_BISECT_LOG_USAGE,
62 BUILTIN_GIT_BISECT_RUN_USAGE,
63 NULL
66 struct add_bisect_ref_data {
67 struct rev_info *revs;
68 unsigned int object_flags;
71 struct bisect_terms {
72 char *term_good;
73 char *term_bad;
76 static void free_terms(struct bisect_terms *terms)
78 FREE_AND_NULL(terms->term_good);
79 FREE_AND_NULL(terms->term_bad);
82 static void set_terms(struct bisect_terms *terms, const char *bad,
83 const char *good)
85 free((void *)terms->term_good);
86 terms->term_good = xstrdup(good);
87 free((void *)terms->term_bad);
88 terms->term_bad = xstrdup(bad);
91 static const char vocab_bad[] = "bad|new";
92 static const char vocab_good[] = "good|old";
94 static int bisect_autostart(struct bisect_terms *terms);
97 * Check whether the string `term` belongs to the set of strings
98 * included in the variable arguments.
100 LAST_ARG_MUST_BE_NULL
101 static int one_of(const char *term, ...)
103 int res = 0;
104 va_list matches;
105 const char *match;
107 va_start(matches, term);
108 while (!res && (match = va_arg(matches, const char *)))
109 res = !strcmp(term, match);
110 va_end(matches);
112 return res;
116 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
117 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
118 * that indicate special success.
121 static int is_bisect_success(enum bisect_error res)
123 return !res ||
124 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
125 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
128 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
130 FILE *fp = NULL;
131 int res = 0;
133 if (strcmp(mode, "w") && strcmp(mode, "a"))
134 BUG("write-in-file does not support '%s' mode", mode);
135 fp = fopen(path, mode);
136 if (!fp)
137 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
138 res = vfprintf(fp, format, args);
140 if (res < 0) {
141 int saved_errno = errno;
142 fclose(fp);
143 errno = saved_errno;
144 return error_errno(_("could not write to file '%s'"), path);
147 return fclose(fp);
150 __attribute__((format (printf, 2, 3)))
151 static int write_to_file(const char *path, const char *format, ...)
153 int res;
154 va_list args;
156 va_start(args, format);
157 res = write_in_file(path, "w", format, args);
158 va_end(args);
160 return res;
163 __attribute__((format (printf, 2, 3)))
164 static int append_to_file(const char *path, const char *format, ...)
166 int res;
167 va_list args;
169 va_start(args, format);
170 res = write_in_file(path, "a", format, args);
171 va_end(args);
173 return res;
176 static int print_file_to_stdout(const char *path)
178 int fd = open(path, O_RDONLY);
179 int ret = 0;
181 if (fd < 0)
182 return error_errno(_("cannot open file '%s' for reading"), path);
183 if (copy_fd(fd, 1) < 0)
184 ret = error_errno(_("failed to read '%s'"), path);
185 close(fd);
186 return ret;
189 static int check_term_format(const char *term, const char *orig_term)
191 int res;
192 char *new_term = xstrfmt("refs/bisect/%s", term);
194 res = check_refname_format(new_term, 0);
195 free(new_term);
197 if (res)
198 return error(_("'%s' is not a valid term"), term);
200 if (one_of(term, "help", "start", "skip", "next", "reset",
201 "visualize", "view", "replay", "log", "run", "terms", NULL))
202 return error(_("can't use the builtin command '%s' as a term"), term);
205 * In theory, nothing prevents swapping completely good and bad,
206 * but this situation could be confusing and hasn't been tested
207 * enough. Forbid it for now.
210 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
211 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
212 return error(_("can't change the meaning of the term '%s'"), term);
214 return 0;
217 static int write_terms(const char *bad, const char *good)
219 int res;
221 if (!strcmp(bad, good))
222 return error(_("please use two different terms"));
224 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
225 return -1;
227 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
229 return res;
232 static int bisect_reset(const char *commit)
234 struct strbuf branch = STRBUF_INIT;
236 if (!commit) {
237 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
238 printf(_("We are not bisecting.\n"));
239 return 0;
241 strbuf_rtrim(&branch);
242 } else {
243 struct object_id oid;
245 if (repo_get_oid_commit(the_repository, commit, &oid))
246 return error(_("'%s' is not a valid commit"), commit);
247 strbuf_addstr(&branch, commit);
250 if (!ref_exists("BISECT_HEAD")) {
251 struct child_process cmd = CHILD_PROCESS_INIT;
253 cmd.git_cmd = 1;
254 strvec_pushl(&cmd.args, "checkout", "--ignore-other-worktrees",
255 branch.buf, "--", NULL);
256 if (run_command(&cmd)) {
257 error(_("could not check out original"
258 " HEAD '%s'. Try 'git bisect"
259 " reset <commit>'."), branch.buf);
260 strbuf_release(&branch);
261 return -1;
265 strbuf_release(&branch);
266 return bisect_clean_state();
269 static void log_commit(FILE *fp, char *fmt, const char *state,
270 struct commit *commit)
272 struct pretty_print_context pp = {0};
273 struct strbuf commit_msg = STRBUF_INIT;
274 char *label = xstrfmt(fmt, state);
276 repo_format_commit_message(the_repository, commit, "%s", &commit_msg,
277 &pp);
279 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
280 commit_msg.buf);
282 strbuf_release(&commit_msg);
283 free(label);
286 static int bisect_write(const char *state, const char *rev,
287 const struct bisect_terms *terms, int nolog)
289 struct strbuf tag = STRBUF_INIT;
290 struct object_id oid;
291 struct commit *commit;
292 FILE *fp = NULL;
293 int res = 0;
295 if (!strcmp(state, terms->term_bad)) {
296 strbuf_addf(&tag, "refs/bisect/%s", state);
297 } else if (one_of(state, terms->term_good, "skip", NULL)) {
298 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
299 } else {
300 res = error(_("Bad bisect_write argument: %s"), state);
301 goto finish;
304 if (repo_get_oid(the_repository, rev, &oid)) {
305 res = error(_("couldn't get the oid of the rev '%s'"), rev);
306 goto finish;
309 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
310 UPDATE_REFS_MSG_ON_ERR)) {
311 res = -1;
312 goto finish;
315 fp = fopen(git_path_bisect_log(), "a");
316 if (!fp) {
317 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
318 goto finish;
321 commit = lookup_commit_reference(the_repository, &oid);
322 log_commit(fp, "%s", state, commit);
324 if (!nolog)
325 fprintf(fp, "git bisect %s %s\n", state, rev);
327 finish:
328 if (fp)
329 fclose(fp);
330 strbuf_release(&tag);
331 return res;
334 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
336 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
338 if (one_of(cmd, "skip", "start", "terms", NULL))
339 return 0;
341 if (has_term_file && strcmp(cmd, terms->term_bad) &&
342 strcmp(cmd, terms->term_good))
343 return error(_("Invalid command: you're currently in a "
344 "%s/%s bisect"), terms->term_bad,
345 terms->term_good);
347 if (!has_term_file) {
348 if (one_of(cmd, "bad", "good", NULL)) {
349 set_terms(terms, "bad", "good");
350 return write_terms(terms->term_bad, terms->term_good);
352 if (one_of(cmd, "new", "old", NULL)) {
353 set_terms(terms, "new", "old");
354 return write_terms(terms->term_bad, terms->term_good);
358 return 0;
361 static int inc_nr(const char *refname UNUSED,
362 const struct object_id *oid UNUSED,
363 int flag UNUSED, void *cb_data)
365 unsigned int *nr = (unsigned int *)cb_data;
366 (*nr)++;
367 return 0;
370 static const char need_bad_and_good_revision_warning[] =
371 N_("You need to give me at least one %s and %s revision.\n"
372 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
374 static const char need_bisect_start_warning[] =
375 N_("You need to start by \"git bisect start\".\n"
376 "You then need to give me at least one %s and %s revision.\n"
377 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
379 static int decide_next(const struct bisect_terms *terms,
380 const char *current_term, int missing_good,
381 int missing_bad)
383 if (!missing_good && !missing_bad)
384 return 0;
385 if (!current_term)
386 return -1;
388 if (missing_good && !missing_bad &&
389 !strcmp(current_term, terms->term_good)) {
390 char *yesno;
392 * have bad (or new) but not good (or old). We could bisect
393 * although this is less optimum.
395 warning(_("bisecting only with a %s commit"), terms->term_bad);
396 if (!isatty(0))
397 return 0;
399 * TRANSLATORS: Make sure to include [Y] and [n] in your
400 * translation. The program will only accept English input
401 * at this point.
403 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
404 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
405 return -1;
406 return 0;
409 if (!is_empty_or_missing_file(git_path_bisect_start()))
410 return error(_(need_bad_and_good_revision_warning),
411 vocab_bad, vocab_good, vocab_bad, vocab_good);
412 else
413 return error(_(need_bisect_start_warning),
414 vocab_good, vocab_bad, vocab_good, vocab_bad);
417 static void bisect_status(struct bisect_state *state,
418 const struct bisect_terms *terms)
420 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
421 char *good_glob = xstrfmt("%s-*", terms->term_good);
423 if (ref_exists(bad_ref))
424 state->nr_bad = 1;
426 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
427 (void *) &state->nr_good);
429 free(good_glob);
430 free(bad_ref);
433 __attribute__((format (printf, 1, 2)))
434 static void bisect_log_printf(const char *fmt, ...)
436 struct strbuf buf = STRBUF_INIT;
437 va_list ap;
439 va_start(ap, fmt);
440 strbuf_vaddf(&buf, fmt, ap);
441 va_end(ap);
443 printf("%s", buf.buf);
444 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
446 strbuf_release(&buf);
449 static void bisect_print_status(const struct bisect_terms *terms)
451 struct bisect_state state = { 0 };
453 bisect_status(&state, terms);
455 /* If we had both, we'd already be started, and shouldn't get here. */
456 if (state.nr_good && state.nr_bad)
457 return;
459 if (!state.nr_good && !state.nr_bad)
460 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
461 else if (state.nr_good)
462 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
463 "status: waiting for bad commit, %d good commits known\n",
464 state.nr_good), state.nr_good);
465 else
466 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
469 static int bisect_next_check(const struct bisect_terms *terms,
470 const char *current_term)
472 struct bisect_state state = { 0 };
473 bisect_status(&state, terms);
474 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
477 static int get_terms(struct bisect_terms *terms)
479 struct strbuf str = STRBUF_INIT;
480 FILE *fp = NULL;
481 int res = 0;
483 fp = fopen(git_path_bisect_terms(), "r");
484 if (!fp) {
485 res = -1;
486 goto finish;
489 free_terms(terms);
490 strbuf_getline_lf(&str, fp);
491 terms->term_bad = strbuf_detach(&str, NULL);
492 strbuf_getline_lf(&str, fp);
493 terms->term_good = strbuf_detach(&str, NULL);
495 finish:
496 if (fp)
497 fclose(fp);
498 strbuf_release(&str);
499 return res;
502 static int bisect_terms(struct bisect_terms *terms, const char *option)
504 if (get_terms(terms))
505 return error(_("no terms defined"));
507 if (!option) {
508 printf(_("Your current terms are %s for the old state\n"
509 "and %s for the new state.\n"),
510 terms->term_good, terms->term_bad);
511 return 0;
513 if (one_of(option, "--term-good", "--term-old", NULL))
514 printf("%s\n", terms->term_good);
515 else if (one_of(option, "--term-bad", "--term-new", NULL))
516 printf("%s\n", terms->term_bad);
517 else
518 return error(_("invalid argument %s for 'git bisect terms'.\n"
519 "Supported options are: "
520 "--term-good|--term-old and "
521 "--term-bad|--term-new."), option);
523 return 0;
526 static int bisect_append_log_quoted(const char **argv)
528 int res = 0;
529 FILE *fp = fopen(git_path_bisect_log(), "a");
530 struct strbuf orig_args = STRBUF_INIT;
532 if (!fp)
533 return -1;
535 if (fprintf(fp, "git bisect start") < 1) {
536 res = -1;
537 goto finish;
540 sq_quote_argv(&orig_args, argv);
541 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
542 res = -1;
544 finish:
545 fclose(fp);
546 strbuf_release(&orig_args);
547 return res;
550 static int add_bisect_ref(const char *refname, const struct object_id *oid,
551 int flags UNUSED, void *cb)
553 struct add_bisect_ref_data *data = cb;
555 add_pending_oid(data->revs, refname, oid, data->object_flags);
557 return 0;
560 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
562 int res = 0;
563 struct add_bisect_ref_data cb = { revs };
564 char *good = xstrfmt("%s-*", terms->term_good);
567 * We cannot use terms->term_bad directly in
568 * for_each_glob_ref_in() and we have to append a '*' to it,
569 * otherwise for_each_glob_ref_in() will append '/' and '*'.
571 char *bad = xstrfmt("%s*", terms->term_bad);
574 * It is important to reset the flags used by revision walks
575 * as the previous call to bisect_next_all() in turn
576 * sets up a revision walk.
578 reset_revision_walk();
579 repo_init_revisions(the_repository, revs, NULL);
580 setup_revisions(0, NULL, revs, NULL);
581 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
582 cb.object_flags = UNINTERESTING;
583 for_each_glob_ref_in(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 read_ref(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 = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
787 if (!head)
788 if (repo_get_oid(the_repository, "HEAD", &head_oid))
789 return error(_("bad HEAD - I need a HEAD"));
792 * Check if we are bisecting
794 if (!is_empty_or_missing_file(git_path_bisect_start())) {
795 /* Reset to the rev from where we started */
796 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
797 strbuf_trim(&start_head);
798 if (!no_checkout) {
799 struct child_process cmd = CHILD_PROCESS_INIT;
801 cmd.git_cmd = 1;
802 strvec_pushl(&cmd.args, "checkout", start_head.buf,
803 "--", NULL);
804 if (run_command(&cmd)) {
805 res = error(_("checking out '%s' failed."
806 " Try 'git bisect start "
807 "<valid-branch>'."),
808 start_head.buf);
809 goto finish;
812 } else {
813 /* Get the rev from where we start. */
814 if (!repo_get_oid(the_repository, head, &head_oid) &&
815 !starts_with(head, "refs/heads/")) {
816 strbuf_reset(&start_head);
817 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
818 } else if (!repo_get_oid(the_repository, head, &head_oid) &&
819 skip_prefix(head, "refs/heads/", &head)) {
820 strbuf_addstr(&start_head, head);
821 } else {
822 return error(_("bad HEAD - strange symbolic ref"));
827 * Get rid of any old bisect state.
829 if (bisect_clean_state())
830 return BISECT_FAILED;
833 * Write new start state
835 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
837 if (first_parent_only)
838 write_file(git_path_bisect_first_parent(), "\n");
840 if (no_checkout) {
841 if (repo_get_oid(the_repository, start_head.buf, &oid) < 0) {
842 res = error(_("invalid ref: '%s'"), start_head.buf);
843 goto finish;
845 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
846 UPDATE_REFS_MSG_ON_ERR)) {
847 res = BISECT_FAILED;
848 goto finish;
852 if (pathspec_pos < argc - 1)
853 sq_quote_argv(&bisect_names, argv + pathspec_pos);
854 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
856 for (i = 0; i < states.nr; i++)
857 if (bisect_write(states.items[i].string,
858 revs.items[i].string, terms, 1)) {
859 res = BISECT_FAILED;
860 goto finish;
863 if (must_write_terms && write_terms(terms->term_bad,
864 terms->term_good)) {
865 res = BISECT_FAILED;
866 goto finish;
869 res = bisect_append_log_quoted(argv);
870 if (res)
871 res = BISECT_FAILED;
873 finish:
874 string_list_clear(&revs, 0);
875 string_list_clear(&states, 0);
876 strbuf_release(&start_head);
877 strbuf_release(&bisect_names);
878 if (res)
879 return res;
881 res = bisect_auto_next(terms, NULL);
882 if (!is_bisect_success(res))
883 bisect_clean_state();
884 return res;
887 static inline int file_is_not_empty(const char *path)
889 return !is_empty_or_missing_file(path);
892 static int bisect_autostart(struct bisect_terms *terms)
894 int res;
895 const char *yesno;
897 if (file_is_not_empty(git_path_bisect_start()))
898 return 0;
900 fprintf_ln(stderr, _("You need to start by \"git bisect "
901 "start\"\n"));
903 if (!isatty(STDIN_FILENO))
904 return -1;
907 * TRANSLATORS: Make sure to include [Y] and [n] in your
908 * translation. The program will only accept English input
909 * at this point.
911 yesno = git_prompt(_("Do you want me to do it for you "
912 "[Y/n]? "), PROMPT_ECHO);
913 res = tolower(*yesno) == 'n' ?
914 -1 : bisect_start(terms, 0, empty_strvec);
916 return res;
919 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
920 const char **argv)
922 const char *state;
923 int i, verify_expected = 1;
924 struct object_id oid, expected;
925 struct strbuf buf = STRBUF_INIT;
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 (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
981 get_oid_hex(buf.buf, &expected) < 0)
982 verify_expected = 0; /* Ignore invalid file contents */
983 strbuf_release(&buf);
985 for (i = 0; i < revs.nr; i++) {
986 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
987 oid_array_clear(&revs);
988 return BISECT_FAILED;
990 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
991 unlink_or_warn(git_path_bisect_ancestors_ok());
992 unlink_or_warn(git_path_bisect_expected_rev());
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 = ref_exists("BISECT_HEAD");
1191 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1192 &good_rev);
1193 free(good_glob);
1195 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1196 return -1;
1198 res = bisect_checkout(&good_rev, no_checkout);
1199 if (res != BISECT_OK)
1200 return -1;
1202 rc = do_bisect_run(command);
1204 res = bisect_checkout(&current_rev, no_checkout);
1205 if (res != BISECT_OK)
1206 return -1;
1208 return rc;
1211 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1213 int res = BISECT_OK;
1214 struct strbuf command = STRBUF_INIT;
1215 const char *new_state;
1216 int temporary_stdout_fd, saved_stdout;
1217 int is_first_run = 1;
1219 if (bisect_next_check(terms, NULL))
1220 return BISECT_FAILED;
1222 if (!argc) {
1223 error(_("bisect run failed: no command provided."));
1224 return BISECT_FAILED;
1227 sq_quote_argv(&command, argv);
1228 strbuf_ltrim(&command);
1229 while (1) {
1230 res = do_bisect_run(command.buf);
1233 * Exit code 126 and 127 can either come from the shell
1234 * if it was unable to execute or even find the script,
1235 * or from the script itself. Check with a known-good
1236 * revision to avoid trashing the bisect run due to a
1237 * missing or non-executable script.
1239 if (is_first_run && (res == 126 || res == 127)) {
1240 int rc = verify_good(terms, command.buf);
1241 is_first_run = 0;
1242 if (rc < 0 || 128 <= rc) {
1243 error(_("unable to verify %s on good"
1244 " revision"), command.buf);
1245 res = BISECT_FAILED;
1246 break;
1248 if (rc == res) {
1249 error(_("bogus exit code %d for good revision"),
1250 rc);
1251 res = BISECT_FAILED;
1252 break;
1256 if (res < 0 || 128 <= res) {
1257 error(_("bisect run failed: exit code %d from"
1258 " %s is < 0 or >= 128"), res, command.buf);
1259 break;
1262 if (res == 125)
1263 new_state = "skip";
1264 else if (!res)
1265 new_state = terms->term_good;
1266 else
1267 new_state = terms->term_bad;
1269 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1271 if (temporary_stdout_fd < 0) {
1272 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1273 break;
1276 fflush(stdout);
1277 saved_stdout = dup(1);
1278 dup2(temporary_stdout_fd, 1);
1280 res = bisect_state(terms, 1, &new_state);
1282 fflush(stdout);
1283 dup2(saved_stdout, 1);
1284 close(saved_stdout);
1285 close(temporary_stdout_fd);
1287 print_file_to_stdout(git_path_bisect_run());
1289 if (res == BISECT_ONLY_SKIPPED_LEFT)
1290 error(_("bisect run cannot continue any more"));
1291 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1292 puts(_("bisect run success"));
1293 res = BISECT_OK;
1294 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1295 puts(_("bisect found first bad commit"));
1296 res = BISECT_OK;
1297 } else if (res) {
1298 error(_("bisect run failed: 'git bisect %s'"
1299 " exited with error code %d"), new_state, res);
1300 } else {
1301 continue;
1303 break;
1306 strbuf_release(&command);
1307 return res;
1310 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1312 if (argc > 1)
1313 return error(_("'%s' requires either no argument or a commit"),
1314 "git bisect reset");
1315 return bisect_reset(argc ? argv[0] : NULL);
1318 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1320 int res;
1321 struct bisect_terms terms = { 0 };
1323 if (argc > 1)
1324 return error(_("'%s' requires 0 or 1 argument"),
1325 "git bisect terms");
1326 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1327 free_terms(&terms);
1328 return res;
1331 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1333 int res;
1334 struct bisect_terms terms = { 0 };
1336 set_terms(&terms, "bad", "good");
1337 res = bisect_start(&terms, argc, argv);
1338 free_terms(&terms);
1339 return res;
1342 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1344 int res;
1345 struct bisect_terms terms = { 0 };
1347 if (argc)
1348 return error(_("'%s' requires 0 arguments"),
1349 "git bisect next");
1350 get_terms(&terms);
1351 res = bisect_next(&terms, prefix);
1352 free_terms(&terms);
1353 return res;
1356 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1358 return bisect_log();
1361 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1363 int res;
1364 struct bisect_terms terms = { 0 };
1366 if (argc != 1)
1367 return error(_("no logfile given"));
1368 set_terms(&terms, "bad", "good");
1369 res = bisect_replay(&terms, argv[0]);
1370 free_terms(&terms);
1371 return res;
1374 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1376 int res;
1377 struct bisect_terms terms = { 0 };
1379 set_terms(&terms, "bad", "good");
1380 get_terms(&terms);
1381 res = bisect_skip(&terms, argc, argv);
1382 free_terms(&terms);
1383 return res;
1386 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1388 int res;
1389 struct bisect_terms terms = { 0 };
1391 get_terms(&terms);
1392 res = bisect_visualize(&terms, argc, argv);
1393 free_terms(&terms);
1394 return res;
1397 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1399 int res;
1400 struct bisect_terms terms = { 0 };
1402 if (!argc)
1403 return error(_("'%s' failed: no command provided."), "git bisect run");
1404 get_terms(&terms);
1405 res = bisect_run(&terms, argc, argv);
1406 free_terms(&terms);
1407 return res;
1410 int cmd_bisect(int argc, const char **argv, const char *prefix)
1412 int res = 0;
1413 parse_opt_subcommand_fn *fn = NULL;
1414 struct option options[] = {
1415 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1416 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1417 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1418 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1419 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1420 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1421 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1422 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1423 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1424 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1425 OPT_END()
1427 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1428 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1430 if (!fn) {
1431 struct bisect_terms terms = { 0 };
1433 if (!argc)
1434 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1436 set_terms(&terms, "bad", "good");
1437 get_terms(&terms);
1438 if (check_and_set_terms(&terms, argv[0]))
1439 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1440 options, argv[0]);
1441 res = bisect_state(&terms, argc, argv);
1442 free_terms(&terms);
1443 } else {
1444 argc--;
1445 argv++;
1446 res = fn(argc, argv, prefix);
1449 return is_bisect_success(res) ? 0 : -res;