]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/bisect.c
31cc57e45ba9b97107cf90eab2fc749f4d502694
[thirdparty/git.git] / builtin / bisect.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "gettext.h"
4 #include "hex.h"
5 #include "parse-options.h"
6 #include "bisect.h"
7 #include "refs.h"
8 #include "dir.h"
9 #include "strvec.h"
10 #include "run-command.h"
11 #include "prompt.h"
12 #include "quote.h"
13 #include "revision.h"
14 #include "wrapper.h"
15
16 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
17 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
18 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
19 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
20 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
21 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
22 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
23 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
24
25 #define BUILTIN_GIT_BISECT_START_USAGE \
26 N_("git bisect start [--term-{new,bad}=<term> --term-{old,good}=<term>]" \
27 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
28 " [<pathspec>...]")
29 #define BUILTIN_GIT_BISECT_STATE_USAGE \
30 N_("git bisect (good|bad) [<rev>...]")
31 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
32 "git bisect terms [--term-good | --term-bad]"
33 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
34 N_("git bisect skip [(<rev>|<range>)...]")
35 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
36 "git bisect next"
37 #define BUILTIN_GIT_BISECT_RESET_USAGE \
38 N_("git bisect reset [<commit>]")
39 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
40 "git bisect visualize"
41 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
42 N_("git bisect replay <logfile>")
43 #define BUILTIN_GIT_BISECT_LOG_USAGE \
44 "git bisect log"
45 #define BUILTIN_GIT_BISECT_RUN_USAGE \
46 N_("git bisect run <cmd>...")
47
48 static const char * const git_bisect_usage[] = {
49 BUILTIN_GIT_BISECT_START_USAGE,
50 BUILTIN_GIT_BISECT_STATE_USAGE,
51 BUILTIN_GIT_BISECT_TERMS_USAGE,
52 BUILTIN_GIT_BISECT_SKIP_USAGE,
53 BUILTIN_GIT_BISECT_NEXT_USAGE,
54 BUILTIN_GIT_BISECT_RESET_USAGE,
55 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
56 BUILTIN_GIT_BISECT_REPLAY_USAGE,
57 BUILTIN_GIT_BISECT_LOG_USAGE,
58 BUILTIN_GIT_BISECT_RUN_USAGE,
59 NULL
60 };
61
62 struct add_bisect_ref_data {
63 struct rev_info *revs;
64 unsigned int object_flags;
65 };
66
67 struct bisect_terms {
68 char *term_good;
69 char *term_bad;
70 };
71
72 static void free_terms(struct bisect_terms *terms)
73 {
74 FREE_AND_NULL(terms->term_good);
75 FREE_AND_NULL(terms->term_bad);
76 }
77
78 static void set_terms(struct bisect_terms *terms, const char *bad,
79 const char *good)
80 {
81 free((void *)terms->term_good);
82 terms->term_good = xstrdup(good);
83 free((void *)terms->term_bad);
84 terms->term_bad = xstrdup(bad);
85 }
86
87 static const char vocab_bad[] = "bad|new";
88 static const char vocab_good[] = "good|old";
89
90 static int bisect_autostart(struct bisect_terms *terms);
91
92 /*
93 * Check whether the string `term` belongs to the set of strings
94 * included in the variable arguments.
95 */
96 LAST_ARG_MUST_BE_NULL
97 static int one_of(const char *term, ...)
98 {
99 int res = 0;
100 va_list matches;
101 const char *match;
102
103 va_start(matches, term);
104 while (!res && (match = va_arg(matches, const char *)))
105 res = !strcmp(term, match);
106 va_end(matches);
107
108 return res;
109 }
110
111 /*
112 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
113 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
114 * that indicate special success.
115 */
116
117 static int is_bisect_success(enum bisect_error res)
118 {
119 return !res ||
120 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
121 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
122 }
123
124 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
125 {
126 FILE *fp = NULL;
127 int res = 0;
128
129 if (strcmp(mode, "w") && strcmp(mode, "a"))
130 BUG("write-in-file does not support '%s' mode", mode);
131 fp = fopen(path, mode);
132 if (!fp)
133 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
134 res = vfprintf(fp, format, args);
135
136 if (res < 0) {
137 int saved_errno = errno;
138 fclose(fp);
139 errno = saved_errno;
140 return error_errno(_("could not write to file '%s'"), path);
141 }
142
143 return fclose(fp);
144 }
145
146 __attribute__((format (printf, 2, 3)))
147 static int write_to_file(const char *path, const char *format, ...)
148 {
149 int res;
150 va_list args;
151
152 va_start(args, format);
153 res = write_in_file(path, "w", format, args);
154 va_end(args);
155
156 return res;
157 }
158
159 __attribute__((format (printf, 2, 3)))
160 static int append_to_file(const char *path, const char *format, ...)
161 {
162 int res;
163 va_list args;
164
165 va_start(args, format);
166 res = write_in_file(path, "a", format, args);
167 va_end(args);
168
169 return res;
170 }
171
172 static int print_file_to_stdout(const char *path)
173 {
174 int fd = open(path, O_RDONLY);
175 int ret = 0;
176
177 if (fd < 0)
178 return error_errno(_("cannot open file '%s' for reading"), path);
179 if (copy_fd(fd, 1) < 0)
180 ret = error_errno(_("failed to read '%s'"), path);
181 close(fd);
182 return ret;
183 }
184
185 static int check_term_format(const char *term, const char *orig_term)
186 {
187 int res;
188 char *new_term = xstrfmt("refs/bisect/%s", term);
189
190 res = check_refname_format(new_term, 0);
191 free(new_term);
192
193 if (res)
194 return error(_("'%s' is not a valid term"), term);
195
196 if (one_of(term, "help", "start", "skip", "next", "reset",
197 "visualize", "view", "replay", "log", "run", "terms", NULL))
198 return error(_("can't use the builtin command '%s' as a term"), term);
199
200 /*
201 * In theory, nothing prevents swapping completely good and bad,
202 * but this situation could be confusing and hasn't been tested
203 * enough. Forbid it for now.
204 */
205
206 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
207 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
208 return error(_("can't change the meaning of the term '%s'"), term);
209
210 return 0;
211 }
212
213 static int write_terms(const char *bad, const char *good)
214 {
215 int res;
216
217 if (!strcmp(bad, good))
218 return error(_("please use two different terms"));
219
220 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
221 return -1;
222
223 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
224
225 return res;
226 }
227
228 static int bisect_reset(const char *commit)
229 {
230 struct strbuf branch = STRBUF_INIT;
231
232 if (!commit) {
233 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
234 printf(_("We are not bisecting.\n"));
235 return 0;
236 }
237 strbuf_rtrim(&branch);
238 } else {
239 struct object_id oid;
240
241 if (get_oid_commit(commit, &oid))
242 return error(_("'%s' is not a valid commit"), commit);
243 strbuf_addstr(&branch, commit);
244 }
245
246 if (!ref_exists("BISECT_HEAD")) {
247 struct child_process cmd = CHILD_PROCESS_INIT;
248
249 cmd.git_cmd = 1;
250 strvec_pushl(&cmd.args, "checkout", "--ignore-other-worktrees",
251 branch.buf, "--", NULL);
252 if (run_command(&cmd)) {
253 error(_("could not check out original"
254 " HEAD '%s'. Try 'git bisect"
255 " reset <commit>'."), branch.buf);
256 strbuf_release(&branch);
257 return -1;
258 }
259 }
260
261 strbuf_release(&branch);
262 return bisect_clean_state();
263 }
264
265 static void log_commit(FILE *fp, char *fmt, const char *state,
266 struct commit *commit)
267 {
268 struct pretty_print_context pp = {0};
269 struct strbuf commit_msg = STRBUF_INIT;
270 char *label = xstrfmt(fmt, state);
271
272 format_commit_message(commit, "%s", &commit_msg, &pp);
273
274 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
275 commit_msg.buf);
276
277 strbuf_release(&commit_msg);
278 free(label);
279 }
280
281 static int bisect_write(const char *state, const char *rev,
282 const struct bisect_terms *terms, int nolog)
283 {
284 struct strbuf tag = STRBUF_INIT;
285 struct object_id oid;
286 struct commit *commit;
287 FILE *fp = NULL;
288 int res = 0;
289
290 if (!strcmp(state, terms->term_bad)) {
291 strbuf_addf(&tag, "refs/bisect/%s", state);
292 } else if (one_of(state, terms->term_good, "skip", NULL)) {
293 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
294 } else {
295 res = error(_("Bad bisect_write argument: %s"), state);
296 goto finish;
297 }
298
299 if (get_oid(rev, &oid)) {
300 res = error(_("couldn't get the oid of the rev '%s'"), rev);
301 goto finish;
302 }
303
304 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
305 UPDATE_REFS_MSG_ON_ERR)) {
306 res = -1;
307 goto finish;
308 }
309
310 fp = fopen(git_path_bisect_log(), "a");
311 if (!fp) {
312 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
313 goto finish;
314 }
315
316 commit = lookup_commit_reference(the_repository, &oid);
317 log_commit(fp, "%s", state, commit);
318
319 if (!nolog)
320 fprintf(fp, "git bisect %s %s\n", state, rev);
321
322 finish:
323 if (fp)
324 fclose(fp);
325 strbuf_release(&tag);
326 return res;
327 }
328
329 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
330 {
331 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
332
333 if (one_of(cmd, "skip", "start", "terms", NULL))
334 return 0;
335
336 if (has_term_file && strcmp(cmd, terms->term_bad) &&
337 strcmp(cmd, terms->term_good))
338 return error(_("Invalid command: you're currently in a "
339 "%s/%s bisect"), terms->term_bad,
340 terms->term_good);
341
342 if (!has_term_file) {
343 if (one_of(cmd, "bad", "good", NULL)) {
344 set_terms(terms, "bad", "good");
345 return write_terms(terms->term_bad, terms->term_good);
346 }
347 if (one_of(cmd, "new", "old", NULL)) {
348 set_terms(terms, "new", "old");
349 return write_terms(terms->term_bad, terms->term_good);
350 }
351 }
352
353 return 0;
354 }
355
356 static int inc_nr(const char *refname UNUSED,
357 const struct object_id *oid UNUSED,
358 int flag UNUSED, void *cb_data)
359 {
360 unsigned int *nr = (unsigned int *)cb_data;
361 (*nr)++;
362 return 0;
363 }
364
365 static const char need_bad_and_good_revision_warning[] =
366 N_("You need to give me at least one %s and %s revision.\n"
367 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
368
369 static const char need_bisect_start_warning[] =
370 N_("You need to start by \"git bisect start\".\n"
371 "You then need to give me at least one %s and %s revision.\n"
372 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
373
374 static int decide_next(const struct bisect_terms *terms,
375 const char *current_term, int missing_good,
376 int missing_bad)
377 {
378 if (!missing_good && !missing_bad)
379 return 0;
380 if (!current_term)
381 return -1;
382
383 if (missing_good && !missing_bad &&
384 !strcmp(current_term, terms->term_good)) {
385 char *yesno;
386 /*
387 * have bad (or new) but not good (or old). We could bisect
388 * although this is less optimum.
389 */
390 warning(_("bisecting only with a %s commit"), terms->term_bad);
391 if (!isatty(0))
392 return 0;
393 /*
394 * TRANSLATORS: Make sure to include [Y] and [n] in your
395 * translation. The program will only accept English input
396 * at this point.
397 */
398 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
399 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
400 return -1;
401 return 0;
402 }
403
404 if (!is_empty_or_missing_file(git_path_bisect_start()))
405 return error(_(need_bad_and_good_revision_warning),
406 vocab_bad, vocab_good, vocab_bad, vocab_good);
407 else
408 return error(_(need_bisect_start_warning),
409 vocab_good, vocab_bad, vocab_good, vocab_bad);
410 }
411
412 static void bisect_status(struct bisect_state *state,
413 const struct bisect_terms *terms)
414 {
415 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
416 char *good_glob = xstrfmt("%s-*", terms->term_good);
417
418 if (ref_exists(bad_ref))
419 state->nr_bad = 1;
420
421 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
422 (void *) &state->nr_good);
423
424 free(good_glob);
425 free(bad_ref);
426 }
427
428 __attribute__((format (printf, 1, 2)))
429 static void bisect_log_printf(const char *fmt, ...)
430 {
431 struct strbuf buf = STRBUF_INIT;
432 va_list ap;
433
434 va_start(ap, fmt);
435 strbuf_vaddf(&buf, fmt, ap);
436 va_end(ap);
437
438 printf("%s", buf.buf);
439 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
440
441 strbuf_release(&buf);
442 }
443
444 static void bisect_print_status(const struct bisect_terms *terms)
445 {
446 struct bisect_state state = { 0 };
447
448 bisect_status(&state, terms);
449
450 /* If we had both, we'd already be started, and shouldn't get here. */
451 if (state.nr_good && state.nr_bad)
452 return;
453
454 if (!state.nr_good && !state.nr_bad)
455 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
456 else if (state.nr_good)
457 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
458 "status: waiting for bad commit, %d good commits known\n",
459 state.nr_good), state.nr_good);
460 else
461 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
462 }
463
464 static int bisect_next_check(const struct bisect_terms *terms,
465 const char *current_term)
466 {
467 struct bisect_state state = { 0 };
468 bisect_status(&state, terms);
469 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
470 }
471
472 static int get_terms(struct bisect_terms *terms)
473 {
474 struct strbuf str = STRBUF_INIT;
475 FILE *fp = NULL;
476 int res = 0;
477
478 fp = fopen(git_path_bisect_terms(), "r");
479 if (!fp) {
480 res = -1;
481 goto finish;
482 }
483
484 free_terms(terms);
485 strbuf_getline_lf(&str, fp);
486 terms->term_bad = strbuf_detach(&str, NULL);
487 strbuf_getline_lf(&str, fp);
488 terms->term_good = strbuf_detach(&str, NULL);
489
490 finish:
491 if (fp)
492 fclose(fp);
493 strbuf_release(&str);
494 return res;
495 }
496
497 static int bisect_terms(struct bisect_terms *terms, const char *option)
498 {
499 if (get_terms(terms))
500 return error(_("no terms defined"));
501
502 if (!option) {
503 printf(_("Your current terms are %s for the old state\n"
504 "and %s for the new state.\n"),
505 terms->term_good, terms->term_bad);
506 return 0;
507 }
508 if (one_of(option, "--term-good", "--term-old", NULL))
509 printf("%s\n", terms->term_good);
510 else if (one_of(option, "--term-bad", "--term-new", NULL))
511 printf("%s\n", terms->term_bad);
512 else
513 return error(_("invalid argument %s for 'git bisect terms'.\n"
514 "Supported options are: "
515 "--term-good|--term-old and "
516 "--term-bad|--term-new."), option);
517
518 return 0;
519 }
520
521 static int bisect_append_log_quoted(const char **argv)
522 {
523 int res = 0;
524 FILE *fp = fopen(git_path_bisect_log(), "a");
525 struct strbuf orig_args = STRBUF_INIT;
526
527 if (!fp)
528 return -1;
529
530 if (fprintf(fp, "git bisect start") < 1) {
531 res = -1;
532 goto finish;
533 }
534
535 sq_quote_argv(&orig_args, argv);
536 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
537 res = -1;
538
539 finish:
540 fclose(fp);
541 strbuf_release(&orig_args);
542 return res;
543 }
544
545 static int add_bisect_ref(const char *refname, const struct object_id *oid,
546 int flags UNUSED, void *cb)
547 {
548 struct add_bisect_ref_data *data = cb;
549
550 add_pending_oid(data->revs, refname, oid, data->object_flags);
551
552 return 0;
553 }
554
555 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
556 {
557 int res = 0;
558 struct add_bisect_ref_data cb = { revs };
559 char *good = xstrfmt("%s-*", terms->term_good);
560
561 /*
562 * We cannot use terms->term_bad directly in
563 * for_each_glob_ref_in() and we have to append a '*' to it,
564 * otherwise for_each_glob_ref_in() will append '/' and '*'.
565 */
566 char *bad = xstrfmt("%s*", terms->term_bad);
567
568 /*
569 * It is important to reset the flags used by revision walks
570 * as the previous call to bisect_next_all() in turn
571 * sets up a revision walk.
572 */
573 reset_revision_walk();
574 init_revisions(revs, NULL);
575 setup_revisions(0, NULL, revs, NULL);
576 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
577 cb.object_flags = UNINTERESTING;
578 for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
579 if (prepare_revision_walk(revs))
580 res = error(_("revision walk setup failed\n"));
581
582 free(good);
583 free(bad);
584 return res;
585 }
586
587 static int bisect_skipped_commits(struct bisect_terms *terms)
588 {
589 int res;
590 FILE *fp = NULL;
591 struct rev_info revs;
592 struct commit *commit;
593 struct pretty_print_context pp = {0};
594 struct strbuf commit_name = STRBUF_INIT;
595
596 res = prepare_revs(terms, &revs);
597 if (res)
598 return res;
599
600 fp = fopen(git_path_bisect_log(), "a");
601 if (!fp)
602 return error_errno(_("could not open '%s' for appending"),
603 git_path_bisect_log());
604
605 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
606 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
607
608 while ((commit = get_revision(&revs)) != NULL) {
609 strbuf_reset(&commit_name);
610 format_commit_message(commit, "%s",
611 &commit_name, &pp);
612 fprintf(fp, "# possible first %s commit: [%s] %s\n",
613 terms->term_bad, oid_to_hex(&commit->object.oid),
614 commit_name.buf);
615 }
616
617 /*
618 * Reset the flags used by revision walks in case
619 * there is another revision walk after this one.
620 */
621 reset_revision_walk();
622
623 strbuf_release(&commit_name);
624 release_revisions(&revs);
625 fclose(fp);
626 return 0;
627 }
628
629 static int bisect_successful(struct bisect_terms *terms)
630 {
631 struct object_id oid;
632 struct commit *commit;
633 struct pretty_print_context pp = {0};
634 struct strbuf commit_name = STRBUF_INIT;
635 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
636 int res;
637
638 read_ref(bad_ref, &oid);
639 commit = lookup_commit_reference_by_name(bad_ref);
640 format_commit_message(commit, "%s", &commit_name, &pp);
641
642 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
643 terms->term_bad, oid_to_hex(&commit->object.oid),
644 commit_name.buf);
645
646 strbuf_release(&commit_name);
647 free(bad_ref);
648 return res;
649 }
650
651 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
652 {
653 enum bisect_error res;
654
655 if (bisect_autostart(terms))
656 return BISECT_FAILED;
657
658 if (bisect_next_check(terms, terms->term_good))
659 return BISECT_FAILED;
660
661 /* Perform all bisection computation */
662 res = bisect_next_all(the_repository, prefix);
663
664 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
665 res = bisect_successful(terms);
666 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
667 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
668 res = bisect_skipped_commits(terms);
669 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
670 }
671 return res;
672 }
673
674 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
675 {
676 if (bisect_next_check(terms, NULL)) {
677 bisect_print_status(terms);
678 return BISECT_OK;
679 }
680
681 return bisect_next(terms, prefix);
682 }
683
684 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
685 const char **argv)
686 {
687 int no_checkout = 0;
688 int first_parent_only = 0;
689 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
690 int flags, pathspec_pos;
691 enum bisect_error res = BISECT_OK;
692 struct string_list revs = STRING_LIST_INIT_DUP;
693 struct string_list states = STRING_LIST_INIT_DUP;
694 struct strbuf start_head = STRBUF_INIT;
695 struct strbuf bisect_names = STRBUF_INIT;
696 struct object_id head_oid;
697 struct object_id oid;
698 const char *head;
699
700 if (is_bare_repository())
701 no_checkout = 1;
702
703 /*
704 * Check for one bad and then some good revisions
705 */
706 for (i = 0; i < argc; i++) {
707 if (!strcmp(argv[i], "--")) {
708 has_double_dash = 1;
709 break;
710 }
711 }
712
713 for (i = 0; i < argc; i++) {
714 const char *arg = argv[i];
715 if (!strcmp(argv[i], "--")) {
716 break;
717 } else if (!strcmp(arg, "--no-checkout")) {
718 no_checkout = 1;
719 } else if (!strcmp(arg, "--first-parent")) {
720 first_parent_only = 1;
721 } else if (!strcmp(arg, "--term-good") ||
722 !strcmp(arg, "--term-old")) {
723 i++;
724 if (argc <= i)
725 return error(_("'' is not a valid term"));
726 must_write_terms = 1;
727 free((void *) terms->term_good);
728 terms->term_good = xstrdup(argv[i]);
729 } else if (skip_prefix(arg, "--term-good=", &arg) ||
730 skip_prefix(arg, "--term-old=", &arg)) {
731 must_write_terms = 1;
732 free((void *) terms->term_good);
733 terms->term_good = xstrdup(arg);
734 } else if (!strcmp(arg, "--term-bad") ||
735 !strcmp(arg, "--term-new")) {
736 i++;
737 if (argc <= i)
738 return error(_("'' is not a valid term"));
739 must_write_terms = 1;
740 free((void *) terms->term_bad);
741 terms->term_bad = xstrdup(argv[i]);
742 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
743 skip_prefix(arg, "--term-new=", &arg)) {
744 must_write_terms = 1;
745 free((void *) terms->term_bad);
746 terms->term_bad = xstrdup(arg);
747 } else if (starts_with(arg, "--")) {
748 return error(_("unrecognized option: '%s'"), arg);
749 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
750 string_list_append(&revs, oid_to_hex(&oid));
751 } else if (has_double_dash) {
752 die(_("'%s' does not appear to be a valid "
753 "revision"), arg);
754 } else {
755 break;
756 }
757 }
758 pathspec_pos = i;
759
760 /*
761 * The user ran "git bisect start <sha1> <sha1>", hence did not
762 * explicitly specify the terms, but we are already starting to
763 * set references named with the default terms, and won't be able
764 * to change afterwards.
765 */
766 if (revs.nr)
767 must_write_terms = 1;
768 for (i = 0; i < revs.nr; i++) {
769 if (bad_seen) {
770 string_list_append(&states, terms->term_good);
771 } else {
772 bad_seen = 1;
773 string_list_append(&states, terms->term_bad);
774 }
775 }
776
777 /*
778 * Verify HEAD
779 */
780 head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
781 if (!head)
782 if (get_oid("HEAD", &head_oid))
783 return error(_("bad HEAD - I need a HEAD"));
784
785 /*
786 * Check if we are bisecting
787 */
788 if (!is_empty_or_missing_file(git_path_bisect_start())) {
789 /* Reset to the rev from where we started */
790 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
791 strbuf_trim(&start_head);
792 if (!no_checkout) {
793 struct child_process cmd = CHILD_PROCESS_INIT;
794
795 cmd.git_cmd = 1;
796 strvec_pushl(&cmd.args, "checkout", start_head.buf,
797 "--", NULL);
798 if (run_command(&cmd)) {
799 res = error(_("checking out '%s' failed."
800 " Try 'git bisect start "
801 "<valid-branch>'."),
802 start_head.buf);
803 goto finish;
804 }
805 }
806 } else {
807 /* Get the rev from where we start. */
808 if (!get_oid(head, &head_oid) &&
809 !starts_with(head, "refs/heads/")) {
810 strbuf_reset(&start_head);
811 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
812 } else if (!get_oid(head, &head_oid) &&
813 skip_prefix(head, "refs/heads/", &head)) {
814 strbuf_addstr(&start_head, head);
815 } else {
816 return error(_("bad HEAD - strange symbolic ref"));
817 }
818 }
819
820 /*
821 * Get rid of any old bisect state.
822 */
823 if (bisect_clean_state())
824 return BISECT_FAILED;
825
826 /*
827 * Write new start state
828 */
829 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
830
831 if (first_parent_only)
832 write_file(git_path_bisect_first_parent(), "\n");
833
834 if (no_checkout) {
835 if (get_oid(start_head.buf, &oid) < 0) {
836 res = error(_("invalid ref: '%s'"), start_head.buf);
837 goto finish;
838 }
839 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
840 UPDATE_REFS_MSG_ON_ERR)) {
841 res = BISECT_FAILED;
842 goto finish;
843 }
844 }
845
846 if (pathspec_pos < argc - 1)
847 sq_quote_argv(&bisect_names, argv + pathspec_pos);
848 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
849
850 for (i = 0; i < states.nr; i++)
851 if (bisect_write(states.items[i].string,
852 revs.items[i].string, terms, 1)) {
853 res = BISECT_FAILED;
854 goto finish;
855 }
856
857 if (must_write_terms && write_terms(terms->term_bad,
858 terms->term_good)) {
859 res = BISECT_FAILED;
860 goto finish;
861 }
862
863 res = bisect_append_log_quoted(argv);
864 if (res)
865 res = BISECT_FAILED;
866
867 finish:
868 string_list_clear(&revs, 0);
869 string_list_clear(&states, 0);
870 strbuf_release(&start_head);
871 strbuf_release(&bisect_names);
872 if (res)
873 return res;
874
875 res = bisect_auto_next(terms, NULL);
876 if (!is_bisect_success(res))
877 bisect_clean_state();
878 return res;
879 }
880
881 static inline int file_is_not_empty(const char *path)
882 {
883 return !is_empty_or_missing_file(path);
884 }
885
886 static int bisect_autostart(struct bisect_terms *terms)
887 {
888 int res;
889 const char *yesno;
890
891 if (file_is_not_empty(git_path_bisect_start()))
892 return 0;
893
894 fprintf_ln(stderr, _("You need to start by \"git bisect "
895 "start\"\n"));
896
897 if (!isatty(STDIN_FILENO))
898 return -1;
899
900 /*
901 * TRANSLATORS: Make sure to include [Y] and [n] in your
902 * translation. The program will only accept English input
903 * at this point.
904 */
905 yesno = git_prompt(_("Do you want me to do it for you "
906 "[Y/n]? "), PROMPT_ECHO);
907 res = tolower(*yesno) == 'n' ?
908 -1 : bisect_start(terms, 0, empty_strvec);
909
910 return res;
911 }
912
913 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
914 const char **argv)
915 {
916 const char *state;
917 int i, verify_expected = 1;
918 struct object_id oid, expected;
919 struct strbuf buf = STRBUF_INIT;
920 struct oid_array revs = OID_ARRAY_INIT;
921
922 if (!argc)
923 return error(_("Please call `--bisect-state` with at least one argument"));
924
925 if (bisect_autostart(terms))
926 return BISECT_FAILED;
927
928 state = argv[0];
929 if (check_and_set_terms(terms, state) ||
930 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
931 return BISECT_FAILED;
932
933 argv++;
934 argc--;
935 if (argc > 1 && !strcmp(state, terms->term_bad))
936 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
937
938 if (argc == 0) {
939 const char *head = "BISECT_HEAD";
940 enum get_oid_result res_head = get_oid(head, &oid);
941
942 if (res_head == MISSING_OBJECT) {
943 head = "HEAD";
944 res_head = get_oid(head, &oid);
945 }
946
947 if (res_head)
948 error(_("Bad rev input: %s"), head);
949 oid_array_append(&revs, &oid);
950 }
951
952 /*
953 * All input revs must be checked before executing bisect_write()
954 * to discard junk revs.
955 */
956
957 for (; argc; argc--, argv++) {
958 struct commit *commit;
959
960 if (get_oid(*argv, &oid)){
961 error(_("Bad rev input: %s"), *argv);
962 oid_array_clear(&revs);
963 return BISECT_FAILED;
964 }
965
966 commit = lookup_commit_reference(the_repository, &oid);
967 if (!commit)
968 die(_("Bad rev input (not a commit): %s"), *argv);
969
970 oid_array_append(&revs, &commit->object.oid);
971 }
972
973 if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
974 get_oid_hex(buf.buf, &expected) < 0)
975 verify_expected = 0; /* Ignore invalid file contents */
976 strbuf_release(&buf);
977
978 for (i = 0; i < revs.nr; i++) {
979 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
980 oid_array_clear(&revs);
981 return BISECT_FAILED;
982 }
983 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
984 unlink_or_warn(git_path_bisect_ancestors_ok());
985 unlink_or_warn(git_path_bisect_expected_rev());
986 verify_expected = 0;
987 }
988 }
989
990 oid_array_clear(&revs);
991 return bisect_auto_next(terms, NULL);
992 }
993
994 static enum bisect_error bisect_log(void)
995 {
996 int fd, status;
997 const char* filename = git_path_bisect_log();
998
999 if (is_empty_or_missing_file(filename))
1000 return error(_("We are not bisecting."));
1001
1002 fd = open(filename, O_RDONLY);
1003 if (fd < 0)
1004 return BISECT_FAILED;
1005
1006 status = copy_fd(fd, STDOUT_FILENO);
1007 close(fd);
1008 return status ? BISECT_FAILED : BISECT_OK;
1009 }
1010
1011 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1012 {
1013 const char *p = line->buf + strspn(line->buf, " \t");
1014 char *word_end, *rev;
1015
1016 if ((!skip_prefix(p, "git bisect", &p) &&
1017 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1018 return 0;
1019 p += strspn(p, " \t");
1020
1021 word_end = (char *)p + strcspn(p, " \t");
1022 rev = word_end + strspn(word_end, " \t");
1023 *word_end = '\0'; /* NUL-terminate the word */
1024
1025 get_terms(terms);
1026 if (check_and_set_terms(terms, p))
1027 return -1;
1028
1029 if (!strcmp(p, "start")) {
1030 struct strvec argv = STRVEC_INIT;
1031 int res;
1032 sq_dequote_to_strvec(rev, &argv);
1033 res = bisect_start(terms, argv.nr, argv.v);
1034 strvec_clear(&argv);
1035 return res;
1036 }
1037
1038 if (one_of(p, terms->term_good,
1039 terms->term_bad, "skip", NULL))
1040 return bisect_write(p, rev, terms, 0);
1041
1042 if (!strcmp(p, "terms")) {
1043 struct strvec argv = STRVEC_INIT;
1044 int res;
1045 sq_dequote_to_strvec(rev, &argv);
1046 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1047 strvec_clear(&argv);
1048 return res;
1049 }
1050 error(_("'%s'?? what are you talking about?"), p);
1051
1052 return -1;
1053 }
1054
1055 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1056 {
1057 FILE *fp = NULL;
1058 enum bisect_error res = BISECT_OK;
1059 struct strbuf line = STRBUF_INIT;
1060
1061 if (is_empty_or_missing_file(filename))
1062 return error(_("cannot read file '%s' for replaying"), filename);
1063
1064 if (bisect_reset(NULL))
1065 return BISECT_FAILED;
1066
1067 fp = fopen(filename, "r");
1068 if (!fp)
1069 return BISECT_FAILED;
1070
1071 while ((strbuf_getline(&line, fp) != EOF) && !res)
1072 res = process_replay_line(terms, &line);
1073
1074 strbuf_release(&line);
1075 fclose(fp);
1076
1077 if (res)
1078 return BISECT_FAILED;
1079
1080 return bisect_auto_next(terms, NULL);
1081 }
1082
1083 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1084 const char **argv)
1085 {
1086 int i;
1087 enum bisect_error res;
1088 struct strvec argv_state = STRVEC_INIT;
1089
1090 strvec_push(&argv_state, "skip");
1091
1092 for (i = 0; i < argc; i++) {
1093 const char *dotdot = strstr(argv[i], "..");
1094
1095 if (dotdot) {
1096 struct rev_info revs;
1097 struct commit *commit;
1098
1099 init_revisions(&revs, NULL);
1100 setup_revisions(2, argv + i - 1, &revs, NULL);
1101
1102 if (prepare_revision_walk(&revs))
1103 die(_("revision walk setup failed\n"));
1104 while ((commit = get_revision(&revs)) != NULL)
1105 strvec_push(&argv_state,
1106 oid_to_hex(&commit->object.oid));
1107
1108 reset_revision_walk();
1109 release_revisions(&revs);
1110 } else {
1111 strvec_push(&argv_state, argv[i]);
1112 }
1113 }
1114 res = bisect_state(terms, argv_state.nr, argv_state.v);
1115
1116 strvec_clear(&argv_state);
1117 return res;
1118 }
1119
1120 static int bisect_visualize(struct bisect_terms *terms, int argc,
1121 const char **argv)
1122 {
1123 struct child_process cmd = CHILD_PROCESS_INIT;
1124 struct strbuf sb = STRBUF_INIT;
1125
1126 if (bisect_next_check(terms, NULL) != 0)
1127 return BISECT_FAILED;
1128
1129 cmd.no_stdin = 1;
1130 if (!argc) {
1131 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1132 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1133 strvec_push(&cmd.args, "gitk");
1134 } else {
1135 strvec_push(&cmd.args, "log");
1136 cmd.git_cmd = 1;
1137 }
1138 } else {
1139 if (argv[0][0] == '-') {
1140 strvec_push(&cmd.args, "log");
1141 cmd.git_cmd = 1;
1142 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1143 cmd.git_cmd = 1;
1144
1145 strvec_pushv(&cmd.args, argv);
1146 }
1147
1148 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1149
1150 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1151 sq_dequote_to_strvec(sb.buf, &cmd.args);
1152 strbuf_release(&sb);
1153
1154 return run_command(&cmd);
1155 }
1156
1157 static int get_first_good(const char *refname UNUSED,
1158 const struct object_id *oid,
1159 int flag UNUSED, void *cb_data)
1160 {
1161 oidcpy(cb_data, oid);
1162 return 1;
1163 }
1164
1165 static int do_bisect_run(const char *command)
1166 {
1167 struct child_process cmd = CHILD_PROCESS_INIT;
1168
1169 printf(_("running %s\n"), command);
1170 cmd.use_shell = 1;
1171 strvec_push(&cmd.args, command);
1172 return run_command(&cmd);
1173 }
1174
1175 static int verify_good(const struct bisect_terms *terms, const char *command)
1176 {
1177 int rc;
1178 enum bisect_error res;
1179 struct object_id good_rev;
1180 struct object_id current_rev;
1181 char *good_glob = xstrfmt("%s-*", terms->term_good);
1182 int no_checkout = ref_exists("BISECT_HEAD");
1183
1184 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1185 &good_rev);
1186 free(good_glob);
1187
1188 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1189 return -1;
1190
1191 res = bisect_checkout(&good_rev, no_checkout);
1192 if (res != BISECT_OK)
1193 return -1;
1194
1195 rc = do_bisect_run(command);
1196
1197 res = bisect_checkout(&current_rev, no_checkout);
1198 if (res != BISECT_OK)
1199 return -1;
1200
1201 return rc;
1202 }
1203
1204 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1205 {
1206 int res = BISECT_OK;
1207 struct strbuf command = STRBUF_INIT;
1208 const char *new_state;
1209 int temporary_stdout_fd, saved_stdout;
1210 int is_first_run = 1;
1211
1212 if (bisect_next_check(terms, NULL))
1213 return BISECT_FAILED;
1214
1215 if (!argc) {
1216 error(_("bisect run failed: no command provided."));
1217 return BISECT_FAILED;
1218 }
1219
1220 sq_quote_argv(&command, argv);
1221 strbuf_ltrim(&command);
1222 while (1) {
1223 res = do_bisect_run(command.buf);
1224
1225 /*
1226 * Exit code 126 and 127 can either come from the shell
1227 * if it was unable to execute or even find the script,
1228 * or from the script itself. Check with a known-good
1229 * revision to avoid trashing the bisect run due to a
1230 * missing or non-executable script.
1231 */
1232 if (is_first_run && (res == 126 || res == 127)) {
1233 int rc = verify_good(terms, command.buf);
1234 is_first_run = 0;
1235 if (rc < 0 || 128 <= rc) {
1236 error(_("unable to verify %s on good"
1237 " revision"), command.buf);
1238 res = BISECT_FAILED;
1239 break;
1240 }
1241 if (rc == res) {
1242 error(_("bogus exit code %d for good revision"),
1243 rc);
1244 res = BISECT_FAILED;
1245 break;
1246 }
1247 }
1248
1249 if (res < 0 || 128 <= res) {
1250 error(_("bisect run failed: exit code %d from"
1251 " %s is < 0 or >= 128"), res, command.buf);
1252 break;
1253 }
1254
1255 if (res == 125)
1256 new_state = "skip";
1257 else if (!res)
1258 new_state = terms->term_good;
1259 else
1260 new_state = terms->term_bad;
1261
1262 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1263
1264 if (temporary_stdout_fd < 0) {
1265 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1266 break;
1267 }
1268
1269 fflush(stdout);
1270 saved_stdout = dup(1);
1271 dup2(temporary_stdout_fd, 1);
1272
1273 res = bisect_state(terms, 1, &new_state);
1274
1275 fflush(stdout);
1276 dup2(saved_stdout, 1);
1277 close(saved_stdout);
1278 close(temporary_stdout_fd);
1279
1280 print_file_to_stdout(git_path_bisect_run());
1281
1282 if (res == BISECT_ONLY_SKIPPED_LEFT)
1283 error(_("bisect run cannot continue any more"));
1284 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1285 puts(_("bisect run success"));
1286 res = BISECT_OK;
1287 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1288 puts(_("bisect found first bad commit"));
1289 res = BISECT_OK;
1290 } else if (res) {
1291 error(_("bisect run failed: 'git bisect %s'"
1292 " exited with error code %d"), new_state, res);
1293 } else {
1294 continue;
1295 }
1296 break;
1297 }
1298
1299 strbuf_release(&command);
1300 return res;
1301 }
1302
1303 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1304 {
1305 if (argc > 1)
1306 return error(_("'%s' requires either no argument or a commit"),
1307 "git bisect reset");
1308 return bisect_reset(argc ? argv[0] : NULL);
1309 }
1310
1311 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1312 {
1313 int res;
1314 struct bisect_terms terms = { 0 };
1315
1316 if (argc > 1)
1317 return error(_("'%s' requires 0 or 1 argument"),
1318 "git bisect terms");
1319 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1320 free_terms(&terms);
1321 return res;
1322 }
1323
1324 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1325 {
1326 int res;
1327 struct bisect_terms terms = { 0 };
1328
1329 set_terms(&terms, "bad", "good");
1330 res = bisect_start(&terms, argc, argv);
1331 free_terms(&terms);
1332 return res;
1333 }
1334
1335 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1336 {
1337 int res;
1338 struct bisect_terms terms = { 0 };
1339
1340 if (argc)
1341 return error(_("'%s' requires 0 arguments"),
1342 "git bisect next");
1343 get_terms(&terms);
1344 res = bisect_next(&terms, prefix);
1345 free_terms(&terms);
1346 return res;
1347 }
1348
1349 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1350 {
1351 return bisect_log();
1352 }
1353
1354 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1355 {
1356 int res;
1357 struct bisect_terms terms = { 0 };
1358
1359 if (argc != 1)
1360 return error(_("no logfile given"));
1361 set_terms(&terms, "bad", "good");
1362 res = bisect_replay(&terms, argv[0]);
1363 free_terms(&terms);
1364 return res;
1365 }
1366
1367 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1368 {
1369 int res;
1370 struct bisect_terms terms = { 0 };
1371
1372 set_terms(&terms, "bad", "good");
1373 get_terms(&terms);
1374 res = bisect_skip(&terms, argc, argv);
1375 free_terms(&terms);
1376 return res;
1377 }
1378
1379 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1380 {
1381 int res;
1382 struct bisect_terms terms = { 0 };
1383
1384 get_terms(&terms);
1385 res = bisect_visualize(&terms, argc, argv);
1386 free_terms(&terms);
1387 return res;
1388 }
1389
1390 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1391 {
1392 int res;
1393 struct bisect_terms terms = { 0 };
1394
1395 if (!argc)
1396 return error(_("'%s' failed: no command provided."), "git bisect run");
1397 get_terms(&terms);
1398 res = bisect_run(&terms, argc, argv);
1399 free_terms(&terms);
1400 return res;
1401 }
1402
1403 int cmd_bisect(int argc, const char **argv, const char *prefix)
1404 {
1405 int res = 0;
1406 parse_opt_subcommand_fn *fn = NULL;
1407 struct option options[] = {
1408 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1409 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1410 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1411 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1412 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1413 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1414 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1415 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1416 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1417 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1418 OPT_END()
1419 };
1420 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1421 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1422
1423 if (!fn) {
1424 struct bisect_terms terms = { 0 };
1425
1426 if (!argc)
1427 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1428
1429 set_terms(&terms, "bad", "good");
1430 get_terms(&terms);
1431 if (check_and_set_terms(&terms, argv[0]))
1432 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1433 options, argv[0]);
1434 res = bisect_state(&terms, argc, argv);
1435 free_terms(&terms);
1436 } else {
1437 argc--;
1438 argv++;
1439 res = fn(argc, argv, prefix);
1440 }
1441
1442 return is_bisect_success(res) ? 0 : -res;
1443 }