banned.h: mark `strtok()` and `strtok_r()` as banned
[git/debian.git] / builtin / bisect.c
blob26f07357a03ead1e0bba6946c4f3afb68ed60eeb
1 #include "builtin.h"
2 #include "cache.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "hex.h"
6 #include "parse-options.h"
7 #include "bisect.h"
8 #include "refs.h"
9 #include "dir.h"
10 #include "strvec.h"
11 #include "run-command.h"
12 #include "prompt.h"
13 #include "quote.h"
14 #include "revision.h"
15 #include "wrapper.h"
17 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
18 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
19 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
20 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
21 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
22 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
23 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
24 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
26 #define BUILTIN_GIT_BISECT_START_USAGE \
27 N_("git bisect start [--term-{new,bad}=<term> --term-{old,good}=<term>]" \
28 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
29 " [<pathspec>...]")
30 #define BUILTIN_GIT_BISECT_STATE_USAGE \
31 N_("git bisect (good|bad) [<rev>...]")
32 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
33 "git bisect terms [--term-good | --term-bad]"
34 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
35 N_("git bisect skip [(<rev>|<range>)...]")
36 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
37 "git bisect next"
38 #define BUILTIN_GIT_BISECT_RESET_USAGE \
39 N_("git bisect reset [<commit>]")
40 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
41 "git bisect visualize"
42 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
43 N_("git bisect replay <logfile>")
44 #define BUILTIN_GIT_BISECT_LOG_USAGE \
45 "git bisect log"
46 #define BUILTIN_GIT_BISECT_RUN_USAGE \
47 N_("git bisect run <cmd>...")
49 static const char * const git_bisect_usage[] = {
50 BUILTIN_GIT_BISECT_START_USAGE,
51 BUILTIN_GIT_BISECT_STATE_USAGE,
52 BUILTIN_GIT_BISECT_TERMS_USAGE,
53 BUILTIN_GIT_BISECT_SKIP_USAGE,
54 BUILTIN_GIT_BISECT_NEXT_USAGE,
55 BUILTIN_GIT_BISECT_RESET_USAGE,
56 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
57 BUILTIN_GIT_BISECT_REPLAY_USAGE,
58 BUILTIN_GIT_BISECT_LOG_USAGE,
59 BUILTIN_GIT_BISECT_RUN_USAGE,
60 NULL
63 struct add_bisect_ref_data {
64 struct rev_info *revs;
65 unsigned int object_flags;
68 struct bisect_terms {
69 char *term_good;
70 char *term_bad;
73 static void free_terms(struct bisect_terms *terms)
75 FREE_AND_NULL(terms->term_good);
76 FREE_AND_NULL(terms->term_bad);
79 static void set_terms(struct bisect_terms *terms, const char *bad,
80 const char *good)
82 free((void *)terms->term_good);
83 terms->term_good = xstrdup(good);
84 free((void *)terms->term_bad);
85 terms->term_bad = xstrdup(bad);
88 static const char vocab_bad[] = "bad|new";
89 static const char vocab_good[] = "good|old";
91 static int bisect_autostart(struct bisect_terms *terms);
94 * Check whether the string `term` belongs to the set of strings
95 * included in the variable arguments.
97 LAST_ARG_MUST_BE_NULL
98 static int one_of(const char *term, ...)
100 int res = 0;
101 va_list matches;
102 const char *match;
104 va_start(matches, term);
105 while (!res && (match = va_arg(matches, const char *)))
106 res = !strcmp(term, match);
107 va_end(matches);
109 return res;
113 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
114 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
115 * that indicate special success.
118 static int is_bisect_success(enum bisect_error res)
120 return !res ||
121 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
122 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
125 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
127 FILE *fp = NULL;
128 int res = 0;
130 if (strcmp(mode, "w") && strcmp(mode, "a"))
131 BUG("write-in-file does not support '%s' mode", mode);
132 fp = fopen(path, mode);
133 if (!fp)
134 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
135 res = vfprintf(fp, format, args);
137 if (res < 0) {
138 int saved_errno = errno;
139 fclose(fp);
140 errno = saved_errno;
141 return error_errno(_("could not write to file '%s'"), path);
144 return fclose(fp);
147 __attribute__((format (printf, 2, 3)))
148 static int write_to_file(const char *path, const char *format, ...)
150 int res;
151 va_list args;
153 va_start(args, format);
154 res = write_in_file(path, "w", format, args);
155 va_end(args);
157 return res;
160 __attribute__((format (printf, 2, 3)))
161 static int append_to_file(const char *path, const char *format, ...)
163 int res;
164 va_list args;
166 va_start(args, format);
167 res = write_in_file(path, "a", format, args);
168 va_end(args);
170 return res;
173 static int print_file_to_stdout(const char *path)
175 int fd = open(path, O_RDONLY);
176 int ret = 0;
178 if (fd < 0)
179 return error_errno(_("cannot open file '%s' for reading"), path);
180 if (copy_fd(fd, 1) < 0)
181 ret = error_errno(_("failed to read '%s'"), path);
182 close(fd);
183 return ret;
186 static int check_term_format(const char *term, const char *orig_term)
188 int res;
189 char *new_term = xstrfmt("refs/bisect/%s", term);
191 res = check_refname_format(new_term, 0);
192 free(new_term);
194 if (res)
195 return error(_("'%s' is not a valid term"), term);
197 if (one_of(term, "help", "start", "skip", "next", "reset",
198 "visualize", "view", "replay", "log", "run", "terms", NULL))
199 return error(_("can't use the builtin command '%s' as a term"), term);
202 * In theory, nothing prevents swapping completely good and bad,
203 * but this situation could be confusing and hasn't been tested
204 * enough. Forbid it for now.
207 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
208 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
209 return error(_("can't change the meaning of the term '%s'"), term);
211 return 0;
214 static int write_terms(const char *bad, const char *good)
216 int res;
218 if (!strcmp(bad, good))
219 return error(_("please use two different terms"));
221 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
222 return -1;
224 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
226 return res;
229 static int bisect_reset(const char *commit)
231 struct strbuf branch = STRBUF_INIT;
233 if (!commit) {
234 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
235 printf(_("We are not bisecting.\n"));
236 return 0;
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 (!ref_exists("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, char *fmt, const char *state,
267 struct commit *commit)
269 struct pretty_print_context pp = {0};
270 struct strbuf commit_msg = STRBUF_INIT;
271 char *label = xstrfmt(fmt, state);
273 repo_format_commit_message(the_repository, commit, "%s", &commit_msg,
274 &pp);
276 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
277 commit_msg.buf);
279 strbuf_release(&commit_msg);
280 free(label);
283 static int bisect_write(const char *state, const char *rev,
284 const struct bisect_terms *terms, int nolog)
286 struct strbuf tag = STRBUF_INIT;
287 struct object_id oid;
288 struct commit *commit;
289 FILE *fp = NULL;
290 int res = 0;
292 if (!strcmp(state, terms->term_bad)) {
293 strbuf_addf(&tag, "refs/bisect/%s", state);
294 } else if (one_of(state, terms->term_good, "skip", NULL)) {
295 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
296 } else {
297 res = error(_("Bad bisect_write argument: %s"), state);
298 goto finish;
301 if (repo_get_oid(the_repository, rev, &oid)) {
302 res = error(_("couldn't get the oid of the rev '%s'"), rev);
303 goto finish;
306 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
307 UPDATE_REFS_MSG_ON_ERR)) {
308 res = -1;
309 goto finish;
312 fp = fopen(git_path_bisect_log(), "a");
313 if (!fp) {
314 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
315 goto finish;
318 commit = lookup_commit_reference(the_repository, &oid);
319 log_commit(fp, "%s", state, commit);
321 if (!nolog)
322 fprintf(fp, "git bisect %s %s\n", state, rev);
324 finish:
325 if (fp)
326 fclose(fp);
327 strbuf_release(&tag);
328 return res;
331 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
333 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
335 if (one_of(cmd, "skip", "start", "terms", NULL))
336 return 0;
338 if (has_term_file && strcmp(cmd, terms->term_bad) &&
339 strcmp(cmd, terms->term_good))
340 return error(_("Invalid command: you're currently in a "
341 "%s/%s bisect"), terms->term_bad,
342 terms->term_good);
344 if (!has_term_file) {
345 if (one_of(cmd, "bad", "good", NULL)) {
346 set_terms(terms, "bad", "good");
347 return write_terms(terms->term_bad, terms->term_good);
349 if (one_of(cmd, "new", "old", NULL)) {
350 set_terms(terms, "new", "old");
351 return write_terms(terms->term_bad, terms->term_good);
355 return 0;
358 static int inc_nr(const char *refname UNUSED,
359 const struct object_id *oid UNUSED,
360 int flag UNUSED, void *cb_data)
362 unsigned int *nr = (unsigned int *)cb_data;
363 (*nr)++;
364 return 0;
367 static const char need_bad_and_good_revision_warning[] =
368 N_("You need to give me at least one %s and %s revision.\n"
369 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
371 static const char need_bisect_start_warning[] =
372 N_("You need to start by \"git bisect start\".\n"
373 "You then need to give me at least one %s and %s revision.\n"
374 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
376 static int decide_next(const struct bisect_terms *terms,
377 const char *current_term, int missing_good,
378 int missing_bad)
380 if (!missing_good && !missing_bad)
381 return 0;
382 if (!current_term)
383 return -1;
385 if (missing_good && !missing_bad &&
386 !strcmp(current_term, terms->term_good)) {
387 char *yesno;
389 * have bad (or new) but not good (or old). We could bisect
390 * although this is less optimum.
392 warning(_("bisecting only with a %s commit"), terms->term_bad);
393 if (!isatty(0))
394 return 0;
396 * TRANSLATORS: Make sure to include [Y] and [n] in your
397 * translation. The program will only accept English input
398 * at this point.
400 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
401 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
402 return -1;
403 return 0;
406 if (!is_empty_or_missing_file(git_path_bisect_start()))
407 return error(_(need_bad_and_good_revision_warning),
408 vocab_bad, vocab_good, vocab_bad, vocab_good);
409 else
410 return error(_(need_bisect_start_warning),
411 vocab_good, vocab_bad, vocab_good, vocab_bad);
414 static void bisect_status(struct bisect_state *state,
415 const struct bisect_terms *terms)
417 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
418 char *good_glob = xstrfmt("%s-*", terms->term_good);
420 if (ref_exists(bad_ref))
421 state->nr_bad = 1;
423 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
424 (void *) &state->nr_good);
426 free(good_glob);
427 free(bad_ref);
430 __attribute__((format (printf, 1, 2)))
431 static void bisect_log_printf(const char *fmt, ...)
433 struct strbuf buf = STRBUF_INIT;
434 va_list ap;
436 va_start(ap, fmt);
437 strbuf_vaddf(&buf, fmt, ap);
438 va_end(ap);
440 printf("%s", buf.buf);
441 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
443 strbuf_release(&buf);
446 static void bisect_print_status(const struct bisect_terms *terms)
448 struct bisect_state state = { 0 };
450 bisect_status(&state, terms);
452 /* If we had both, we'd already be started, and shouldn't get here. */
453 if (state.nr_good && state.nr_bad)
454 return;
456 if (!state.nr_good && !state.nr_bad)
457 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
458 else if (state.nr_good)
459 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
460 "status: waiting for bad commit, %d good commits known\n",
461 state.nr_good), state.nr_good);
462 else
463 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
466 static int bisect_next_check(const struct bisect_terms *terms,
467 const char *current_term)
469 struct bisect_state state = { 0 };
470 bisect_status(&state, terms);
471 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
474 static int get_terms(struct bisect_terms *terms)
476 struct strbuf str = STRBUF_INIT;
477 FILE *fp = NULL;
478 int res = 0;
480 fp = fopen(git_path_bisect_terms(), "r");
481 if (!fp) {
482 res = -1;
483 goto finish;
486 free_terms(terms);
487 strbuf_getline_lf(&str, fp);
488 terms->term_bad = strbuf_detach(&str, NULL);
489 strbuf_getline_lf(&str, fp);
490 terms->term_good = strbuf_detach(&str, NULL);
492 finish:
493 if (fp)
494 fclose(fp);
495 strbuf_release(&str);
496 return res;
499 static int bisect_terms(struct bisect_terms *terms, const char *option)
501 if (get_terms(terms))
502 return error(_("no terms defined"));
504 if (!option) {
505 printf(_("Your current terms are %s for the old state\n"
506 "and %s for the new state.\n"),
507 terms->term_good, terms->term_bad);
508 return 0;
510 if (one_of(option, "--term-good", "--term-old", NULL))
511 printf("%s\n", terms->term_good);
512 else if (one_of(option, "--term-bad", "--term-new", NULL))
513 printf("%s\n", terms->term_bad);
514 else
515 return error(_("invalid argument %s for 'git bisect terms'.\n"
516 "Supported options are: "
517 "--term-good|--term-old and "
518 "--term-bad|--term-new."), option);
520 return 0;
523 static int bisect_append_log_quoted(const char **argv)
525 int res = 0;
526 FILE *fp = fopen(git_path_bisect_log(), "a");
527 struct strbuf orig_args = STRBUF_INIT;
529 if (!fp)
530 return -1;
532 if (fprintf(fp, "git bisect start") < 1) {
533 res = -1;
534 goto finish;
537 sq_quote_argv(&orig_args, argv);
538 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
539 res = -1;
541 finish:
542 fclose(fp);
543 strbuf_release(&orig_args);
544 return res;
547 static int add_bisect_ref(const char *refname, const struct object_id *oid,
548 int flags UNUSED, void *cb)
550 struct add_bisect_ref_data *data = cb;
552 add_pending_oid(data->revs, refname, oid, data->object_flags);
554 return 0;
557 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
559 int res = 0;
560 struct add_bisect_ref_data cb = { revs };
561 char *good = xstrfmt("%s-*", terms->term_good);
564 * We cannot use terms->term_bad directly in
565 * for_each_glob_ref_in() and we have to append a '*' to it,
566 * otherwise for_each_glob_ref_in() will append '/' and '*'.
568 char *bad = xstrfmt("%s*", terms->term_bad);
571 * It is important to reset the flags used by revision walks
572 * as the previous call to bisect_next_all() in turn
573 * sets up a revision walk.
575 reset_revision_walk();
576 repo_init_revisions(the_repository, revs, NULL);
577 setup_revisions(0, NULL, revs, NULL);
578 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
579 cb.object_flags = UNINTERESTING;
580 for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
581 if (prepare_revision_walk(revs))
582 res = error(_("revision walk setup failed\n"));
584 free(good);
585 free(bad);
586 return res;
589 static int bisect_skipped_commits(struct bisect_terms *terms)
591 int res;
592 FILE *fp = NULL;
593 struct rev_info revs;
594 struct commit *commit;
595 struct pretty_print_context pp = {0};
596 struct strbuf commit_name = STRBUF_INIT;
598 res = prepare_revs(terms, &revs);
599 if (res)
600 return res;
602 fp = fopen(git_path_bisect_log(), "a");
603 if (!fp)
604 return error_errno(_("could not open '%s' for appending"),
605 git_path_bisect_log());
607 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
608 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
610 while ((commit = get_revision(&revs)) != NULL) {
611 strbuf_reset(&commit_name);
612 repo_format_commit_message(the_repository, commit, "%s",
613 &commit_name, &pp);
614 fprintf(fp, "# possible first %s commit: [%s] %s\n",
615 terms->term_bad, oid_to_hex(&commit->object.oid),
616 commit_name.buf);
620 * Reset the flags used by revision walks in case
621 * there is another revision walk after this one.
623 reset_revision_walk();
625 strbuf_release(&commit_name);
626 release_revisions(&revs);
627 fclose(fp);
628 return 0;
631 static int bisect_successful(struct bisect_terms *terms)
633 struct object_id oid;
634 struct commit *commit;
635 struct pretty_print_context pp = {0};
636 struct strbuf commit_name = STRBUF_INIT;
637 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
638 int res;
640 read_ref(bad_ref, &oid);
641 commit = lookup_commit_reference_by_name(bad_ref);
642 repo_format_commit_message(the_repository, commit, "%s", &commit_name,
643 &pp);
645 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
646 terms->term_bad, oid_to_hex(&commit->object.oid),
647 commit_name.buf);
649 strbuf_release(&commit_name);
650 free(bad_ref);
651 return res;
654 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
656 enum bisect_error res;
658 if (bisect_autostart(terms))
659 return BISECT_FAILED;
661 if (bisect_next_check(terms, terms->term_good))
662 return BISECT_FAILED;
664 /* Perform all bisection computation */
665 res = bisect_next_all(the_repository, prefix);
667 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
668 res = bisect_successful(terms);
669 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
670 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
671 res = bisect_skipped_commits(terms);
672 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
674 return res;
677 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
679 if (bisect_next_check(terms, NULL)) {
680 bisect_print_status(terms);
681 return BISECT_OK;
684 return bisect_next(terms, prefix);
687 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
688 const char **argv)
690 int no_checkout = 0;
691 int first_parent_only = 0;
692 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
693 int flags, pathspec_pos;
694 enum bisect_error res = BISECT_OK;
695 struct string_list revs = STRING_LIST_INIT_DUP;
696 struct string_list states = STRING_LIST_INIT_DUP;
697 struct strbuf start_head = STRBUF_INIT;
698 struct strbuf bisect_names = STRBUF_INIT;
699 struct object_id head_oid;
700 struct object_id oid;
701 const char *head;
703 if (is_bare_repository())
704 no_checkout = 1;
707 * Check for one bad and then some good revisions
709 for (i = 0; i < argc; i++) {
710 if (!strcmp(argv[i], "--")) {
711 has_double_dash = 1;
712 break;
716 for (i = 0; i < argc; i++) {
717 const char *arg = argv[i];
718 if (!strcmp(argv[i], "--")) {
719 break;
720 } else if (!strcmp(arg, "--no-checkout")) {
721 no_checkout = 1;
722 } else if (!strcmp(arg, "--first-parent")) {
723 first_parent_only = 1;
724 } else if (!strcmp(arg, "--term-good") ||
725 !strcmp(arg, "--term-old")) {
726 i++;
727 if (argc <= i)
728 return error(_("'' is not a valid term"));
729 must_write_terms = 1;
730 free((void *) terms->term_good);
731 terms->term_good = xstrdup(argv[i]);
732 } else if (skip_prefix(arg, "--term-good=", &arg) ||
733 skip_prefix(arg, "--term-old=", &arg)) {
734 must_write_terms = 1;
735 free((void *) terms->term_good);
736 terms->term_good = xstrdup(arg);
737 } else if (!strcmp(arg, "--term-bad") ||
738 !strcmp(arg, "--term-new")) {
739 i++;
740 if (argc <= i)
741 return error(_("'' is not a valid term"));
742 must_write_terms = 1;
743 free((void *) terms->term_bad);
744 terms->term_bad = xstrdup(argv[i]);
745 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
746 skip_prefix(arg, "--term-new=", &arg)) {
747 must_write_terms = 1;
748 free((void *) terms->term_bad);
749 terms->term_bad = xstrdup(arg);
750 } else if (starts_with(arg, "--")) {
751 return error(_("unrecognized option: '%s'"), arg);
752 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
753 string_list_append(&revs, oid_to_hex(&oid));
754 } else if (has_double_dash) {
755 die(_("'%s' does not appear to be a valid "
756 "revision"), arg);
757 } else {
758 break;
761 pathspec_pos = i;
764 * The user ran "git bisect start <sha1> <sha1>", hence did not
765 * explicitly specify the terms, but we are already starting to
766 * set references named with the default terms, and won't be able
767 * to change afterwards.
769 if (revs.nr)
770 must_write_terms = 1;
771 for (i = 0; i < revs.nr; i++) {
772 if (bad_seen) {
773 string_list_append(&states, terms->term_good);
774 } else {
775 bad_seen = 1;
776 string_list_append(&states, terms->term_bad);
781 * Verify HEAD
783 head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
784 if (!head)
785 if (repo_get_oid(the_repository, "HEAD", &head_oid))
786 return error(_("bad HEAD - I need a HEAD"));
789 * Check if we are bisecting
791 if (!is_empty_or_missing_file(git_path_bisect_start())) {
792 /* Reset to the rev from where we started */
793 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
794 strbuf_trim(&start_head);
795 if (!no_checkout) {
796 struct child_process cmd = CHILD_PROCESS_INIT;
798 cmd.git_cmd = 1;
799 strvec_pushl(&cmd.args, "checkout", start_head.buf,
800 "--", NULL);
801 if (run_command(&cmd)) {
802 res = error(_("checking out '%s' failed."
803 " Try 'git bisect start "
804 "<valid-branch>'."),
805 start_head.buf);
806 goto finish;
809 } else {
810 /* Get the rev from where we start. */
811 if (!repo_get_oid(the_repository, head, &head_oid) &&
812 !starts_with(head, "refs/heads/")) {
813 strbuf_reset(&start_head);
814 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
815 } else if (!repo_get_oid(the_repository, head, &head_oid) &&
816 skip_prefix(head, "refs/heads/", &head)) {
817 strbuf_addstr(&start_head, head);
818 } else {
819 return error(_("bad HEAD - strange symbolic ref"));
824 * Get rid of any old bisect state.
826 if (bisect_clean_state())
827 return BISECT_FAILED;
830 * Write new start state
832 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
834 if (first_parent_only)
835 write_file(git_path_bisect_first_parent(), "\n");
837 if (no_checkout) {
838 if (repo_get_oid(the_repository, start_head.buf, &oid) < 0) {
839 res = error(_("invalid ref: '%s'"), start_head.buf);
840 goto finish;
842 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
843 UPDATE_REFS_MSG_ON_ERR)) {
844 res = BISECT_FAILED;
845 goto finish;
849 if (pathspec_pos < argc - 1)
850 sq_quote_argv(&bisect_names, argv + pathspec_pos);
851 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
853 for (i = 0; i < states.nr; i++)
854 if (bisect_write(states.items[i].string,
855 revs.items[i].string, terms, 1)) {
856 res = BISECT_FAILED;
857 goto finish;
860 if (must_write_terms && write_terms(terms->term_bad,
861 terms->term_good)) {
862 res = BISECT_FAILED;
863 goto finish;
866 res = bisect_append_log_quoted(argv);
867 if (res)
868 res = BISECT_FAILED;
870 finish:
871 string_list_clear(&revs, 0);
872 string_list_clear(&states, 0);
873 strbuf_release(&start_head);
874 strbuf_release(&bisect_names);
875 if (res)
876 return res;
878 res = bisect_auto_next(terms, NULL);
879 if (!is_bisect_success(res))
880 bisect_clean_state();
881 return res;
884 static inline int file_is_not_empty(const char *path)
886 return !is_empty_or_missing_file(path);
889 static int bisect_autostart(struct bisect_terms *terms)
891 int res;
892 const char *yesno;
894 if (file_is_not_empty(git_path_bisect_start()))
895 return 0;
897 fprintf_ln(stderr, _("You need to start by \"git bisect "
898 "start\"\n"));
900 if (!isatty(STDIN_FILENO))
901 return -1;
904 * TRANSLATORS: Make sure to include [Y] and [n] in your
905 * translation. The program will only accept English input
906 * at this point.
908 yesno = git_prompt(_("Do you want me to do it for you "
909 "[Y/n]? "), PROMPT_ECHO);
910 res = tolower(*yesno) == 'n' ?
911 -1 : bisect_start(terms, 0, empty_strvec);
913 return res;
916 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
917 const char **argv)
919 const char *state;
920 int i, verify_expected = 1;
921 struct object_id oid, expected;
922 struct strbuf buf = STRBUF_INIT;
923 struct oid_array revs = OID_ARRAY_INIT;
925 if (!argc)
926 return error(_("Please call `--bisect-state` with at least one argument"));
928 if (bisect_autostart(terms))
929 return BISECT_FAILED;
931 state = argv[0];
932 if (check_and_set_terms(terms, state) ||
933 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
934 return BISECT_FAILED;
936 argv++;
937 argc--;
938 if (argc > 1 && !strcmp(state, terms->term_bad))
939 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
941 if (argc == 0) {
942 const char *head = "BISECT_HEAD";
943 enum get_oid_result res_head = repo_get_oid(the_repository,
944 head, &oid);
946 if (res_head == MISSING_OBJECT) {
947 head = "HEAD";
948 res_head = repo_get_oid(the_repository, head, &oid);
951 if (res_head)
952 error(_("Bad rev input: %s"), head);
953 oid_array_append(&revs, &oid);
957 * All input revs must be checked before executing bisect_write()
958 * to discard junk revs.
961 for (; argc; argc--, argv++) {
962 struct commit *commit;
964 if (repo_get_oid(the_repository, *argv, &oid)){
965 error(_("Bad rev input: %s"), *argv);
966 oid_array_clear(&revs);
967 return BISECT_FAILED;
970 commit = lookup_commit_reference(the_repository, &oid);
971 if (!commit)
972 die(_("Bad rev input (not a commit): %s"), *argv);
974 oid_array_append(&revs, &commit->object.oid);
977 if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
978 get_oid_hex(buf.buf, &expected) < 0)
979 verify_expected = 0; /* Ignore invalid file contents */
980 strbuf_release(&buf);
982 for (i = 0; i < revs.nr; i++) {
983 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
984 oid_array_clear(&revs);
985 return BISECT_FAILED;
987 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
988 unlink_or_warn(git_path_bisect_ancestors_ok());
989 unlink_or_warn(git_path_bisect_expected_rev());
990 verify_expected = 0;
994 oid_array_clear(&revs);
995 return bisect_auto_next(terms, NULL);
998 static enum bisect_error bisect_log(void)
1000 int fd, status;
1001 const char* filename = git_path_bisect_log();
1003 if (is_empty_or_missing_file(filename))
1004 return error(_("We are not bisecting."));
1006 fd = open(filename, O_RDONLY);
1007 if (fd < 0)
1008 return BISECT_FAILED;
1010 status = copy_fd(fd, STDOUT_FILENO);
1011 close(fd);
1012 return status ? BISECT_FAILED : BISECT_OK;
1015 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1017 const char *p = line->buf + strspn(line->buf, " \t");
1018 char *word_end, *rev;
1020 if ((!skip_prefix(p, "git bisect", &p) &&
1021 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1022 return 0;
1023 p += strspn(p, " \t");
1025 word_end = (char *)p + strcspn(p, " \t");
1026 rev = word_end + strspn(word_end, " \t");
1027 *word_end = '\0'; /* NUL-terminate the word */
1029 get_terms(terms);
1030 if (check_and_set_terms(terms, p))
1031 return -1;
1033 if (!strcmp(p, "start")) {
1034 struct strvec argv = STRVEC_INIT;
1035 int res;
1036 sq_dequote_to_strvec(rev, &argv);
1037 res = bisect_start(terms, argv.nr, argv.v);
1038 strvec_clear(&argv);
1039 return res;
1042 if (one_of(p, terms->term_good,
1043 terms->term_bad, "skip", NULL))
1044 return bisect_write(p, rev, terms, 0);
1046 if (!strcmp(p, "terms")) {
1047 struct strvec argv = STRVEC_INIT;
1048 int res;
1049 sq_dequote_to_strvec(rev, &argv);
1050 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1051 strvec_clear(&argv);
1052 return res;
1054 error(_("'%s'?? what are you talking about?"), p);
1056 return -1;
1059 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1061 FILE *fp = NULL;
1062 enum bisect_error res = BISECT_OK;
1063 struct strbuf line = STRBUF_INIT;
1065 if (is_empty_or_missing_file(filename))
1066 return error(_("cannot read file '%s' for replaying"), filename);
1068 if (bisect_reset(NULL))
1069 return BISECT_FAILED;
1071 fp = fopen(filename, "r");
1072 if (!fp)
1073 return BISECT_FAILED;
1075 while ((strbuf_getline(&line, fp) != EOF) && !res)
1076 res = process_replay_line(terms, &line);
1078 strbuf_release(&line);
1079 fclose(fp);
1081 if (res)
1082 return BISECT_FAILED;
1084 return bisect_auto_next(terms, NULL);
1087 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1088 const char **argv)
1090 int i;
1091 enum bisect_error res;
1092 struct strvec argv_state = STRVEC_INIT;
1094 strvec_push(&argv_state, "skip");
1096 for (i = 0; i < argc; i++) {
1097 const char *dotdot = strstr(argv[i], "..");
1099 if (dotdot) {
1100 struct rev_info revs;
1101 struct commit *commit;
1103 repo_init_revisions(the_repository, &revs, NULL);
1104 setup_revisions(2, argv + i - 1, &revs, NULL);
1106 if (prepare_revision_walk(&revs))
1107 die(_("revision walk setup failed\n"));
1108 while ((commit = get_revision(&revs)) != NULL)
1109 strvec_push(&argv_state,
1110 oid_to_hex(&commit->object.oid));
1112 reset_revision_walk();
1113 release_revisions(&revs);
1114 } else {
1115 strvec_push(&argv_state, argv[i]);
1118 res = bisect_state(terms, argv_state.nr, argv_state.v);
1120 strvec_clear(&argv_state);
1121 return res;
1124 static int bisect_visualize(struct bisect_terms *terms, int argc,
1125 const char **argv)
1127 struct child_process cmd = CHILD_PROCESS_INIT;
1128 struct strbuf sb = STRBUF_INIT;
1130 if (bisect_next_check(terms, NULL) != 0)
1131 return BISECT_FAILED;
1133 cmd.no_stdin = 1;
1134 if (!argc) {
1135 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1136 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1137 strvec_push(&cmd.args, "gitk");
1138 } else {
1139 strvec_push(&cmd.args, "log");
1140 cmd.git_cmd = 1;
1142 } else {
1143 if (argv[0][0] == '-') {
1144 strvec_push(&cmd.args, "log");
1145 cmd.git_cmd = 1;
1146 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1147 cmd.git_cmd = 1;
1149 strvec_pushv(&cmd.args, argv);
1152 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1154 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1155 sq_dequote_to_strvec(sb.buf, &cmd.args);
1156 strbuf_release(&sb);
1158 return run_command(&cmd);
1161 static int get_first_good(const char *refname UNUSED,
1162 const struct object_id *oid,
1163 int flag UNUSED, void *cb_data)
1165 oidcpy(cb_data, oid);
1166 return 1;
1169 static int do_bisect_run(const char *command)
1171 struct child_process cmd = CHILD_PROCESS_INIT;
1173 printf(_("running %s\n"), command);
1174 cmd.use_shell = 1;
1175 strvec_push(&cmd.args, command);
1176 return run_command(&cmd);
1179 static int verify_good(const struct bisect_terms *terms, const char *command)
1181 int rc;
1182 enum bisect_error res;
1183 struct object_id good_rev;
1184 struct object_id current_rev;
1185 char *good_glob = xstrfmt("%s-*", terms->term_good);
1186 int no_checkout = ref_exists("BISECT_HEAD");
1188 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1189 &good_rev);
1190 free(good_glob);
1192 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1193 return -1;
1195 res = bisect_checkout(&good_rev, no_checkout);
1196 if (res != BISECT_OK)
1197 return -1;
1199 rc = do_bisect_run(command);
1201 res = bisect_checkout(&current_rev, no_checkout);
1202 if (res != BISECT_OK)
1203 return -1;
1205 return rc;
1208 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1210 int res = BISECT_OK;
1211 struct strbuf command = STRBUF_INIT;
1212 const char *new_state;
1213 int temporary_stdout_fd, saved_stdout;
1214 int is_first_run = 1;
1216 if (bisect_next_check(terms, NULL))
1217 return BISECT_FAILED;
1219 if (!argc) {
1220 error(_("bisect run failed: no command provided."));
1221 return BISECT_FAILED;
1224 sq_quote_argv(&command, argv);
1225 strbuf_ltrim(&command);
1226 while (1) {
1227 res = do_bisect_run(command.buf);
1230 * Exit code 126 and 127 can either come from the shell
1231 * if it was unable to execute or even find the script,
1232 * or from the script itself. Check with a known-good
1233 * revision to avoid trashing the bisect run due to a
1234 * missing or non-executable script.
1236 if (is_first_run && (res == 126 || res == 127)) {
1237 int rc = verify_good(terms, command.buf);
1238 is_first_run = 0;
1239 if (rc < 0 || 128 <= rc) {
1240 error(_("unable to verify %s on good"
1241 " revision"), command.buf);
1242 res = BISECT_FAILED;
1243 break;
1245 if (rc == res) {
1246 error(_("bogus exit code %d for good revision"),
1247 rc);
1248 res = BISECT_FAILED;
1249 break;
1253 if (res < 0 || 128 <= res) {
1254 error(_("bisect run failed: exit code %d from"
1255 " %s is < 0 or >= 128"), res, command.buf);
1256 break;
1259 if (res == 125)
1260 new_state = "skip";
1261 else if (!res)
1262 new_state = terms->term_good;
1263 else
1264 new_state = terms->term_bad;
1266 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1268 if (temporary_stdout_fd < 0) {
1269 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1270 break;
1273 fflush(stdout);
1274 saved_stdout = dup(1);
1275 dup2(temporary_stdout_fd, 1);
1277 res = bisect_state(terms, 1, &new_state);
1279 fflush(stdout);
1280 dup2(saved_stdout, 1);
1281 close(saved_stdout);
1282 close(temporary_stdout_fd);
1284 print_file_to_stdout(git_path_bisect_run());
1286 if (res == BISECT_ONLY_SKIPPED_LEFT)
1287 error(_("bisect run cannot continue any more"));
1288 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1289 puts(_("bisect run success"));
1290 res = BISECT_OK;
1291 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1292 puts(_("bisect found first bad commit"));
1293 res = BISECT_OK;
1294 } else if (res) {
1295 error(_("bisect run failed: 'git bisect %s'"
1296 " exited with error code %d"), new_state, res);
1297 } else {
1298 continue;
1300 break;
1303 strbuf_release(&command);
1304 return res;
1307 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1309 if (argc > 1)
1310 return error(_("'%s' requires either no argument or a commit"),
1311 "git bisect reset");
1312 return bisect_reset(argc ? argv[0] : NULL);
1315 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1317 int res;
1318 struct bisect_terms terms = { 0 };
1320 if (argc > 1)
1321 return error(_("'%s' requires 0 or 1 argument"),
1322 "git bisect terms");
1323 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1324 free_terms(&terms);
1325 return res;
1328 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1330 int res;
1331 struct bisect_terms terms = { 0 };
1333 set_terms(&terms, "bad", "good");
1334 res = bisect_start(&terms, argc, argv);
1335 free_terms(&terms);
1336 return res;
1339 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1341 int res;
1342 struct bisect_terms terms = { 0 };
1344 if (argc)
1345 return error(_("'%s' requires 0 arguments"),
1346 "git bisect next");
1347 get_terms(&terms);
1348 res = bisect_next(&terms, prefix);
1349 free_terms(&terms);
1350 return res;
1353 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1355 return bisect_log();
1358 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1360 int res;
1361 struct bisect_terms terms = { 0 };
1363 if (argc != 1)
1364 return error(_("no logfile given"));
1365 set_terms(&terms, "bad", "good");
1366 res = bisect_replay(&terms, argv[0]);
1367 free_terms(&terms);
1368 return res;
1371 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1373 int res;
1374 struct bisect_terms terms = { 0 };
1376 set_terms(&terms, "bad", "good");
1377 get_terms(&terms);
1378 res = bisect_skip(&terms, argc, argv);
1379 free_terms(&terms);
1380 return res;
1383 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1385 int res;
1386 struct bisect_terms terms = { 0 };
1388 get_terms(&terms);
1389 res = bisect_visualize(&terms, argc, argv);
1390 free_terms(&terms);
1391 return res;
1394 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1396 int res;
1397 struct bisect_terms terms = { 0 };
1399 if (!argc)
1400 return error(_("'%s' failed: no command provided."), "git bisect run");
1401 get_terms(&terms);
1402 res = bisect_run(&terms, argc, argv);
1403 free_terms(&terms);
1404 return res;
1407 int cmd_bisect(int argc, const char **argv, const char *prefix)
1409 int res = 0;
1410 parse_opt_subcommand_fn *fn = NULL;
1411 struct option options[] = {
1412 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1413 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1414 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1415 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1416 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1417 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1418 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1419 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1420 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1421 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1422 OPT_END()
1424 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1425 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1427 if (!fn) {
1428 struct bisect_terms terms = { 0 };
1430 if (!argc)
1431 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1433 set_terms(&terms, "bad", "good");
1434 get_terms(&terms);
1435 if (check_and_set_terms(&terms, argv[0]))
1436 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1437 options, argv[0]);
1438 res = bisect_state(&terms, argc, argv);
1439 free_terms(&terms);
1440 } else {
1441 argc--;
1442 argv++;
1443 res = fn(argc, argv, prefix);
1446 return is_bisect_success(res) ? 0 : -res;