trace.c, git.c: remove unnecessary parameter to trace_repo_setup()
[git/debian.git] / builtin / bisect.c
blob73017402671d30ce7f868a9691f9bb6f520695e1
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "bisect.h"
5 #include "refs.h"
6 #include "dir.h"
7 #include "strvec.h"
8 #include "run-command.h"
9 #include "prompt.h"
10 #include "quote.h"
11 #include "revision.h"
13 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
14 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
15 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
16 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
17 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
18 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
19 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
20 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
22 #define BUILTIN_GIT_BISECT_START_USAGE \
23 N_("git bisect start [--term-{new,bad}=<term> --term-{old,good}=<term>]" \
24 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
25 " [<pathspec>...]")
26 #define BUILTIN_GIT_BISECT_STATE_USAGE \
27 N_("git bisect (good|bad) [<rev>...]")
28 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
29 "git bisect terms [--term-good | --term-bad]"
30 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
31 N_("git bisect skip [(<rev>|<range>)...]")
32 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
33 "git bisect next"
34 #define BUILTIN_GIT_BISECT_RESET_USAGE \
35 N_("git bisect reset [<commit>]")
36 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
37 "git bisect visualize"
38 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
39 N_("git bisect replay <logfile>")
40 #define BUILTIN_GIT_BISECT_LOG_USAGE \
41 "git bisect log"
42 #define BUILTIN_GIT_BISECT_RUN_USAGE \
43 N_("git bisect run <cmd>...")
45 static const char * const git_bisect_usage[] = {
46 BUILTIN_GIT_BISECT_START_USAGE,
47 BUILTIN_GIT_BISECT_STATE_USAGE,
48 BUILTIN_GIT_BISECT_TERMS_USAGE,
49 BUILTIN_GIT_BISECT_SKIP_USAGE,
50 BUILTIN_GIT_BISECT_NEXT_USAGE,
51 BUILTIN_GIT_BISECT_RESET_USAGE,
52 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
53 BUILTIN_GIT_BISECT_REPLAY_USAGE,
54 BUILTIN_GIT_BISECT_LOG_USAGE,
55 BUILTIN_GIT_BISECT_RUN_USAGE,
56 NULL
59 struct add_bisect_ref_data {
60 struct rev_info *revs;
61 unsigned int object_flags;
64 struct bisect_terms {
65 char *term_good;
66 char *term_bad;
69 static void free_terms(struct bisect_terms *terms)
71 FREE_AND_NULL(terms->term_good);
72 FREE_AND_NULL(terms->term_bad);
75 static void set_terms(struct bisect_terms *terms, const char *bad,
76 const char *good)
78 free((void *)terms->term_good);
79 terms->term_good = xstrdup(good);
80 free((void *)terms->term_bad);
81 terms->term_bad = xstrdup(bad);
84 static const char vocab_bad[] = "bad|new";
85 static const char vocab_good[] = "good|old";
87 static int bisect_autostart(struct bisect_terms *terms);
90 * Check whether the string `term` belongs to the set of strings
91 * included in the variable arguments.
93 LAST_ARG_MUST_BE_NULL
94 static int one_of(const char *term, ...)
96 int res = 0;
97 va_list matches;
98 const char *match;
100 va_start(matches, term);
101 while (!res && (match = va_arg(matches, const char *)))
102 res = !strcmp(term, match);
103 va_end(matches);
105 return res;
109 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
110 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
111 * that indicate special success.
114 static int is_bisect_success(enum bisect_error res)
116 return !res ||
117 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
118 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
121 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
123 FILE *fp = NULL;
124 int res = 0;
126 if (strcmp(mode, "w") && strcmp(mode, "a"))
127 BUG("write-in-file does not support '%s' mode", mode);
128 fp = fopen(path, mode);
129 if (!fp)
130 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
131 res = vfprintf(fp, format, args);
133 if (res < 0) {
134 int saved_errno = errno;
135 fclose(fp);
136 errno = saved_errno;
137 return error_errno(_("could not write to file '%s'"), path);
140 return fclose(fp);
143 __attribute__((format (printf, 2, 3)))
144 static int write_to_file(const char *path, const char *format, ...)
146 int res;
147 va_list args;
149 va_start(args, format);
150 res = write_in_file(path, "w", format, args);
151 va_end(args);
153 return res;
156 __attribute__((format (printf, 2, 3)))
157 static int append_to_file(const char *path, const char *format, ...)
159 int res;
160 va_list args;
162 va_start(args, format);
163 res = write_in_file(path, "a", format, args);
164 va_end(args);
166 return res;
169 static int print_file_to_stdout(const char *path)
171 int fd = open(path, O_RDONLY);
172 int ret = 0;
174 if (fd < 0)
175 return error_errno(_("cannot open file '%s' for reading"), path);
176 if (copy_fd(fd, 1) < 0)
177 ret = error_errno(_("failed to read '%s'"), path);
178 close(fd);
179 return ret;
182 static int check_term_format(const char *term, const char *orig_term)
184 int res;
185 char *new_term = xstrfmt("refs/bisect/%s", term);
187 res = check_refname_format(new_term, 0);
188 free(new_term);
190 if (res)
191 return error(_("'%s' is not a valid term"), term);
193 if (one_of(term, "help", "start", "skip", "next", "reset",
194 "visualize", "view", "replay", "log", "run", "terms", NULL))
195 return error(_("can't use the builtin command '%s' as a term"), term);
198 * In theory, nothing prevents swapping completely good and bad,
199 * but this situation could be confusing and hasn't been tested
200 * enough. Forbid it for now.
203 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
204 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
205 return error(_("can't change the meaning of the term '%s'"), term);
207 return 0;
210 static int write_terms(const char *bad, const char *good)
212 int res;
214 if (!strcmp(bad, good))
215 return error(_("please use two different terms"));
217 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
218 return -1;
220 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
222 return res;
225 static int bisect_reset(const char *commit)
227 struct strbuf branch = STRBUF_INIT;
229 if (!commit) {
230 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
231 printf(_("We are not bisecting.\n"));
232 return 0;
234 strbuf_rtrim(&branch);
235 } else {
236 struct object_id oid;
238 if (get_oid_commit(commit, &oid))
239 return error(_("'%s' is not a valid commit"), commit);
240 strbuf_addstr(&branch, commit);
243 if (!ref_exists("BISECT_HEAD")) {
244 struct child_process cmd = CHILD_PROCESS_INIT;
246 cmd.git_cmd = 1;
247 strvec_pushl(&cmd.args, "checkout", branch.buf, "--", NULL);
248 if (run_command(&cmd)) {
249 error(_("could not check out original"
250 " HEAD '%s'. Try 'git bisect"
251 " reset <commit>'."), branch.buf);
252 strbuf_release(&branch);
253 return -1;
257 strbuf_release(&branch);
258 return bisect_clean_state();
261 static void log_commit(FILE *fp, char *fmt, const char *state,
262 struct commit *commit)
264 struct pretty_print_context pp = {0};
265 struct strbuf commit_msg = STRBUF_INIT;
266 char *label = xstrfmt(fmt, state);
268 format_commit_message(commit, "%s", &commit_msg, &pp);
270 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
271 commit_msg.buf);
273 strbuf_release(&commit_msg);
274 free(label);
277 static int bisect_write(const char *state, const char *rev,
278 const struct bisect_terms *terms, int nolog)
280 struct strbuf tag = STRBUF_INIT;
281 struct object_id oid;
282 struct commit *commit;
283 FILE *fp = NULL;
284 int res = 0;
286 if (!strcmp(state, terms->term_bad)) {
287 strbuf_addf(&tag, "refs/bisect/%s", state);
288 } else if (one_of(state, terms->term_good, "skip", NULL)) {
289 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
290 } else {
291 res = error(_("Bad bisect_write argument: %s"), state);
292 goto finish;
295 if (get_oid(rev, &oid)) {
296 res = error(_("couldn't get the oid of the rev '%s'"), rev);
297 goto finish;
300 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
301 UPDATE_REFS_MSG_ON_ERR)) {
302 res = -1;
303 goto finish;
306 fp = fopen(git_path_bisect_log(), "a");
307 if (!fp) {
308 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
309 goto finish;
312 commit = lookup_commit_reference(the_repository, &oid);
313 log_commit(fp, "%s", state, commit);
315 if (!nolog)
316 fprintf(fp, "git bisect %s %s\n", state, rev);
318 finish:
319 if (fp)
320 fclose(fp);
321 strbuf_release(&tag);
322 return res;
325 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
327 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
329 if (one_of(cmd, "skip", "start", "terms", NULL))
330 return 0;
332 if (has_term_file && strcmp(cmd, terms->term_bad) &&
333 strcmp(cmd, terms->term_good))
334 return error(_("Invalid command: you're currently in a "
335 "%s/%s bisect"), terms->term_bad,
336 terms->term_good);
338 if (!has_term_file) {
339 if (one_of(cmd, "bad", "good", NULL)) {
340 set_terms(terms, "bad", "good");
341 return write_terms(terms->term_bad, terms->term_good);
343 if (one_of(cmd, "new", "old", NULL)) {
344 set_terms(terms, "new", "old");
345 return write_terms(terms->term_bad, terms->term_good);
349 return 0;
352 static int inc_nr(const char *refname UNUSED,
353 const struct object_id *oid UNUSED,
354 int flag UNUSED, void *cb_data)
356 unsigned int *nr = (unsigned int *)cb_data;
357 (*nr)++;
358 return 0;
361 static const char need_bad_and_good_revision_warning[] =
362 N_("You need to give me at least one %s and %s revision.\n"
363 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
365 static const char need_bisect_start_warning[] =
366 N_("You need to start by \"git bisect start\".\n"
367 "You then need to give me at least one %s and %s revision.\n"
368 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
370 static int decide_next(const struct bisect_terms *terms,
371 const char *current_term, int missing_good,
372 int missing_bad)
374 if (!missing_good && !missing_bad)
375 return 0;
376 if (!current_term)
377 return -1;
379 if (missing_good && !missing_bad &&
380 !strcmp(current_term, terms->term_good)) {
381 char *yesno;
383 * have bad (or new) but not good (or old). We could bisect
384 * although this is less optimum.
386 warning(_("bisecting only with a %s commit"), terms->term_bad);
387 if (!isatty(0))
388 return 0;
390 * TRANSLATORS: Make sure to include [Y] and [n] in your
391 * translation. The program will only accept English input
392 * at this point.
394 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
395 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
396 return -1;
397 return 0;
400 if (!is_empty_or_missing_file(git_path_bisect_start()))
401 return error(_(need_bad_and_good_revision_warning),
402 vocab_bad, vocab_good, vocab_bad, vocab_good);
403 else
404 return error(_(need_bisect_start_warning),
405 vocab_good, vocab_bad, vocab_good, vocab_bad);
408 static void bisect_status(struct bisect_state *state,
409 const struct bisect_terms *terms)
411 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
412 char *good_glob = xstrfmt("%s-*", terms->term_good);
414 if (ref_exists(bad_ref))
415 state->nr_bad = 1;
417 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
418 (void *) &state->nr_good);
420 free(good_glob);
421 free(bad_ref);
424 __attribute__((format (printf, 1, 2)))
425 static void bisect_log_printf(const char *fmt, ...)
427 struct strbuf buf = STRBUF_INIT;
428 va_list ap;
430 va_start(ap, fmt);
431 strbuf_vaddf(&buf, fmt, ap);
432 va_end(ap);
434 printf("%s", buf.buf);
435 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
437 strbuf_release(&buf);
440 static void bisect_print_status(const struct bisect_terms *terms)
442 struct bisect_state state = { 0 };
444 bisect_status(&state, terms);
446 /* If we had both, we'd already be started, and shouldn't get here. */
447 if (state.nr_good && state.nr_bad)
448 return;
450 if (!state.nr_good && !state.nr_bad)
451 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
452 else if (state.nr_good)
453 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
454 "status: waiting for bad commit, %d good commits known\n",
455 state.nr_good), state.nr_good);
456 else
457 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
460 static int bisect_next_check(const struct bisect_terms *terms,
461 const char *current_term)
463 struct bisect_state state = { 0 };
464 bisect_status(&state, terms);
465 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
468 static int get_terms(struct bisect_terms *terms)
470 struct strbuf str = STRBUF_INIT;
471 FILE *fp = NULL;
472 int res = 0;
474 fp = fopen(git_path_bisect_terms(), "r");
475 if (!fp) {
476 res = -1;
477 goto finish;
480 free_terms(terms);
481 strbuf_getline_lf(&str, fp);
482 terms->term_bad = strbuf_detach(&str, NULL);
483 strbuf_getline_lf(&str, fp);
484 terms->term_good = strbuf_detach(&str, NULL);
486 finish:
487 if (fp)
488 fclose(fp);
489 strbuf_release(&str);
490 return res;
493 static int bisect_terms(struct bisect_terms *terms, const char *option)
495 if (get_terms(terms))
496 return error(_("no terms defined"));
498 if (!option) {
499 printf(_("Your current terms are %s for the old state\n"
500 "and %s for the new state.\n"),
501 terms->term_good, terms->term_bad);
502 return 0;
504 if (one_of(option, "--term-good", "--term-old", NULL))
505 printf("%s\n", terms->term_good);
506 else if (one_of(option, "--term-bad", "--term-new", NULL))
507 printf("%s\n", terms->term_bad);
508 else
509 return error(_("invalid argument %s for 'git bisect terms'.\n"
510 "Supported options are: "
511 "--term-good|--term-old and "
512 "--term-bad|--term-new."), option);
514 return 0;
517 static int bisect_append_log_quoted(const char **argv)
519 int res = 0;
520 FILE *fp = fopen(git_path_bisect_log(), "a");
521 struct strbuf orig_args = STRBUF_INIT;
523 if (!fp)
524 return -1;
526 if (fprintf(fp, "git bisect start") < 1) {
527 res = -1;
528 goto finish;
531 sq_quote_argv(&orig_args, argv);
532 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
533 res = -1;
535 finish:
536 fclose(fp);
537 strbuf_release(&orig_args);
538 return res;
541 static int add_bisect_ref(const char *refname, const struct object_id *oid,
542 int flags UNUSED, void *cb)
544 struct add_bisect_ref_data *data = cb;
546 add_pending_oid(data->revs, refname, oid, data->object_flags);
548 return 0;
551 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
553 int res = 0;
554 struct add_bisect_ref_data cb = { revs };
555 char *good = xstrfmt("%s-*", terms->term_good);
558 * We cannot use terms->term_bad directly in
559 * for_each_glob_ref_in() and we have to append a '*' to it,
560 * otherwise for_each_glob_ref_in() will append '/' and '*'.
562 char *bad = xstrfmt("%s*", terms->term_bad);
565 * It is important to reset the flags used by revision walks
566 * as the previous call to bisect_next_all() in turn
567 * sets up a revision walk.
569 reset_revision_walk();
570 init_revisions(revs, NULL);
571 setup_revisions(0, NULL, revs, NULL);
572 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
573 cb.object_flags = UNINTERESTING;
574 for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
575 if (prepare_revision_walk(revs))
576 res = error(_("revision walk setup failed\n"));
578 free(good);
579 free(bad);
580 return res;
583 static int bisect_skipped_commits(struct bisect_terms *terms)
585 int res;
586 FILE *fp = NULL;
587 struct rev_info revs;
588 struct commit *commit;
589 struct pretty_print_context pp = {0};
590 struct strbuf commit_name = STRBUF_INIT;
592 res = prepare_revs(terms, &revs);
593 if (res)
594 return res;
596 fp = fopen(git_path_bisect_log(), "a");
597 if (!fp)
598 return error_errno(_("could not open '%s' for appending"),
599 git_path_bisect_log());
601 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
602 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
604 while ((commit = get_revision(&revs)) != NULL) {
605 strbuf_reset(&commit_name);
606 format_commit_message(commit, "%s",
607 &commit_name, &pp);
608 fprintf(fp, "# possible first %s commit: [%s] %s\n",
609 terms->term_bad, oid_to_hex(&commit->object.oid),
610 commit_name.buf);
614 * Reset the flags used by revision walks in case
615 * there is another revision walk after this one.
617 reset_revision_walk();
619 strbuf_release(&commit_name);
620 release_revisions(&revs);
621 fclose(fp);
622 return 0;
625 static int bisect_successful(struct bisect_terms *terms)
627 struct object_id oid;
628 struct commit *commit;
629 struct pretty_print_context pp = {0};
630 struct strbuf commit_name = STRBUF_INIT;
631 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
632 int res;
634 read_ref(bad_ref, &oid);
635 commit = lookup_commit_reference_by_name(bad_ref);
636 format_commit_message(commit, "%s", &commit_name, &pp);
638 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
639 terms->term_bad, oid_to_hex(&commit->object.oid),
640 commit_name.buf);
642 strbuf_release(&commit_name);
643 free(bad_ref);
644 return res;
647 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
649 enum bisect_error res;
651 if (bisect_autostart(terms))
652 return BISECT_FAILED;
654 if (bisect_next_check(terms, terms->term_good))
655 return BISECT_FAILED;
657 /* Perform all bisection computation */
658 res = bisect_next_all(the_repository, prefix);
660 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
661 res = bisect_successful(terms);
662 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
663 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
664 res = bisect_skipped_commits(terms);
665 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
667 return res;
670 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
672 if (bisect_next_check(terms, NULL)) {
673 bisect_print_status(terms);
674 return BISECT_OK;
677 return bisect_next(terms, prefix);
680 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
681 const char **argv)
683 int no_checkout = 0;
684 int first_parent_only = 0;
685 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
686 int flags, pathspec_pos;
687 enum bisect_error res = BISECT_OK;
688 struct string_list revs = STRING_LIST_INIT_DUP;
689 struct string_list states = STRING_LIST_INIT_DUP;
690 struct strbuf start_head = STRBUF_INIT;
691 struct strbuf bisect_names = STRBUF_INIT;
692 struct object_id head_oid;
693 struct object_id oid;
694 const char *head;
696 if (is_bare_repository())
697 no_checkout = 1;
700 * Check for one bad and then some good revisions
702 for (i = 0; i < argc; i++) {
703 if (!strcmp(argv[i], "--")) {
704 has_double_dash = 1;
705 break;
709 for (i = 0; i < argc; i++) {
710 const char *arg = argv[i];
711 if (!strcmp(argv[i], "--")) {
712 break;
713 } else if (!strcmp(arg, "--no-checkout")) {
714 no_checkout = 1;
715 } else if (!strcmp(arg, "--first-parent")) {
716 first_parent_only = 1;
717 } else if (!strcmp(arg, "--term-good") ||
718 !strcmp(arg, "--term-old")) {
719 i++;
720 if (argc <= i)
721 return error(_("'' is not a valid term"));
722 must_write_terms = 1;
723 free((void *) terms->term_good);
724 terms->term_good = xstrdup(argv[i]);
725 } else if (skip_prefix(arg, "--term-good=", &arg) ||
726 skip_prefix(arg, "--term-old=", &arg)) {
727 must_write_terms = 1;
728 free((void *) terms->term_good);
729 terms->term_good = xstrdup(arg);
730 } else if (!strcmp(arg, "--term-bad") ||
731 !strcmp(arg, "--term-new")) {
732 i++;
733 if (argc <= i)
734 return error(_("'' is not a valid term"));
735 must_write_terms = 1;
736 free((void *) terms->term_bad);
737 terms->term_bad = xstrdup(argv[i]);
738 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
739 skip_prefix(arg, "--term-new=", &arg)) {
740 must_write_terms = 1;
741 free((void *) terms->term_bad);
742 terms->term_bad = xstrdup(arg);
743 } else if (starts_with(arg, "--")) {
744 return error(_("unrecognized option: '%s'"), arg);
745 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
746 string_list_append(&revs, oid_to_hex(&oid));
747 } else if (has_double_dash) {
748 die(_("'%s' does not appear to be a valid "
749 "revision"), arg);
750 } else {
751 break;
754 pathspec_pos = i;
757 * The user ran "git bisect start <sha1> <sha1>", hence did not
758 * explicitly specify the terms, but we are already starting to
759 * set references named with the default terms, and won't be able
760 * to change afterwards.
762 if (revs.nr)
763 must_write_terms = 1;
764 for (i = 0; i < revs.nr; i++) {
765 if (bad_seen) {
766 string_list_append(&states, terms->term_good);
767 } else {
768 bad_seen = 1;
769 string_list_append(&states, terms->term_bad);
774 * Verify HEAD
776 head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
777 if (!head)
778 if (get_oid("HEAD", &head_oid))
779 return error(_("bad HEAD - I need a HEAD"));
782 * Check if we are bisecting
784 if (!is_empty_or_missing_file(git_path_bisect_start())) {
785 /* Reset to the rev from where we started */
786 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
787 strbuf_trim(&start_head);
788 if (!no_checkout) {
789 struct child_process cmd = CHILD_PROCESS_INIT;
791 cmd.git_cmd = 1;
792 strvec_pushl(&cmd.args, "checkout", start_head.buf,
793 "--", NULL);
794 if (run_command(&cmd)) {
795 res = error(_("checking out '%s' failed."
796 " Try 'git bisect start "
797 "<valid-branch>'."),
798 start_head.buf);
799 goto finish;
802 } else {
803 /* Get the rev from where we start. */
804 if (!get_oid(head, &head_oid) &&
805 !starts_with(head, "refs/heads/")) {
806 strbuf_reset(&start_head);
807 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
808 } else if (!get_oid(head, &head_oid) &&
809 skip_prefix(head, "refs/heads/", &head)) {
810 strbuf_addstr(&start_head, head);
811 } else {
812 return error(_("bad HEAD - strange symbolic ref"));
817 * Get rid of any old bisect state.
819 if (bisect_clean_state())
820 return BISECT_FAILED;
823 * Write new start state
825 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
827 if (first_parent_only)
828 write_file(git_path_bisect_first_parent(), "\n");
830 if (no_checkout) {
831 if (get_oid(start_head.buf, &oid) < 0) {
832 res = error(_("invalid ref: '%s'"), start_head.buf);
833 goto finish;
835 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
836 UPDATE_REFS_MSG_ON_ERR)) {
837 res = BISECT_FAILED;
838 goto finish;
842 if (pathspec_pos < argc - 1)
843 sq_quote_argv(&bisect_names, argv + pathspec_pos);
844 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
846 for (i = 0; i < states.nr; i++)
847 if (bisect_write(states.items[i].string,
848 revs.items[i].string, terms, 1)) {
849 res = BISECT_FAILED;
850 goto finish;
853 if (must_write_terms && write_terms(terms->term_bad,
854 terms->term_good)) {
855 res = BISECT_FAILED;
856 goto finish;
859 res = bisect_append_log_quoted(argv);
860 if (res)
861 res = BISECT_FAILED;
863 finish:
864 string_list_clear(&revs, 0);
865 string_list_clear(&states, 0);
866 strbuf_release(&start_head);
867 strbuf_release(&bisect_names);
868 if (res)
869 return res;
871 res = bisect_auto_next(terms, NULL);
872 if (!is_bisect_success(res))
873 bisect_clean_state();
874 return res;
877 static inline int file_is_not_empty(const char *path)
879 return !is_empty_or_missing_file(path);
882 static int bisect_autostart(struct bisect_terms *terms)
884 int res;
885 const char *yesno;
887 if (file_is_not_empty(git_path_bisect_start()))
888 return 0;
890 fprintf_ln(stderr, _("You need to start by \"git bisect "
891 "start\"\n"));
893 if (!isatty(STDIN_FILENO))
894 return -1;
897 * TRANSLATORS: Make sure to include [Y] and [n] in your
898 * translation. The program will only accept English input
899 * at this point.
901 yesno = git_prompt(_("Do you want me to do it for you "
902 "[Y/n]? "), PROMPT_ECHO);
903 res = tolower(*yesno) == 'n' ?
904 -1 : bisect_start(terms, 0, empty_strvec);
906 return res;
909 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
910 const char **argv)
912 const char *state;
913 int i, verify_expected = 1;
914 struct object_id oid, expected;
915 struct strbuf buf = STRBUF_INIT;
916 struct oid_array revs = OID_ARRAY_INIT;
918 if (!argc)
919 return error(_("Please call `--bisect-state` with at least one argument"));
921 if (bisect_autostart(terms))
922 return BISECT_FAILED;
924 state = argv[0];
925 if (check_and_set_terms(terms, state) ||
926 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
927 return BISECT_FAILED;
929 argv++;
930 argc--;
931 if (argc > 1 && !strcmp(state, terms->term_bad))
932 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
934 if (argc == 0) {
935 const char *head = "BISECT_HEAD";
936 enum get_oid_result res_head = get_oid(head, &oid);
938 if (res_head == MISSING_OBJECT) {
939 head = "HEAD";
940 res_head = get_oid(head, &oid);
943 if (res_head)
944 error(_("Bad rev input: %s"), head);
945 oid_array_append(&revs, &oid);
949 * All input revs must be checked before executing bisect_write()
950 * to discard junk revs.
953 for (; argc; argc--, argv++) {
954 struct commit *commit;
956 if (get_oid(*argv, &oid)){
957 error(_("Bad rev input: %s"), *argv);
958 oid_array_clear(&revs);
959 return BISECT_FAILED;
962 commit = lookup_commit_reference(the_repository, &oid);
963 if (!commit)
964 die(_("Bad rev input (not a commit): %s"), *argv);
966 oid_array_append(&revs, &commit->object.oid);
969 if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
970 get_oid_hex(buf.buf, &expected) < 0)
971 verify_expected = 0; /* Ignore invalid file contents */
972 strbuf_release(&buf);
974 for (i = 0; i < revs.nr; i++) {
975 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
976 oid_array_clear(&revs);
977 return BISECT_FAILED;
979 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
980 unlink_or_warn(git_path_bisect_ancestors_ok());
981 unlink_or_warn(git_path_bisect_expected_rev());
982 verify_expected = 0;
986 oid_array_clear(&revs);
987 return bisect_auto_next(terms, NULL);
990 static enum bisect_error bisect_log(void)
992 int fd, status;
993 const char* filename = git_path_bisect_log();
995 if (is_empty_or_missing_file(filename))
996 return error(_("We are not bisecting."));
998 fd = open(filename, O_RDONLY);
999 if (fd < 0)
1000 return BISECT_FAILED;
1002 status = copy_fd(fd, STDOUT_FILENO);
1003 close(fd);
1004 return status ? BISECT_FAILED : BISECT_OK;
1007 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1009 const char *p = line->buf + strspn(line->buf, " \t");
1010 char *word_end, *rev;
1012 if ((!skip_prefix(p, "git bisect", &p) &&
1013 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1014 return 0;
1015 p += strspn(p, " \t");
1017 word_end = (char *)p + strcspn(p, " \t");
1018 rev = word_end + strspn(word_end, " \t");
1019 *word_end = '\0'; /* NUL-terminate the word */
1021 get_terms(terms);
1022 if (check_and_set_terms(terms, p))
1023 return -1;
1025 if (!strcmp(p, "start")) {
1026 struct strvec argv = STRVEC_INIT;
1027 int res;
1028 sq_dequote_to_strvec(rev, &argv);
1029 res = bisect_start(terms, argv.nr, argv.v);
1030 strvec_clear(&argv);
1031 return res;
1034 if (one_of(p, terms->term_good,
1035 terms->term_bad, "skip", NULL))
1036 return bisect_write(p, rev, terms, 0);
1038 if (!strcmp(p, "terms")) {
1039 struct strvec argv = STRVEC_INIT;
1040 int res;
1041 sq_dequote_to_strvec(rev, &argv);
1042 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1043 strvec_clear(&argv);
1044 return res;
1046 error(_("'%s'?? what are you talking about?"), p);
1048 return -1;
1051 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1053 FILE *fp = NULL;
1054 enum bisect_error res = BISECT_OK;
1055 struct strbuf line = STRBUF_INIT;
1057 if (is_empty_or_missing_file(filename))
1058 return error(_("cannot read file '%s' for replaying"), filename);
1060 if (bisect_reset(NULL))
1061 return BISECT_FAILED;
1063 fp = fopen(filename, "r");
1064 if (!fp)
1065 return BISECT_FAILED;
1067 while ((strbuf_getline(&line, fp) != EOF) && !res)
1068 res = process_replay_line(terms, &line);
1070 strbuf_release(&line);
1071 fclose(fp);
1073 if (res)
1074 return BISECT_FAILED;
1076 return bisect_auto_next(terms, NULL);
1079 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1080 const char **argv)
1082 int i;
1083 enum bisect_error res;
1084 struct strvec argv_state = STRVEC_INIT;
1086 strvec_push(&argv_state, "skip");
1088 for (i = 0; i < argc; i++) {
1089 const char *dotdot = strstr(argv[i], "..");
1091 if (dotdot) {
1092 struct rev_info revs;
1093 struct commit *commit;
1095 init_revisions(&revs, NULL);
1096 setup_revisions(2, argv + i - 1, &revs, NULL);
1098 if (prepare_revision_walk(&revs))
1099 die(_("revision walk setup failed\n"));
1100 while ((commit = get_revision(&revs)) != NULL)
1101 strvec_push(&argv_state,
1102 oid_to_hex(&commit->object.oid));
1104 reset_revision_walk();
1105 release_revisions(&revs);
1106 } else {
1107 strvec_push(&argv_state, argv[i]);
1110 res = bisect_state(terms, argv_state.nr, argv_state.v);
1112 strvec_clear(&argv_state);
1113 return res;
1116 static int bisect_visualize(struct bisect_terms *terms, int argc,
1117 const char **argv)
1119 struct child_process cmd = CHILD_PROCESS_INIT;
1120 struct strbuf sb = STRBUF_INIT;
1122 if (bisect_next_check(terms, NULL) != 0)
1123 return BISECT_FAILED;
1125 cmd.no_stdin = 1;
1126 if (!argc) {
1127 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1128 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1129 strvec_push(&cmd.args, "gitk");
1130 } else {
1131 strvec_push(&cmd.args, "log");
1132 cmd.git_cmd = 1;
1134 } else {
1135 if (argv[0][0] == '-') {
1136 strvec_push(&cmd.args, "log");
1137 cmd.git_cmd = 1;
1138 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1139 cmd.git_cmd = 1;
1141 strvec_pushv(&cmd.args, argv);
1144 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1146 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1147 sq_dequote_to_strvec(sb.buf, &cmd.args);
1148 strbuf_release(&sb);
1150 return run_command(&cmd);
1153 static int get_first_good(const char *refname UNUSED,
1154 const struct object_id *oid,
1155 int flag UNUSED, void *cb_data)
1157 oidcpy(cb_data, oid);
1158 return 1;
1161 static int do_bisect_run(const char *command)
1163 struct child_process cmd = CHILD_PROCESS_INIT;
1165 printf(_("running %s\n"), command);
1166 cmd.use_shell = 1;
1167 strvec_push(&cmd.args, command);
1168 return run_command(&cmd);
1171 static int verify_good(const struct bisect_terms *terms, const char *command)
1173 int rc;
1174 enum bisect_error res;
1175 struct object_id good_rev;
1176 struct object_id current_rev;
1177 char *good_glob = xstrfmt("%s-*", terms->term_good);
1178 int no_checkout = ref_exists("BISECT_HEAD");
1180 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1181 &good_rev);
1182 free(good_glob);
1184 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1185 return -1;
1187 res = bisect_checkout(&good_rev, no_checkout);
1188 if (res != BISECT_OK)
1189 return -1;
1191 rc = do_bisect_run(command);
1193 res = bisect_checkout(&current_rev, no_checkout);
1194 if (res != BISECT_OK)
1195 return -1;
1197 return rc;
1200 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1202 int res = BISECT_OK;
1203 struct strbuf command = STRBUF_INIT;
1204 const char *new_state;
1205 int temporary_stdout_fd, saved_stdout;
1206 int is_first_run = 1;
1208 if (bisect_next_check(terms, NULL))
1209 return BISECT_FAILED;
1211 if (!argc) {
1212 error(_("bisect run failed: no command provided."));
1213 return BISECT_FAILED;
1216 sq_quote_argv(&command, argv);
1217 strbuf_ltrim(&command);
1218 while (1) {
1219 res = do_bisect_run(command.buf);
1222 * Exit code 126 and 127 can either come from the shell
1223 * if it was unable to execute or even find the script,
1224 * or from the script itself. Check with a known-good
1225 * revision to avoid trashing the bisect run due to a
1226 * missing or non-executable script.
1228 if (is_first_run && (res == 126 || res == 127)) {
1229 int rc = verify_good(terms, command.buf);
1230 is_first_run = 0;
1231 if (rc < 0 || 128 <= rc) {
1232 error(_("unable to verify %s on good"
1233 " revision"), command.buf);
1234 res = BISECT_FAILED;
1235 break;
1237 if (rc == res) {
1238 error(_("bogus exit code %d for good revision"),
1239 rc);
1240 res = BISECT_FAILED;
1241 break;
1245 if (res < 0 || 128 <= res) {
1246 error(_("bisect run failed: exit code %d from"
1247 " %s is < 0 or >= 128"), res, command.buf);
1248 break;
1251 if (res == 125)
1252 new_state = "skip";
1253 else if (!res)
1254 new_state = terms->term_good;
1255 else
1256 new_state = terms->term_bad;
1258 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1260 if (temporary_stdout_fd < 0) {
1261 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1262 break;
1265 fflush(stdout);
1266 saved_stdout = dup(1);
1267 dup2(temporary_stdout_fd, 1);
1269 res = bisect_state(terms, 1, &new_state);
1271 fflush(stdout);
1272 dup2(saved_stdout, 1);
1273 close(saved_stdout);
1274 close(temporary_stdout_fd);
1276 print_file_to_stdout(git_path_bisect_run());
1278 if (res == BISECT_ONLY_SKIPPED_LEFT)
1279 error(_("bisect run cannot continue any more"));
1280 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1281 puts(_("bisect run success"));
1282 res = BISECT_OK;
1283 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1284 puts(_("bisect found first bad commit"));
1285 res = BISECT_OK;
1286 } else if (res) {
1287 error(_("bisect run failed: 'git bisect %s'"
1288 " exited with error code %d"), new_state, res);
1289 } else {
1290 continue;
1292 break;
1295 strbuf_release(&command);
1296 return res;
1299 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1301 if (argc > 1)
1302 return error(_("'%s' requires either no argument or a commit"),
1303 "git bisect reset");
1304 return bisect_reset(argc ? argv[0] : NULL);
1307 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1309 int res;
1310 struct bisect_terms terms = { 0 };
1312 if (argc > 1)
1313 return error(_("'%s' requires 0 or 1 argument"),
1314 "git bisect terms");
1315 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1316 free_terms(&terms);
1317 return res;
1320 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1322 int res;
1323 struct bisect_terms terms = { 0 };
1325 set_terms(&terms, "bad", "good");
1326 res = bisect_start(&terms, argc, argv);
1327 free_terms(&terms);
1328 return res;
1331 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1333 int res;
1334 struct bisect_terms terms = { 0 };
1336 if (argc)
1337 return error(_("'%s' requires 0 arguments"),
1338 "git bisect next");
1339 get_terms(&terms);
1340 res = bisect_next(&terms, prefix);
1341 free_terms(&terms);
1342 return res;
1345 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1347 return bisect_log();
1350 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1352 int res;
1353 struct bisect_terms terms = { 0 };
1355 if (argc != 1)
1356 return error(_("no logfile given"));
1357 set_terms(&terms, "bad", "good");
1358 res = bisect_replay(&terms, argv[0]);
1359 free_terms(&terms);
1360 return res;
1363 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1365 int res;
1366 struct bisect_terms terms = { 0 };
1368 set_terms(&terms, "bad", "good");
1369 get_terms(&terms);
1370 res = bisect_skip(&terms, argc, argv);
1371 free_terms(&terms);
1372 return res;
1375 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1377 int res;
1378 struct bisect_terms terms = { 0 };
1380 get_terms(&terms);
1381 res = bisect_visualize(&terms, argc, argv);
1382 free_terms(&terms);
1383 return res;
1386 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1388 int res;
1389 struct bisect_terms terms = { 0 };
1391 if (!argc)
1392 return error(_("'%s' failed: no command provided."), "git bisect run");
1393 get_terms(&terms);
1394 res = bisect_run(&terms, argc, argv);
1395 free_terms(&terms);
1396 return res;
1399 int cmd_bisect(int argc, const char **argv, const char *prefix)
1401 int res = 0;
1402 parse_opt_subcommand_fn *fn = NULL;
1403 struct option options[] = {
1404 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1405 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1406 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1407 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1408 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1409 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1410 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1411 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1412 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1413 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1414 OPT_END()
1416 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1417 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1419 if (!fn) {
1420 struct bisect_terms terms = { 0 };
1422 if (!argc)
1423 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1425 set_terms(&terms, "bad", "good");
1426 get_terms(&terms);
1427 if (check_and_set_terms(&terms, argv[0]))
1428 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1429 options, argv[0]);
1430 res = bisect_state(&terms, argc, argv);
1431 free_terms(&terms);
1432 } else {
1433 argc--;
1434 argv++;
1435 res = fn(argc, argv, prefix);
1438 return is_bisect_success(res) ? 0 : -res;