Clean up RelNotes for 2.48
[alt-git.git] / builtin / bisect.c
blob21d17a6c1a83e51fb82b53703b95d89bd9028830
1 #define USE_THE_REPOSITORY_VARIABLE
2 #include "builtin.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 "strvec.h"
12 #include "run-command.h"
13 #include "oid-array.h"
14 #include "path.h"
15 #include "prompt.h"
16 #include "quote.h"
17 #include "revision.h"
19 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
20 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
21 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
22 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
23 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
24 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
25 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
27 #define BUILTIN_GIT_BISECT_START_USAGE \
28 N_("git bisect start [--term-(new|bad)=<term> --term-(old|good)=<term>]" \
29 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
30 " [<pathspec>...]")
31 #define BUILTIN_GIT_BISECT_STATE_USAGE \
32 N_("git bisect (good|bad) [<rev>...]")
33 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
34 "git bisect terms [--term-good | --term-bad]"
35 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
36 N_("git bisect skip [(<rev>|<range>)...]")
37 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
38 "git bisect next"
39 #define BUILTIN_GIT_BISECT_RESET_USAGE \
40 N_("git bisect reset [<commit>]")
41 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
42 "git bisect visualize"
43 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
44 N_("git bisect replay <logfile>")
45 #define BUILTIN_GIT_BISECT_LOG_USAGE \
46 "git bisect log"
47 #define BUILTIN_GIT_BISECT_RUN_USAGE \
48 N_("git bisect run <cmd> [<arg>...]")
50 static const char * const git_bisect_usage[] = {
51 BUILTIN_GIT_BISECT_START_USAGE,
52 BUILTIN_GIT_BISECT_STATE_USAGE,
53 BUILTIN_GIT_BISECT_TERMS_USAGE,
54 BUILTIN_GIT_BISECT_SKIP_USAGE,
55 BUILTIN_GIT_BISECT_NEXT_USAGE,
56 BUILTIN_GIT_BISECT_RESET_USAGE,
57 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
58 BUILTIN_GIT_BISECT_REPLAY_USAGE,
59 BUILTIN_GIT_BISECT_LOG_USAGE,
60 BUILTIN_GIT_BISECT_RUN_USAGE,
61 NULL
64 struct add_bisect_ref_data {
65 struct rev_info *revs;
66 unsigned int object_flags;
69 struct bisect_terms {
70 char *term_good;
71 char *term_bad;
74 static void free_terms(struct bisect_terms *terms)
76 FREE_AND_NULL(terms->term_good);
77 FREE_AND_NULL(terms->term_bad);
80 static void set_terms(struct bisect_terms *terms, const char *bad,
81 const char *good)
83 free((void *)terms->term_good);
84 terms->term_good = xstrdup(good);
85 free((void *)terms->term_bad);
86 terms->term_bad = xstrdup(bad);
89 static const char vocab_bad[] = "bad|new";
90 static const char vocab_good[] = "good|old";
92 static int bisect_autostart(struct bisect_terms *terms);
95 * Check whether the string `term` belongs to the set of strings
96 * included in the variable arguments.
98 LAST_ARG_MUST_BE_NULL
99 static int one_of(const char *term, ...)
101 int res = 0;
102 va_list matches;
103 const char *match;
105 va_start(matches, term);
106 while (!res && (match = va_arg(matches, const char *)))
107 res = !strcmp(term, match);
108 va_end(matches);
110 return res;
114 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
115 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
116 * that indicate special success.
119 static int is_bisect_success(enum bisect_error res)
121 return !res ||
122 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
123 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
126 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
128 FILE *fp = NULL;
129 int res = 0;
131 if (strcmp(mode, "w") && strcmp(mode, "a"))
132 BUG("write-in-file does not support '%s' mode", mode);
133 fp = fopen(path, mode);
134 if (!fp)
135 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
136 res = vfprintf(fp, format, args);
138 if (res < 0) {
139 int saved_errno = errno;
140 fclose(fp);
141 errno = saved_errno;
142 return error_errno(_("could not write to file '%s'"), path);
145 return fclose(fp);
148 __attribute__((format (printf, 2, 3)))
149 static int write_to_file(const char *path, const char *format, ...)
151 int res;
152 va_list args;
154 va_start(args, format);
155 res = write_in_file(path, "w", format, args);
156 va_end(args);
158 return res;
161 __attribute__((format (printf, 2, 3)))
162 static int append_to_file(const char *path, const char *format, ...)
164 int res;
165 va_list args;
167 va_start(args, format);
168 res = write_in_file(path, "a", format, args);
169 va_end(args);
171 return res;
174 static int print_file_to_stdout(const char *path)
176 int fd = open(path, O_RDONLY);
177 int ret = 0;
179 if (fd < 0)
180 return error_errno(_("cannot open file '%s' for reading"), path);
181 if (copy_fd(fd, 1) < 0)
182 ret = error_errno(_("failed to read '%s'"), path);
183 close(fd);
184 return ret;
187 static int check_term_format(const char *term, const char *orig_term)
189 int res;
190 char *new_term = xstrfmt("refs/bisect/%s", term);
192 res = check_refname_format(new_term, 0);
193 free(new_term);
195 if (res)
196 return error(_("'%s' is not a valid term"), term);
198 if (one_of(term, "help", "start", "skip", "next", "reset",
199 "visualize", "view", "replay", "log", "run", "terms", NULL))
200 return error(_("can't use the builtin command '%s' as a term"), term);
203 * In theory, nothing prevents swapping completely good and bad,
204 * but this situation could be confusing and hasn't been tested
205 * enough. Forbid it for now.
208 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
209 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
210 return error(_("can't change the meaning of the term '%s'"), term);
212 return 0;
215 static int write_terms(const char *bad, const char *good)
217 int res;
219 if (!strcmp(bad, good))
220 return error(_("please use two different terms"));
222 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
223 return -1;
225 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
227 return res;
230 static int bisect_reset(const char *commit)
232 struct strbuf branch = STRBUF_INIT;
234 if (!commit) {
235 if (!strbuf_read_file(&branch, git_path_bisect_start(), 0))
236 printf(_("We are not bisecting.\n"));
237 else
238 strbuf_rtrim(&branch);
239 } else {
240 struct object_id oid;
242 if (repo_get_oid_commit(the_repository, commit, &oid))
243 return error(_("'%s' is not a valid commit"), commit);
244 strbuf_addstr(&branch, commit);
247 if (branch.len && !refs_ref_exists(get_main_ref_store(the_repository), "BISECT_HEAD")) {
248 struct child_process cmd = CHILD_PROCESS_INIT;
250 cmd.git_cmd = 1;
251 strvec_pushl(&cmd.args, "checkout", "--ignore-other-worktrees",
252 branch.buf, "--", NULL);
253 if (run_command(&cmd)) {
254 error(_("could not check out original"
255 " HEAD '%s'. Try 'git bisect"
256 " reset <commit>'."), branch.buf);
257 strbuf_release(&branch);
258 return -1;
262 strbuf_release(&branch);
263 return bisect_clean_state();
266 static void log_commit(FILE *fp,
267 const char *fmt, const char *state,
268 struct commit *commit)
270 struct pretty_print_context pp = {0};
271 struct strbuf commit_msg = STRBUF_INIT;
272 char *label = xstrfmt(fmt, state);
274 repo_format_commit_message(the_repository, commit, "%s", &commit_msg,
275 &pp);
277 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
278 commit_msg.buf);
280 strbuf_release(&commit_msg);
281 free(label);
284 static int bisect_write(const char *state, const char *rev,
285 const struct bisect_terms *terms, int nolog)
287 struct strbuf tag = STRBUF_INIT;
288 struct object_id oid;
289 struct commit *commit;
290 FILE *fp = NULL;
291 int res = 0;
293 if (!strcmp(state, terms->term_bad)) {
294 strbuf_addf(&tag, "refs/bisect/%s", state);
295 } else if (one_of(state, terms->term_good, "skip", NULL)) {
296 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
297 } else {
298 res = error(_("Bad bisect_write argument: %s"), state);
299 goto finish;
302 if (repo_get_oid(the_repository, rev, &oid)) {
303 res = error(_("couldn't get the oid of the rev '%s'"), rev);
304 goto finish;
307 if (refs_update_ref(get_main_ref_store(the_repository), NULL, tag.buf, &oid, NULL, 0,
308 UPDATE_REFS_MSG_ON_ERR)) {
309 res = -1;
310 goto finish;
313 fp = fopen(git_path_bisect_log(), "a");
314 if (!fp) {
315 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
316 goto finish;
319 commit = lookup_commit_reference(the_repository, &oid);
320 log_commit(fp, "%s", state, commit);
322 if (!nolog)
323 fprintf(fp, "git bisect %s %s\n", state, rev);
325 finish:
326 if (fp)
327 fclose(fp);
328 strbuf_release(&tag);
329 return res;
332 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
334 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
336 if (one_of(cmd, "skip", "start", "terms", NULL))
337 return 0;
339 if (has_term_file && strcmp(cmd, terms->term_bad) &&
340 strcmp(cmd, terms->term_good))
341 return error(_("Invalid command: you're currently in a "
342 "%s/%s bisect"), terms->term_bad,
343 terms->term_good);
345 if (!has_term_file) {
346 if (one_of(cmd, "bad", "good", NULL)) {
347 set_terms(terms, "bad", "good");
348 return write_terms(terms->term_bad, terms->term_good);
350 if (one_of(cmd, "new", "old", NULL)) {
351 set_terms(terms, "new", "old");
352 return write_terms(terms->term_bad, terms->term_good);
356 return 0;
359 static int inc_nr(const char *refname UNUSED,
360 const char *referent UNUSED,
361 const struct object_id *oid UNUSED,
362 int flag UNUSED, void *cb_data)
364 unsigned int *nr = (unsigned int *)cb_data;
365 (*nr)++;
366 return 0;
369 static const char need_bad_and_good_revision_warning[] =
370 N_("You need to give me at least one %s and %s revision.\n"
371 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
373 static const char need_bisect_start_warning[] =
374 N_("You need to start by \"git bisect start\".\n"
375 "You then need to give me at least one %s and %s revision.\n"
376 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
378 static int decide_next(const struct bisect_terms *terms,
379 const char *current_term, int missing_good,
380 int missing_bad)
382 if (!missing_good && !missing_bad)
383 return 0;
384 if (!current_term)
385 return -1;
387 if (missing_good && !missing_bad &&
388 !strcmp(current_term, terms->term_good)) {
389 char *yesno;
391 * have bad (or new) but not good (or old). We could bisect
392 * although this is less optimum.
394 warning(_("bisecting only with a %s commit"), terms->term_bad);
395 if (!isatty(0))
396 return 0;
398 * TRANSLATORS: Make sure to include [Y] and [n] in your
399 * translation. The program will only accept English input
400 * at this point.
402 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
403 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
404 return -1;
405 return 0;
408 if (!is_empty_or_missing_file(git_path_bisect_start()))
409 return error(_(need_bad_and_good_revision_warning),
410 vocab_bad, vocab_good, vocab_bad, vocab_good);
411 else
412 return error(_(need_bisect_start_warning),
413 vocab_good, vocab_bad, vocab_good, vocab_bad);
416 static void bisect_status(struct bisect_state *state,
417 const struct bisect_terms *terms)
419 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
420 char *good_glob = xstrfmt("%s-*", terms->term_good);
422 if (refs_ref_exists(get_main_ref_store(the_repository), bad_ref))
423 state->nr_bad = 1;
425 refs_for_each_glob_ref_in(get_main_ref_store(the_repository), inc_nr,
426 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 char *referent UNUSED, 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 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
582 add_bisect_ref, bad, "refs/bisect/", &cb);
583 cb.object_flags = UNINTERESTING;
584 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
585 add_bisect_ref, good, "refs/bisect/", &cb);
586 if (prepare_revision_walk(revs))
587 res = error(_("revision walk setup failed"));
589 free(good);
590 free(bad);
591 return res;
594 static int bisect_skipped_commits(struct bisect_terms *terms)
596 int res;
597 FILE *fp = NULL;
598 struct rev_info revs;
599 struct commit *commit;
600 struct pretty_print_context pp = {0};
601 struct strbuf commit_name = STRBUF_INIT;
603 res = prepare_revs(terms, &revs);
604 if (res)
605 return res;
607 fp = fopen(git_path_bisect_log(), "a");
608 if (!fp)
609 return error_errno(_("could not open '%s' for appending"),
610 git_path_bisect_log());
612 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
613 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
615 while ((commit = get_revision(&revs)) != NULL) {
616 strbuf_reset(&commit_name);
617 repo_format_commit_message(the_repository, commit, "%s",
618 &commit_name, &pp);
619 fprintf(fp, "# possible first %s commit: [%s] %s\n",
620 terms->term_bad, oid_to_hex(&commit->object.oid),
621 commit_name.buf);
625 * Reset the flags used by revision walks in case
626 * there is another revision walk after this one.
628 reset_revision_walk();
630 strbuf_release(&commit_name);
631 release_revisions(&revs);
632 fclose(fp);
633 return 0;
636 static int bisect_successful(struct bisect_terms *terms)
638 struct object_id oid;
639 struct commit *commit;
640 struct pretty_print_context pp = {0};
641 struct strbuf commit_name = STRBUF_INIT;
642 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
643 int res;
645 refs_read_ref(get_main_ref_store(the_repository), bad_ref, &oid);
646 commit = lookup_commit_reference_by_name(bad_ref);
647 repo_format_commit_message(the_repository, commit, "%s", &commit_name,
648 &pp);
650 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
651 terms->term_bad, oid_to_hex(&commit->object.oid),
652 commit_name.buf);
654 strbuf_release(&commit_name);
655 free(bad_ref);
656 return res;
659 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
661 enum bisect_error res;
663 if (bisect_autostart(terms))
664 return BISECT_FAILED;
666 if (bisect_next_check(terms, terms->term_good))
667 return BISECT_FAILED;
669 /* Perform all bisection computation */
670 res = bisect_next_all(the_repository, prefix);
672 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
673 res = bisect_successful(terms);
674 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
675 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
676 res = bisect_skipped_commits(terms);
677 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
679 return res;
682 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
684 if (bisect_next_check(terms, NULL)) {
685 bisect_print_status(terms);
686 return BISECT_OK;
689 return bisect_next(terms, prefix);
692 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
693 const char **argv)
695 int no_checkout = 0;
696 int first_parent_only = 0;
697 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
698 int flags, pathspec_pos;
699 enum bisect_error res = BISECT_OK;
700 struct string_list revs = STRING_LIST_INIT_DUP;
701 struct string_list states = STRING_LIST_INIT_DUP;
702 struct strbuf start_head = STRBUF_INIT;
703 struct strbuf bisect_names = STRBUF_INIT;
704 struct object_id head_oid;
705 struct object_id oid;
706 const char *head;
708 if (is_bare_repository())
709 no_checkout = 1;
712 * Check for one bad and then some good revisions
714 for (i = 0; i < argc; i++) {
715 if (!strcmp(argv[i], "--")) {
716 has_double_dash = 1;
717 break;
721 for (i = 0; i < argc; i++) {
722 const char *arg = argv[i];
723 if (!strcmp(argv[i], "--")) {
724 break;
725 } else if (!strcmp(arg, "--no-checkout")) {
726 no_checkout = 1;
727 } else if (!strcmp(arg, "--first-parent")) {
728 first_parent_only = 1;
729 } else if (!strcmp(arg, "--term-good") ||
730 !strcmp(arg, "--term-old")) {
731 i++;
732 if (argc <= i)
733 return error(_("'' is not a valid term"));
734 must_write_terms = 1;
735 free((void *) terms->term_good);
736 terms->term_good = xstrdup(argv[i]);
737 } else if (skip_prefix(arg, "--term-good=", &arg) ||
738 skip_prefix(arg, "--term-old=", &arg)) {
739 must_write_terms = 1;
740 free((void *) terms->term_good);
741 terms->term_good = xstrdup(arg);
742 } else if (!strcmp(arg, "--term-bad") ||
743 !strcmp(arg, "--term-new")) {
744 i++;
745 if (argc <= i)
746 return error(_("'' is not a valid term"));
747 must_write_terms = 1;
748 free((void *) terms->term_bad);
749 terms->term_bad = xstrdup(argv[i]);
750 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
751 skip_prefix(arg, "--term-new=", &arg)) {
752 must_write_terms = 1;
753 free((void *) terms->term_bad);
754 terms->term_bad = xstrdup(arg);
755 } else if (starts_with(arg, "--")) {
756 return error(_("unrecognized option: '%s'"), arg);
757 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
758 string_list_append(&revs, oid_to_hex(&oid));
759 } else if (has_double_dash) {
760 die(_("'%s' does not appear to be a valid "
761 "revision"), arg);
762 } else {
763 break;
766 pathspec_pos = i;
769 * The user ran "git bisect start <sha1> <sha1>", hence did not
770 * explicitly specify the terms, but we are already starting to
771 * set references named with the default terms, and won't be able
772 * to change afterwards.
774 if (revs.nr)
775 must_write_terms = 1;
776 for (i = 0; i < revs.nr; i++) {
777 if (bad_seen) {
778 string_list_append(&states, terms->term_good);
779 } else {
780 bad_seen = 1;
781 string_list_append(&states, terms->term_bad);
786 * Verify HEAD
788 head = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
789 "HEAD", 0, &head_oid, &flags);
790 if (!head)
791 if (repo_get_oid(the_repository, "HEAD", &head_oid))
792 return error(_("bad HEAD - I need a HEAD"));
795 * Check if we are bisecting
797 if (!is_empty_or_missing_file(git_path_bisect_start())) {
798 /* Reset to the rev from where we started */
799 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
800 strbuf_trim(&start_head);
801 if (!no_checkout) {
802 struct child_process cmd = CHILD_PROCESS_INIT;
804 cmd.git_cmd = 1;
805 strvec_pushl(&cmd.args, "checkout", start_head.buf,
806 "--", NULL);
807 if (run_command(&cmd)) {
808 res = error(_("checking out '%s' failed."
809 " Try 'git bisect start "
810 "<valid-branch>'."),
811 start_head.buf);
812 goto finish;
815 } else {
816 /* Get the rev from where we start. */
817 if (!repo_get_oid(the_repository, head, &head_oid) &&
818 !starts_with(head, "refs/heads/")) {
819 strbuf_reset(&start_head);
820 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
821 } else if (!repo_get_oid(the_repository, head, &head_oid) &&
822 skip_prefix(head, "refs/heads/", &head)) {
823 strbuf_addstr(&start_head, head);
824 } else {
825 return error(_("bad HEAD - strange symbolic ref"));
830 * Get rid of any old bisect state.
832 if (bisect_clean_state())
833 return BISECT_FAILED;
836 * Write new start state
838 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
840 if (first_parent_only)
841 write_file(git_path_bisect_first_parent(), "\n");
843 if (no_checkout) {
844 if (repo_get_oid(the_repository, start_head.buf, &oid) < 0) {
845 res = error(_("invalid ref: '%s'"), start_head.buf);
846 goto finish;
848 if (refs_update_ref(get_main_ref_store(the_repository), NULL, "BISECT_HEAD", &oid, NULL, 0,
849 UPDATE_REFS_MSG_ON_ERR)) {
850 res = BISECT_FAILED;
851 goto finish;
855 if (pathspec_pos < argc - 1)
856 sq_quote_argv(&bisect_names, argv + pathspec_pos);
857 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
859 for (i = 0; i < states.nr; i++)
860 if (bisect_write(states.items[i].string,
861 revs.items[i].string, terms, 1)) {
862 res = BISECT_FAILED;
863 goto finish;
866 if (must_write_terms && write_terms(terms->term_bad,
867 terms->term_good)) {
868 res = BISECT_FAILED;
869 goto finish;
872 res = bisect_append_log_quoted(argv);
873 if (res)
874 res = BISECT_FAILED;
876 finish:
877 string_list_clear(&revs, 0);
878 string_list_clear(&states, 0);
879 strbuf_release(&start_head);
880 strbuf_release(&bisect_names);
881 if (res)
882 return res;
884 res = bisect_auto_next(terms, NULL);
885 if (!is_bisect_success(res))
886 bisect_clean_state();
887 return res;
890 static inline int file_is_not_empty(const char *path)
892 return !is_empty_or_missing_file(path);
895 static int bisect_autostart(struct bisect_terms *terms)
897 int res;
898 const char *yesno;
900 if (file_is_not_empty(git_path_bisect_start()))
901 return 0;
903 fprintf_ln(stderr, _("You need to start by \"git bisect "
904 "start\"\n"));
906 if (!isatty(STDIN_FILENO))
907 return -1;
910 * TRANSLATORS: Make sure to include [Y] and [n] in your
911 * translation. The program will only accept English input
912 * at this point.
914 yesno = git_prompt(_("Do you want me to do it for you "
915 "[Y/n]? "), PROMPT_ECHO);
916 res = tolower(*yesno) == 'n' ?
917 -1 : bisect_start(terms, 0, empty_strvec);
919 return res;
922 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
923 const char **argv)
925 const char *state;
926 int i, verify_expected = 1;
927 struct object_id oid, expected;
928 struct oid_array revs = OID_ARRAY_INIT;
930 if (!argc)
931 return error(_("Please call `--bisect-state` with at least one argument"));
933 if (bisect_autostart(terms))
934 return BISECT_FAILED;
936 state = argv[0];
937 if (check_and_set_terms(terms, state) ||
938 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
939 return BISECT_FAILED;
941 argv++;
942 argc--;
943 if (argc > 1 && !strcmp(state, terms->term_bad))
944 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
946 if (argc == 0) {
947 const char *head = "BISECT_HEAD";
948 enum get_oid_result res_head = repo_get_oid(the_repository,
949 head, &oid);
951 if (res_head == MISSING_OBJECT) {
952 head = "HEAD";
953 res_head = repo_get_oid(the_repository, head, &oid);
956 if (res_head)
957 error(_("Bad rev input: %s"), head);
958 oid_array_append(&revs, &oid);
962 * All input revs must be checked before executing bisect_write()
963 * to discard junk revs.
966 for (; argc; argc--, argv++) {
967 struct commit *commit;
969 if (repo_get_oid(the_repository, *argv, &oid)){
970 error(_("Bad rev input: %s"), *argv);
971 oid_array_clear(&revs);
972 return BISECT_FAILED;
975 commit = lookup_commit_reference(the_repository, &oid);
976 if (!commit)
977 die(_("Bad rev input (not a commit): %s"), *argv);
979 oid_array_append(&revs, &commit->object.oid);
982 if (refs_read_ref(get_main_ref_store(the_repository), "BISECT_EXPECTED_REV", &expected))
983 verify_expected = 0; /* Ignore invalid file contents */
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 refs_delete_ref(get_main_ref_store(the_repository),
993 NULL, "BISECT_EXPECTED_REV", NULL,
994 REF_NO_DEREF);
995 verify_expected = 0;
999 oid_array_clear(&revs);
1000 return bisect_auto_next(terms, NULL);
1003 static enum bisect_error bisect_log(void)
1005 int fd, status;
1006 const char* filename = git_path_bisect_log();
1008 if (is_empty_or_missing_file(filename))
1009 return error(_("We are not bisecting."));
1011 fd = open(filename, O_RDONLY);
1012 if (fd < 0)
1013 return BISECT_FAILED;
1015 status = copy_fd(fd, STDOUT_FILENO);
1016 close(fd);
1017 return status ? BISECT_FAILED : BISECT_OK;
1020 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1022 const char *p = line->buf + strspn(line->buf, " \t");
1023 char *word_end, *rev;
1025 if ((!skip_prefix(p, "git bisect", &p) &&
1026 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1027 return 0;
1028 p += strspn(p, " \t");
1030 word_end = (char *)p + strcspn(p, " \t");
1031 rev = word_end + strspn(word_end, " \t");
1032 *word_end = '\0'; /* NUL-terminate the word */
1034 get_terms(terms);
1035 if (check_and_set_terms(terms, p))
1036 return -1;
1038 if (!strcmp(p, "start")) {
1039 struct strvec argv = STRVEC_INIT;
1040 int res;
1041 sq_dequote_to_strvec(rev, &argv);
1042 res = bisect_start(terms, argv.nr, argv.v);
1043 strvec_clear(&argv);
1044 return res;
1047 if (one_of(p, terms->term_good,
1048 terms->term_bad, "skip", NULL))
1049 return bisect_write(p, rev, terms, 0);
1051 if (!strcmp(p, "terms")) {
1052 struct strvec argv = STRVEC_INIT;
1053 int res;
1054 sq_dequote_to_strvec(rev, &argv);
1055 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1056 strvec_clear(&argv);
1057 return res;
1059 error(_("'%s'?? what are you talking about?"), p);
1061 return -1;
1064 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1066 FILE *fp = NULL;
1067 enum bisect_error res = BISECT_OK;
1068 struct strbuf line = STRBUF_INIT;
1070 if (is_empty_or_missing_file(filename))
1071 return error(_("cannot read file '%s' for replaying"), filename);
1073 if (bisect_reset(NULL))
1074 return BISECT_FAILED;
1076 fp = fopen(filename, "r");
1077 if (!fp)
1078 return BISECT_FAILED;
1080 while ((strbuf_getline(&line, fp) != EOF) && !res)
1081 res = process_replay_line(terms, &line);
1083 strbuf_release(&line);
1084 fclose(fp);
1086 if (res)
1087 return BISECT_FAILED;
1089 return bisect_auto_next(terms, NULL);
1092 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1093 const char **argv)
1095 int i;
1096 enum bisect_error res;
1097 struct strvec argv_state = STRVEC_INIT;
1099 strvec_push(&argv_state, "skip");
1101 for (i = 0; i < argc; i++) {
1102 const char *dotdot = strstr(argv[i], "..");
1104 if (dotdot) {
1105 struct rev_info revs;
1106 struct commit *commit;
1108 repo_init_revisions(the_repository, &revs, NULL);
1109 setup_revisions(2, argv + i - 1, &revs, NULL);
1111 if (prepare_revision_walk(&revs))
1112 die(_("revision walk setup failed"));
1113 while ((commit = get_revision(&revs)) != NULL)
1114 strvec_push(&argv_state,
1115 oid_to_hex(&commit->object.oid));
1117 reset_revision_walk();
1118 release_revisions(&revs);
1119 } else {
1120 strvec_push(&argv_state, argv[i]);
1123 res = bisect_state(terms, argv_state.nr, argv_state.v);
1125 strvec_clear(&argv_state);
1126 return res;
1129 static int bisect_visualize(struct bisect_terms *terms, int argc,
1130 const char **argv)
1132 struct child_process cmd = CHILD_PROCESS_INIT;
1133 struct strbuf sb = STRBUF_INIT;
1135 if (bisect_next_check(terms, NULL) != 0)
1136 return BISECT_FAILED;
1138 cmd.no_stdin = 1;
1139 if (!argc) {
1140 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1141 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1142 strvec_push(&cmd.args, "gitk");
1143 } else {
1144 strvec_push(&cmd.args, "log");
1145 cmd.git_cmd = 1;
1147 } else {
1148 if (argv[0][0] == '-') {
1149 strvec_push(&cmd.args, "log");
1150 cmd.git_cmd = 1;
1151 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1152 cmd.git_cmd = 1;
1154 strvec_pushv(&cmd.args, argv);
1157 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1159 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1160 sq_dequote_to_strvec(sb.buf, &cmd.args);
1161 strbuf_release(&sb);
1163 return run_command(&cmd);
1166 static int get_first_good(const char *refname UNUSED,
1167 const char *referent UNUSED,
1168 const struct object_id *oid,
1169 int flag UNUSED, void *cb_data)
1171 oidcpy(cb_data, oid);
1172 return 1;
1175 static int do_bisect_run(const char *command)
1177 struct child_process cmd = CHILD_PROCESS_INIT;
1179 printf(_("running %s\n"), command);
1180 cmd.use_shell = 1;
1181 strvec_push(&cmd.args, command);
1182 return run_command(&cmd);
1185 static int verify_good(const struct bisect_terms *terms, const char *command)
1187 int rc;
1188 enum bisect_error res;
1189 struct object_id good_rev;
1190 struct object_id current_rev;
1191 char *good_glob = xstrfmt("%s-*", terms->term_good);
1192 int no_checkout = refs_ref_exists(get_main_ref_store(the_repository),
1193 "BISECT_HEAD");
1195 refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
1196 get_first_good, good_glob, "refs/bisect/",
1197 &good_rev);
1198 free(good_glob);
1200 if (refs_read_ref(get_main_ref_store(the_repository), no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1201 return -1;
1203 res = bisect_checkout(&good_rev, no_checkout);
1204 if (res != BISECT_OK)
1205 return -1;
1207 rc = do_bisect_run(command);
1209 res = bisect_checkout(&current_rev, no_checkout);
1210 if (res != BISECT_OK)
1211 return -1;
1213 return rc;
1216 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1218 int res = BISECT_OK;
1219 struct strbuf command = STRBUF_INIT;
1220 const char *new_state;
1221 int temporary_stdout_fd, saved_stdout;
1222 int is_first_run = 1;
1224 if (bisect_next_check(terms, NULL))
1225 return BISECT_FAILED;
1227 if (!argc) {
1228 error(_("bisect run failed: no command provided."));
1229 return BISECT_FAILED;
1232 sq_quote_argv(&command, argv);
1233 strbuf_ltrim(&command);
1234 while (1) {
1235 res = do_bisect_run(command.buf);
1238 * Exit code 126 and 127 can either come from the shell
1239 * if it was unable to execute or even find the script,
1240 * or from the script itself. Check with a known-good
1241 * revision to avoid trashing the bisect run due to a
1242 * missing or non-executable script.
1244 if (is_first_run && (res == 126 || res == 127)) {
1245 int rc = verify_good(terms, command.buf);
1246 is_first_run = 0;
1247 if (rc < 0 || 128 <= rc) {
1248 error(_("unable to verify %s on good"
1249 " revision"), command.buf);
1250 res = BISECT_FAILED;
1251 break;
1253 if (rc == res) {
1254 error(_("bogus exit code %d for good revision"),
1255 rc);
1256 res = BISECT_FAILED;
1257 break;
1261 if (res < 0 || 128 <= res) {
1262 error(_("bisect run failed: exit code %d from"
1263 " %s is < 0 or >= 128"), res, command.buf);
1264 break;
1267 if (res == 125)
1268 new_state = "skip";
1269 else if (!res)
1270 new_state = terms->term_good;
1271 else
1272 new_state = terms->term_bad;
1274 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1276 if (temporary_stdout_fd < 0) {
1277 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1278 break;
1281 fflush(stdout);
1282 saved_stdout = dup(1);
1283 dup2(temporary_stdout_fd, 1);
1285 res = bisect_state(terms, 1, &new_state);
1287 fflush(stdout);
1288 dup2(saved_stdout, 1);
1289 close(saved_stdout);
1290 close(temporary_stdout_fd);
1292 print_file_to_stdout(git_path_bisect_run());
1294 if (res == BISECT_ONLY_SKIPPED_LEFT)
1295 error(_("bisect run cannot continue any more"));
1296 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1297 puts(_("bisect run success"));
1298 res = BISECT_OK;
1299 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1300 puts(_("bisect found first bad commit"));
1301 res = BISECT_OK;
1302 } else if (res) {
1303 error(_("bisect run failed: 'git bisect %s'"
1304 " exited with error code %d"), new_state, res);
1305 } else {
1306 continue;
1308 break;
1311 strbuf_release(&command);
1312 return res;
1315 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1317 if (argc > 1)
1318 return error(_("'%s' requires either no argument or a commit"),
1319 "git bisect reset");
1320 return bisect_reset(argc ? argv[0] : NULL);
1323 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1325 int res;
1326 struct bisect_terms terms = { 0 };
1328 if (argc > 1)
1329 return error(_("'%s' requires 0 or 1 argument"),
1330 "git bisect terms");
1331 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1332 free_terms(&terms);
1333 return res;
1336 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1338 int res;
1339 struct bisect_terms terms = { 0 };
1341 set_terms(&terms, "bad", "good");
1342 res = bisect_start(&terms, argc, argv);
1343 free_terms(&terms);
1344 return res;
1347 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1349 int res;
1350 struct bisect_terms terms = { 0 };
1352 if (argc)
1353 return error(_("'%s' requires 0 arguments"),
1354 "git bisect next");
1355 get_terms(&terms);
1356 res = bisect_next(&terms, prefix);
1357 free_terms(&terms);
1358 return res;
1361 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1363 return bisect_log();
1366 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1368 int res;
1369 struct bisect_terms terms = { 0 };
1371 if (argc != 1)
1372 return error(_("no logfile given"));
1373 set_terms(&terms, "bad", "good");
1374 res = bisect_replay(&terms, argv[0]);
1375 free_terms(&terms);
1376 return res;
1379 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1381 int res;
1382 struct bisect_terms terms = { 0 };
1384 set_terms(&terms, "bad", "good");
1385 get_terms(&terms);
1386 res = bisect_skip(&terms, argc, argv);
1387 free_terms(&terms);
1388 return res;
1391 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1393 int res;
1394 struct bisect_terms terms = { 0 };
1396 get_terms(&terms);
1397 res = bisect_visualize(&terms, argc, argv);
1398 free_terms(&terms);
1399 return res;
1402 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1404 int res;
1405 struct bisect_terms terms = { 0 };
1407 if (!argc)
1408 return error(_("'%s' failed: no command provided."), "git bisect run");
1409 get_terms(&terms);
1410 res = bisect_run(&terms, argc, argv);
1411 free_terms(&terms);
1412 return res;
1415 int cmd_bisect(int argc,
1416 const char **argv,
1417 const char *prefix,
1418 struct repository *repo UNUSED)
1420 int res = 0;
1421 parse_opt_subcommand_fn *fn = NULL;
1422 struct option options[] = {
1423 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1424 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1425 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1426 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1427 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1428 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1429 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1430 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1431 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1432 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1433 OPT_END()
1435 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1436 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1438 if (!fn) {
1439 struct bisect_terms terms = { 0 };
1441 if (!argc)
1442 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1444 set_terms(&terms, "bad", "good");
1445 get_terms(&terms);
1446 if (check_and_set_terms(&terms, argv[0]))
1447 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1448 options, argv[0]);
1449 res = bisect_state(&terms, argc, argv);
1450 free_terms(&terms);
1451 } else {
1452 argc--;
1453 argv++;
1454 res = fn(argc, argv, prefix);
1457 return is_bisect_success(res) ? 0 : -res;