t7800: use single quotes for test bodies
[alt-git.git] / builtin / rebase.c
blob4084a6abb8bf2d7eb87b64f3af792d8a7892292d
1 /*
2 * "git rebase" builtin command
4 * Copyright (c) 2018 Pratik Karki
5 */
7 #define USE_THE_INDEX_VARIABLE
8 #include "builtin.h"
9 #include "abspath.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "hex.h"
13 #include "run-command.h"
14 #include "strvec.h"
15 #include "dir.h"
16 #include "refs.h"
17 #include "config.h"
18 #include "unpack-trees.h"
19 #include "lockfile.h"
20 #include "object-file.h"
21 #include "object-name.h"
22 #include "parse-options.h"
23 #include "path.h"
24 #include "commit.h"
25 #include "diff.h"
26 #include "wt-status.h"
27 #include "revision.h"
28 #include "commit-reach.h"
29 #include "rerere.h"
30 #include "branch.h"
31 #include "sequencer.h"
32 #include "rebase-interactive.h"
33 #include "reset.h"
34 #include "trace2.h"
35 #include "hook.h"
37 static char const * const builtin_rebase_usage[] = {
38 N_("git rebase [-i] [options] [--exec <cmd>] "
39 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
40 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
41 "--root [<branch>]"),
42 "git rebase --continue | --abort | --skip | --edit-todo",
43 NULL
46 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
47 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
48 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
49 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
51 enum rebase_type {
52 REBASE_UNSPECIFIED = -1,
53 REBASE_APPLY,
54 REBASE_MERGE
57 enum empty_type {
58 EMPTY_UNSPECIFIED = -1,
59 EMPTY_DROP,
60 EMPTY_KEEP,
61 EMPTY_ASK
64 enum action {
65 ACTION_NONE = 0,
66 ACTION_CONTINUE,
67 ACTION_SKIP,
68 ACTION_ABORT,
69 ACTION_QUIT,
70 ACTION_EDIT_TODO,
71 ACTION_SHOW_CURRENT_PATCH
74 static const char *action_names[] = {
75 "undefined",
76 "continue",
77 "skip",
78 "abort",
79 "quit",
80 "edit_todo",
81 "show_current_patch"
84 struct rebase_options {
85 enum rebase_type type;
86 enum empty_type empty;
87 const char *default_backend;
88 const char *state_dir;
89 struct commit *upstream;
90 const char *upstream_name;
91 const char *upstream_arg;
92 char *head_name;
93 struct commit *orig_head;
94 struct commit *onto;
95 const char *onto_name;
96 const char *revisions;
97 const char *switch_to;
98 int root, root_with_onto;
99 struct object_id *squash_onto;
100 struct commit *restrict_revision;
101 int dont_finish_rebase;
102 enum {
103 REBASE_NO_QUIET = 1<<0,
104 REBASE_VERBOSE = 1<<1,
105 REBASE_DIFFSTAT = 1<<2,
106 REBASE_FORCE = 1<<3,
107 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
108 } flags;
109 struct strvec git_am_opts;
110 enum action action;
111 char *reflog_action;
112 int signoff;
113 int allow_rerere_autoupdate;
114 int keep_empty;
115 int autosquash;
116 char *gpg_sign_opt;
117 int autostash;
118 int committer_date_is_author_date;
119 int ignore_date;
120 struct string_list exec;
121 int allow_empty_message;
122 int rebase_merges, rebase_cousins;
123 char *strategy;
124 struct string_list strategy_opts;
125 struct strbuf git_format_patch_opt;
126 int reschedule_failed_exec;
127 int reapply_cherry_picks;
128 int fork_point;
129 int update_refs;
130 int config_autosquash;
131 int config_rebase_merges;
132 int config_update_refs;
135 #define REBASE_OPTIONS_INIT { \
136 .type = REBASE_UNSPECIFIED, \
137 .empty = EMPTY_UNSPECIFIED, \
138 .keep_empty = 1, \
139 .default_backend = "merge", \
140 .flags = REBASE_NO_QUIET, \
141 .git_am_opts = STRVEC_INIT, \
142 .exec = STRING_LIST_INIT_NODUP, \
143 .git_format_patch_opt = STRBUF_INIT, \
144 .fork_point = -1, \
145 .reapply_cherry_picks = -1, \
146 .allow_empty_message = 1, \
147 .autosquash = -1, \
148 .config_autosquash = -1, \
149 .rebase_merges = -1, \
150 .config_rebase_merges = -1, \
151 .update_refs = -1, \
152 .config_update_refs = -1, \
153 .strategy_opts = STRING_LIST_INIT_NODUP,\
156 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
158 struct replay_opts replay = REPLAY_OPTS_INIT;
160 replay.action = REPLAY_INTERACTIVE_REBASE;
161 replay.strategy = NULL;
162 sequencer_init_config(&replay);
164 replay.signoff = opts->signoff;
165 replay.allow_ff = !(opts->flags & REBASE_FORCE);
166 if (opts->allow_rerere_autoupdate)
167 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
168 replay.allow_empty = 1;
169 replay.allow_empty_message = opts->allow_empty_message;
170 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
171 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
172 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
173 replay.verbose = opts->flags & REBASE_VERBOSE;
174 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
175 replay.committer_date_is_author_date =
176 opts->committer_date_is_author_date;
177 replay.ignore_date = opts->ignore_date;
178 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
179 replay.reflog_action = xstrdup(opts->reflog_action);
180 if (opts->strategy)
181 replay.strategy = xstrdup_or_null(opts->strategy);
182 else if (!replay.strategy && replay.default_strategy) {
183 replay.strategy = replay.default_strategy;
184 replay.default_strategy = NULL;
187 for (size_t i = 0; i < opts->strategy_opts.nr; i++)
188 strvec_push(&replay.xopts, opts->strategy_opts.items[i].string);
190 if (opts->squash_onto) {
191 oidcpy(&replay.squash_onto, opts->squash_onto);
192 replay.have_squash_onto = 1;
195 return replay;
198 static int edit_todo_file(unsigned flags)
200 const char *todo_file = rebase_path_todo();
201 struct todo_list todo_list = TODO_LIST_INIT,
202 new_todo = TODO_LIST_INIT;
203 int res = 0;
205 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
206 return error_errno(_("could not read '%s'."), todo_file);
208 strbuf_stripspace(&todo_list.buf, comment_line_char);
209 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
210 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
211 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
212 res = error_errno(_("could not write '%s'"), todo_file);
214 todo_list_release(&todo_list);
215 todo_list_release(&new_todo);
217 return res;
220 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
221 struct object_id *orig_head, char **revisions,
222 char **shortrevisions)
224 struct commit *base_rev = upstream ? upstream : onto;
225 const char *shorthead;
227 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
228 oid_to_hex(orig_head));
230 shorthead = repo_find_unique_abbrev(the_repository, orig_head,
231 DEFAULT_ABBREV);
233 if (upstream) {
234 const char *shortrev;
236 shortrev = repo_find_unique_abbrev(the_repository,
237 &base_rev->object.oid,
238 DEFAULT_ABBREV);
240 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
241 } else
242 *shortrevisions = xstrdup(shorthead);
244 return 0;
247 static int init_basic_state(struct replay_opts *opts, const char *head_name,
248 struct commit *onto,
249 const struct object_id *orig_head)
251 FILE *interactive;
253 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
254 return error_errno(_("could not create temporary %s"), merge_dir());
256 delete_reflog("REBASE_HEAD");
258 interactive = fopen(path_interactive(), "w");
259 if (!interactive)
260 return error_errno(_("could not mark as interactive"));
261 fclose(interactive);
263 return write_basic_state(opts, head_name, onto, orig_head);
266 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
268 int ret = -1;
269 char *revisions = NULL, *shortrevisions = NULL;
270 struct strvec make_script_args = STRVEC_INIT;
271 struct todo_list todo_list = TODO_LIST_INIT;
272 struct replay_opts replay = get_replay_opts(opts);
274 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
275 &revisions, &shortrevisions))
276 goto cleanup;
278 if (init_basic_state(&replay,
279 opts->head_name ? opts->head_name : "detached HEAD",
280 opts->onto, &opts->orig_head->object.oid))
281 goto cleanup;
283 if (!opts->upstream && opts->squash_onto)
284 write_file(path_squash_onto(), "%s\n",
285 oid_to_hex(opts->squash_onto));
287 strvec_pushl(&make_script_args, "", revisions, NULL);
288 if (opts->restrict_revision)
289 strvec_pushf(&make_script_args, "^%s",
290 oid_to_hex(&opts->restrict_revision->object.oid));
292 ret = sequencer_make_script(the_repository, &todo_list.buf,
293 make_script_args.nr, make_script_args.v,
294 flags);
296 if (ret)
297 error(_("could not generate todo list"));
298 else {
299 discard_index(&the_index);
300 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
301 &todo_list))
302 BUG("unusable todo list");
304 ret = complete_action(the_repository, &replay, flags,
305 shortrevisions, opts->onto_name, opts->onto,
306 &opts->orig_head->object.oid, &opts->exec,
307 opts->autosquash, opts->update_refs, &todo_list);
310 cleanup:
311 replay_opts_release(&replay);
312 free(revisions);
313 free(shortrevisions);
314 todo_list_release(&todo_list);
315 strvec_clear(&make_script_args);
317 return ret;
320 static int run_sequencer_rebase(struct rebase_options *opts)
322 unsigned flags = 0;
323 int abbreviate_commands = 0, ret = 0;
325 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
327 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
328 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
329 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
330 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
331 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
332 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
333 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
335 switch (opts->action) {
336 case ACTION_NONE: {
337 if (!opts->onto && !opts->upstream)
338 die(_("a base commit must be provided with --upstream or --onto"));
340 ret = do_interactive_rebase(opts, flags);
341 break;
343 case ACTION_SKIP: {
344 struct string_list merge_rr = STRING_LIST_INIT_DUP;
346 rerere_clear(the_repository, &merge_rr);
348 /* fallthrough */
349 case ACTION_CONTINUE: {
350 struct replay_opts replay_opts = get_replay_opts(opts);
352 ret = sequencer_continue(the_repository, &replay_opts);
353 replay_opts_release(&replay_opts);
354 break;
356 case ACTION_EDIT_TODO:
357 ret = edit_todo_file(flags);
358 break;
359 case ACTION_SHOW_CURRENT_PATCH: {
360 struct child_process cmd = CHILD_PROCESS_INIT;
362 cmd.git_cmd = 1;
363 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
364 ret = run_command(&cmd);
366 break;
368 default:
369 BUG("invalid command '%d'", opts->action);
372 return ret;
375 static int is_merge(struct rebase_options *opts)
377 return opts->type == REBASE_MERGE;
380 static void imply_merge(struct rebase_options *opts, const char *option)
382 switch (opts->type) {
383 case REBASE_APPLY:
384 die(_("%s requires the merge backend"), option);
385 break;
386 case REBASE_MERGE:
387 break;
388 default:
389 opts->type = REBASE_MERGE; /* implied */
390 break;
394 /* Returns the filename prefixed by the state_dir */
395 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
397 static struct strbuf path = STRBUF_INIT;
398 static size_t prefix_len;
400 if (!prefix_len) {
401 strbuf_addf(&path, "%s/", opts->state_dir);
402 prefix_len = path.len;
405 strbuf_setlen(&path, prefix_len);
406 strbuf_addstr(&path, filename);
407 return path.buf;
410 /* Initialize the rebase options from the state directory. */
411 static int read_basic_state(struct rebase_options *opts)
413 struct strbuf head_name = STRBUF_INIT;
414 struct strbuf buf = STRBUF_INIT;
415 struct object_id oid;
417 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
418 READ_ONELINER_WARN_MISSING) ||
419 !read_oneliner(&buf, state_dir_path("onto", opts),
420 READ_ONELINER_WARN_MISSING))
421 return -1;
422 opts->head_name = starts_with(head_name.buf, "refs/") ?
423 xstrdup(head_name.buf) : NULL;
424 strbuf_release(&head_name);
425 if (get_oid_hex(buf.buf, &oid) ||
426 !(opts->onto = lookup_commit_object(the_repository, &oid)))
427 return error(_("invalid onto: '%s'"), buf.buf);
430 * We always write to orig-head, but interactive rebase used to write to
431 * head. Fall back to reading from head to cover for the case that the
432 * user upgraded git with an ongoing interactive rebase.
434 strbuf_reset(&buf);
435 if (file_exists(state_dir_path("orig-head", opts))) {
436 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
437 READ_ONELINER_WARN_MISSING))
438 return -1;
439 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
440 READ_ONELINER_WARN_MISSING))
441 return -1;
442 if (get_oid_hex(buf.buf, &oid) ||
443 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
444 return error(_("invalid orig-head: '%s'"), buf.buf);
446 if (file_exists(state_dir_path("quiet", opts)))
447 opts->flags &= ~REBASE_NO_QUIET;
448 else
449 opts->flags |= REBASE_NO_QUIET;
451 if (file_exists(state_dir_path("verbose", opts)))
452 opts->flags |= REBASE_VERBOSE;
454 if (file_exists(state_dir_path("signoff", opts))) {
455 opts->signoff = 1;
456 opts->flags |= REBASE_FORCE;
459 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
460 strbuf_reset(&buf);
461 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
462 READ_ONELINER_WARN_MISSING))
463 return -1;
464 if (!strcmp(buf.buf, "--rerere-autoupdate"))
465 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
466 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
467 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
468 else
469 warning(_("ignoring invalid allow_rerere_autoupdate: "
470 "'%s'"), buf.buf);
473 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
474 strbuf_reset(&buf);
475 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
476 READ_ONELINER_WARN_MISSING))
477 return -1;
478 free(opts->gpg_sign_opt);
479 opts->gpg_sign_opt = xstrdup(buf.buf);
482 strbuf_release(&buf);
484 return 0;
487 static int rebase_write_basic_state(struct rebase_options *opts)
489 write_file(state_dir_path("head-name", opts), "%s",
490 opts->head_name ? opts->head_name : "detached HEAD");
491 write_file(state_dir_path("onto", opts), "%s",
492 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
493 write_file(state_dir_path("orig-head", opts), "%s",
494 oid_to_hex(&opts->orig_head->object.oid));
495 if (!(opts->flags & REBASE_NO_QUIET))
496 write_file(state_dir_path("quiet", opts), "%s", "");
497 if (opts->flags & REBASE_VERBOSE)
498 write_file(state_dir_path("verbose", opts), "%s", "");
499 if (opts->allow_rerere_autoupdate > 0)
500 write_file(state_dir_path("allow_rerere_autoupdate", opts),
501 "-%s-rerere-autoupdate",
502 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
503 "" : "-no");
504 if (opts->gpg_sign_opt)
505 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
506 opts->gpg_sign_opt);
507 if (opts->signoff)
508 write_file(state_dir_path("signoff", opts), "--signoff");
510 return 0;
513 static int finish_rebase(struct rebase_options *opts)
515 struct strbuf dir = STRBUF_INIT;
516 int ret = 0;
518 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
519 unlink(git_path_auto_merge(the_repository));
520 apply_autostash(state_dir_path("autostash", opts));
522 * We ignore errors in 'git maintenance run --auto', since the
523 * user should see them.
525 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
526 if (opts->type == REBASE_MERGE) {
527 struct replay_opts replay = REPLAY_OPTS_INIT;
529 replay.action = REPLAY_INTERACTIVE_REBASE;
530 ret = sequencer_remove_state(&replay);
531 replay_opts_release(&replay);
532 } else {
533 strbuf_addstr(&dir, opts->state_dir);
534 if (remove_dir_recursively(&dir, 0))
535 ret = error(_("could not remove '%s'"),
536 opts->state_dir);
537 strbuf_release(&dir);
540 return ret;
543 static int move_to_original_branch(struct rebase_options *opts)
545 struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
546 struct reset_head_opts ropts = { 0 };
547 int ret;
549 if (!opts->head_name)
550 return 0; /* nothing to move back to */
552 if (!opts->onto)
553 BUG("move_to_original_branch without onto");
555 strbuf_addf(&branch_reflog, "%s (finish): %s onto %s",
556 opts->reflog_action,
557 opts->head_name, oid_to_hex(&opts->onto->object.oid));
558 strbuf_addf(&head_reflog, "%s (finish): returning to %s",
559 opts->reflog_action, opts->head_name);
560 ropts.branch = opts->head_name;
561 ropts.flags = RESET_HEAD_REFS_ONLY;
562 ropts.branch_msg = branch_reflog.buf;
563 ropts.head_msg = head_reflog.buf;
564 ret = reset_head(the_repository, &ropts);
566 strbuf_release(&branch_reflog);
567 strbuf_release(&head_reflog);
568 return ret;
571 static const char *resolvemsg =
572 N_("Resolve all conflicts manually, mark them as resolved with\n"
573 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
574 "You can instead skip this commit: run \"git rebase --skip\".\n"
575 "To abort and get back to the state before \"git rebase\", run "
576 "\"git rebase --abort\".");
578 static int run_am(struct rebase_options *opts)
580 struct child_process am = CHILD_PROCESS_INIT;
581 struct child_process format_patch = CHILD_PROCESS_INIT;
582 int status;
583 char *rebased_patches;
585 am.git_cmd = 1;
586 strvec_push(&am.args, "am");
587 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
588 opts->reflog_action);
589 if (opts->action == ACTION_CONTINUE) {
590 strvec_push(&am.args, "--resolved");
591 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
592 if (opts->gpg_sign_opt)
593 strvec_push(&am.args, opts->gpg_sign_opt);
594 status = run_command(&am);
595 if (status)
596 return status;
598 return move_to_original_branch(opts);
600 if (opts->action == ACTION_SKIP) {
601 strvec_push(&am.args, "--skip");
602 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
603 status = run_command(&am);
604 if (status)
605 return status;
607 return move_to_original_branch(opts);
609 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
610 strvec_push(&am.args, "--show-current-patch");
611 return run_command(&am);
614 rebased_patches = xstrdup(git_path("rebased-patches"));
615 format_patch.out = open(rebased_patches,
616 O_WRONLY | O_CREAT | O_TRUNC, 0666);
617 if (format_patch.out < 0) {
618 status = error_errno(_("could not open '%s' for writing"),
619 rebased_patches);
620 free(rebased_patches);
621 strvec_clear(&am.args);
622 return status;
625 format_patch.git_cmd = 1;
626 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
627 "--full-index", "--cherry-pick", "--right-only",
628 "--default-prefix", "--no-renames",
629 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
630 "--no-base", NULL);
631 if (opts->git_format_patch_opt.len)
632 strvec_split(&format_patch.args,
633 opts->git_format_patch_opt.buf);
634 strvec_pushf(&format_patch.args, "%s...%s",
635 oid_to_hex(opts->root ?
636 /* this is now equivalent to !opts->upstream */
637 &opts->onto->object.oid :
638 &opts->upstream->object.oid),
639 oid_to_hex(&opts->orig_head->object.oid));
640 if (opts->restrict_revision)
641 strvec_pushf(&format_patch.args, "^%s",
642 oid_to_hex(&opts->restrict_revision->object.oid));
644 status = run_command(&format_patch);
645 if (status) {
646 struct reset_head_opts ropts = { 0 };
647 unlink(rebased_patches);
648 free(rebased_patches);
649 strvec_clear(&am.args);
651 ropts.oid = &opts->orig_head->object.oid;
652 ropts.branch = opts->head_name;
653 ropts.default_reflog_action = opts->reflog_action;
654 reset_head(the_repository, &ropts);
655 error(_("\ngit encountered an error while preparing the "
656 "patches to replay\n"
657 "these revisions:\n"
658 "\n %s\n\n"
659 "As a result, git cannot rebase them."),
660 opts->revisions);
662 return status;
665 am.in = open(rebased_patches, O_RDONLY);
666 if (am.in < 0) {
667 status = error_errno(_("could not open '%s' for reading"),
668 rebased_patches);
669 free(rebased_patches);
670 strvec_clear(&am.args);
671 return status;
674 strvec_pushv(&am.args, opts->git_am_opts.v);
675 strvec_push(&am.args, "--rebasing");
676 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
677 strvec_push(&am.args, "--patch-format=mboxrd");
678 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
679 strvec_push(&am.args, "--rerere-autoupdate");
680 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
681 strvec_push(&am.args, "--no-rerere-autoupdate");
682 if (opts->gpg_sign_opt)
683 strvec_push(&am.args, opts->gpg_sign_opt);
684 status = run_command(&am);
685 unlink(rebased_patches);
686 free(rebased_patches);
688 if (!status) {
689 return move_to_original_branch(opts);
692 if (is_directory(opts->state_dir))
693 rebase_write_basic_state(opts);
695 return status;
698 static int run_specific_rebase(struct rebase_options *opts)
700 int status;
702 if (opts->type == REBASE_MERGE) {
703 /* Run sequencer-based rebase */
704 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
705 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
706 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
707 opts->autosquash = 0;
709 if (opts->gpg_sign_opt) {
710 /* remove the leading "-S" */
711 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
712 free(opts->gpg_sign_opt);
713 opts->gpg_sign_opt = tmp;
716 status = run_sequencer_rebase(opts);
717 } else if (opts->type == REBASE_APPLY)
718 status = run_am(opts);
719 else
720 BUG("Unhandled rebase type %d", opts->type);
722 if (opts->dont_finish_rebase)
723 ; /* do nothing */
724 else if (opts->type == REBASE_MERGE)
725 ; /* merge backend cleans up after itself */
726 else if (status == 0) {
727 if (!file_exists(state_dir_path("stopped-sha", opts)))
728 finish_rebase(opts);
729 } else if (status == 2) {
730 struct strbuf dir = STRBUF_INIT;
732 apply_autostash(state_dir_path("autostash", opts));
733 strbuf_addstr(&dir, opts->state_dir);
734 remove_dir_recursively(&dir, 0);
735 strbuf_release(&dir);
736 die("Nothing to do");
739 return status ? -1 : 0;
742 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
744 if (!strcmp("no-rebase-cousins", value))
745 options->rebase_cousins = 0;
746 else if (!strcmp("rebase-cousins", value))
747 options->rebase_cousins = 1;
748 else
749 die(_("Unknown rebase-merges mode: %s"), value);
752 static int rebase_config(const char *var, const char *value,
753 const struct config_context *ctx, void *data)
755 struct rebase_options *opts = data;
757 if (!strcmp(var, "rebase.stat")) {
758 if (git_config_bool(var, value))
759 opts->flags |= REBASE_DIFFSTAT;
760 else
761 opts->flags &= ~REBASE_DIFFSTAT;
762 return 0;
765 if (!strcmp(var, "rebase.autosquash")) {
766 opts->config_autosquash = git_config_bool(var, value);
767 return 0;
770 if (!strcmp(var, "commit.gpgsign")) {
771 free(opts->gpg_sign_opt);
772 opts->gpg_sign_opt = git_config_bool(var, value) ?
773 xstrdup("-S") : NULL;
774 return 0;
777 if (!strcmp(var, "rebase.autostash")) {
778 opts->autostash = git_config_bool(var, value);
779 return 0;
782 if (!strcmp(var, "rebase.rebasemerges")) {
783 opts->config_rebase_merges = git_parse_maybe_bool(value);
784 if (opts->config_rebase_merges < 0) {
785 opts->config_rebase_merges = 1;
786 parse_rebase_merges_value(opts, value);
787 } else {
788 opts->rebase_cousins = 0;
790 return 0;
793 if (!strcmp(var, "rebase.updaterefs")) {
794 opts->config_update_refs = git_config_bool(var, value);
795 return 0;
798 if (!strcmp(var, "rebase.reschedulefailedexec")) {
799 opts->reschedule_failed_exec = git_config_bool(var, value);
800 return 0;
803 if (!strcmp(var, "rebase.forkpoint")) {
804 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
805 return 0;
808 if (!strcmp(var, "rebase.backend")) {
809 return git_config_string(&opts->default_backend, var, value);
812 return git_default_config(var, value, ctx, data);
815 static int checkout_up_to_date(struct rebase_options *options)
817 struct strbuf buf = STRBUF_INIT;
818 struct reset_head_opts ropts = { 0 };
819 int ret = 0;
821 strbuf_addf(&buf, "%s: checkout %s",
822 options->reflog_action, options->switch_to);
823 ropts.oid = &options->orig_head->object.oid;
824 ropts.branch = options->head_name;
825 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
826 if (!ropts.branch)
827 ropts.flags |= RESET_HEAD_DETACH;
828 ropts.head_msg = buf.buf;
829 if (reset_head(the_repository, &ropts) < 0)
830 ret = error(_("could not switch to %s"), options->switch_to);
831 strbuf_release(&buf);
833 return ret;
837 * Determines whether the commits in from..to are linear, i.e. contain
838 * no merge commits. This function *expects* `from` to be an ancestor of
839 * `to`.
841 static int is_linear_history(struct commit *from, struct commit *to)
843 while (to && to != from) {
844 repo_parse_commit(the_repository, to);
845 if (!to->parents)
846 return 1;
847 if (to->parents->next)
848 return 0;
849 to = to->parents->item;
851 return 1;
854 static int can_fast_forward(struct commit *onto, struct commit *upstream,
855 struct commit *restrict_revision,
856 struct commit *head, struct object_id *branch_base)
858 struct commit_list *merge_bases = NULL;
859 int res = 0;
861 if (is_null_oid(branch_base))
862 goto done; /* fill_branch_base() found multiple merge bases */
864 if (!oideq(branch_base, &onto->object.oid))
865 goto done;
867 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
868 goto done;
870 if (!upstream)
871 goto done;
873 merge_bases = repo_get_merge_bases(the_repository, upstream, head);
874 if (!merge_bases || merge_bases->next)
875 goto done;
877 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
878 goto done;
880 res = 1;
882 done:
883 free_commit_list(merge_bases);
884 return res && is_linear_history(onto, head);
887 static void fill_branch_base(struct rebase_options *options,
888 struct object_id *branch_base)
890 struct commit_list *merge_bases = NULL;
892 merge_bases = repo_get_merge_bases(the_repository, options->onto,
893 options->orig_head);
894 if (!merge_bases || merge_bases->next)
895 oidcpy(branch_base, null_oid());
896 else
897 oidcpy(branch_base, &merge_bases->item->object.oid);
899 free_commit_list(merge_bases);
902 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
904 struct rebase_options *opts = opt->value;
906 BUG_ON_OPT_NEG(unset);
907 BUG_ON_OPT_ARG(arg);
909 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
910 die(_("apply options and merge options cannot be used together"));
912 opts->type = REBASE_APPLY;
914 return 0;
917 /* -i followed by -m is still -i */
918 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
920 struct rebase_options *opts = opt->value;
922 BUG_ON_OPT_NEG(unset);
923 BUG_ON_OPT_ARG(arg);
925 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
926 die(_("apply options and merge options cannot be used together"));
928 opts->type = REBASE_MERGE;
930 return 0;
933 /* -i followed by -r is still explicitly interactive, but -r alone is not */
934 static int parse_opt_interactive(const struct option *opt, const char *arg,
935 int unset)
937 struct rebase_options *opts = opt->value;
939 BUG_ON_OPT_NEG(unset);
940 BUG_ON_OPT_ARG(arg);
942 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
943 die(_("apply options and merge options cannot be used together"));
945 opts->type = REBASE_MERGE;
946 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
948 return 0;
951 static enum empty_type parse_empty_value(const char *value)
953 if (!strcasecmp(value, "drop"))
954 return EMPTY_DROP;
955 else if (!strcasecmp(value, "keep"))
956 return EMPTY_KEEP;
957 else if (!strcasecmp(value, "ask"))
958 return EMPTY_ASK;
960 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
963 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
964 int unset)
966 struct rebase_options *opts = opt->value;
968 BUG_ON_OPT_ARG(arg);
970 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
971 opts->keep_empty = !unset;
972 return 0;
975 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
977 struct rebase_options *options = opt->value;
978 enum empty_type value = parse_empty_value(arg);
980 BUG_ON_OPT_NEG(unset);
982 options->empty = value;
983 return 0;
986 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
988 struct rebase_options *options = opt->value;
990 options->rebase_merges = !unset;
991 options->rebase_cousins = 0;
993 if (arg) {
994 if (!*arg) {
995 warning(_("--rebase-merges with an empty string "
996 "argument is deprecated and will stop "
997 "working in a future version of Git. Use "
998 "--rebase-merges without an argument "
999 "instead, which does the same thing."));
1000 return 0;
1002 parse_rebase_merges_value(options, arg);
1005 return 0;
1008 static void NORETURN error_on_missing_default_upstream(void)
1010 struct branch *current_branch = branch_get(NULL);
1012 printf(_("%s\n"
1013 "Please specify which branch you want to rebase against.\n"
1014 "See git-rebase(1) for details.\n"
1015 "\n"
1016 " git rebase '<branch>'\n"
1017 "\n"),
1018 current_branch ? _("There is no tracking information for "
1019 "the current branch.") :
1020 _("You are not currently on a branch."));
1022 if (current_branch) {
1023 const char *remote = current_branch->remote_name;
1025 if (!remote)
1026 remote = _("<remote>");
1028 printf(_("If you wish to set tracking information for this "
1029 "branch you can do so with:\n"
1030 "\n"
1031 " git branch --set-upstream-to=%s/<branch> %s\n"
1032 "\n"),
1033 remote, current_branch->name);
1035 exit(1);
1038 static int check_exec_cmd(const char *cmd)
1040 if (strchr(cmd, '\n'))
1041 return error(_("exec commands cannot contain newlines"));
1043 /* Does the command consist purely of whitespace? */
1044 if (!cmd[strspn(cmd, " \t\r\f\v")])
1045 return error(_("empty exec command"));
1047 return 0;
1050 int cmd_rebase(int argc, const char **argv, const char *prefix)
1052 struct rebase_options options = REBASE_OPTIONS_INIT;
1053 const char *branch_name;
1054 int ret, flags, total_argc, in_progress = 0;
1055 int keep_base = 0;
1056 int ok_to_skip_pre_rebase = 0;
1057 struct strbuf msg = STRBUF_INIT;
1058 struct strbuf revisions = STRBUF_INIT;
1059 struct strbuf buf = STRBUF_INIT;
1060 struct object_id branch_base;
1061 int ignore_whitespace = 0;
1062 const char *gpg_sign = NULL;
1063 struct object_id squash_onto;
1064 char *squash_onto_name = NULL;
1065 char *keep_base_onto_name = NULL;
1066 int reschedule_failed_exec = -1;
1067 int allow_preemptive_ff = 1;
1068 int preserve_merges_selected = 0;
1069 struct reset_head_opts ropts = { 0 };
1070 struct option builtin_rebase_options[] = {
1071 OPT_STRING(0, "onto", &options.onto_name,
1072 N_("revision"),
1073 N_("rebase onto given branch instead of upstream")),
1074 OPT_BOOL(0, "keep-base", &keep_base,
1075 N_("use the merge-base of upstream and branch as the current base")),
1076 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1077 N_("allow pre-rebase hook to run")),
1078 OPT_NEGBIT('q', "quiet", &options.flags,
1079 N_("be quiet. implies --no-stat"),
1080 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1081 OPT_BIT('v', "verbose", &options.flags,
1082 N_("display a diffstat of what changed upstream"),
1083 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1084 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1085 N_("do not show diffstat of what changed upstream"),
1086 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1087 OPT_BOOL(0, "signoff", &options.signoff,
1088 N_("add a Signed-off-by trailer to each commit")),
1089 OPT_BOOL(0, "committer-date-is-author-date",
1090 &options.committer_date_is_author_date,
1091 N_("make committer date match author date")),
1092 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1093 N_("ignore author date and use current date")),
1094 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1095 N_("synonym of --reset-author-date")),
1096 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1097 N_("passed to 'git apply'"), 0),
1098 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1099 N_("ignore changes in whitespace")),
1100 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1101 N_("action"), N_("passed to 'git apply'"), 0),
1102 OPT_BIT('f', "force-rebase", &options.flags,
1103 N_("cherry-pick all commits, even if unchanged"),
1104 REBASE_FORCE),
1105 OPT_BIT(0, "no-ff", &options.flags,
1106 N_("cherry-pick all commits, even if unchanged"),
1107 REBASE_FORCE),
1108 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1109 ACTION_CONTINUE),
1110 OPT_CMDMODE(0, "skip", &options.action,
1111 N_("skip current patch and continue"), ACTION_SKIP),
1112 OPT_CMDMODE(0, "abort", &options.action,
1113 N_("abort and check out the original branch"),
1114 ACTION_ABORT),
1115 OPT_CMDMODE(0, "quit", &options.action,
1116 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1117 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1118 "during an interactive rebase"), ACTION_EDIT_TODO),
1119 OPT_CMDMODE(0, "show-current-patch", &options.action,
1120 N_("show the patch file being applied or merged"),
1121 ACTION_SHOW_CURRENT_PATCH),
1122 OPT_CALLBACK_F(0, "apply", &options, NULL,
1123 N_("use apply strategies to rebase"),
1124 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1125 parse_opt_am),
1126 OPT_CALLBACK_F('m', "merge", &options, NULL,
1127 N_("use merging strategies to rebase"),
1128 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1129 parse_opt_merge),
1130 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1131 N_("let the user edit the list of commits to rebase"),
1132 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1133 parse_opt_interactive),
1134 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1135 N_("(REMOVED) was: try to recreate merges "
1136 "instead of ignoring them"),
1137 1, PARSE_OPT_HIDDEN),
1138 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1139 OPT_CALLBACK_F(0, "empty", &options, "(drop|keep|ask)",
1140 N_("how to handle commits that become empty"),
1141 PARSE_OPT_NONEG, parse_opt_empty),
1142 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1143 N_("keep commits which start empty"),
1144 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1145 parse_opt_keep_empty),
1146 OPT_BOOL(0, "autosquash", &options.autosquash,
1147 N_("move commits that begin with "
1148 "squash!/fixup! under -i")),
1149 OPT_BOOL(0, "update-refs", &options.update_refs,
1150 N_("update branches that point to commits "
1151 "that are being rebased")),
1152 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1153 N_("GPG-sign commits"),
1154 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1155 OPT_AUTOSTASH(&options.autostash),
1156 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1157 N_("add exec lines after each commit of the "
1158 "editable list")),
1159 OPT_BOOL_F(0, "allow-empty-message",
1160 &options.allow_empty_message,
1161 N_("allow rebasing commits with empty messages"),
1162 PARSE_OPT_HIDDEN),
1163 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1164 N_("try to rebase merges instead of skipping them"),
1165 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1166 OPT_BOOL(0, "fork-point", &options.fork_point,
1167 N_("use 'merge-base --fork-point' to refine upstream")),
1168 OPT_STRING('s', "strategy", &options.strategy,
1169 N_("strategy"), N_("use the given merge strategy")),
1170 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1171 N_("option"),
1172 N_("pass the argument through to the merge "
1173 "strategy")),
1174 OPT_BOOL(0, "root", &options.root,
1175 N_("rebase all reachable commits up to the root(s)")),
1176 OPT_BOOL(0, "reschedule-failed-exec",
1177 &reschedule_failed_exec,
1178 N_("automatically re-schedule any `exec` that fails")),
1179 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1180 N_("apply all changes, even those already present upstream")),
1181 OPT_END(),
1183 int i;
1185 if (argc == 2 && !strcmp(argv[1], "-h"))
1186 usage_with_options(builtin_rebase_usage,
1187 builtin_rebase_options);
1189 prepare_repo_settings(the_repository);
1190 the_repository->settings.command_requires_full_index = 0;
1192 git_config(rebase_config, &options);
1193 /* options.gpg_sign_opt will be either "-S" or NULL */
1194 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1195 FREE_AND_NULL(options.gpg_sign_opt);
1197 strbuf_reset(&buf);
1198 strbuf_addf(&buf, "%s/applying", apply_dir());
1199 if(file_exists(buf.buf))
1200 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1202 if (is_directory(apply_dir())) {
1203 options.type = REBASE_APPLY;
1204 options.state_dir = apply_dir();
1205 } else if (is_directory(merge_dir())) {
1206 strbuf_reset(&buf);
1207 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1208 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1209 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1210 "Use `git rebase --abort` to terminate current rebase.\n"
1211 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1212 } else {
1213 strbuf_reset(&buf);
1214 strbuf_addf(&buf, "%s/interactive", merge_dir());
1215 options.type = REBASE_MERGE;
1216 if (file_exists(buf.buf))
1217 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1219 options.state_dir = merge_dir();
1222 if (options.type != REBASE_UNSPECIFIED)
1223 in_progress = 1;
1225 total_argc = argc;
1226 argc = parse_options(argc, argv, prefix,
1227 builtin_rebase_options,
1228 builtin_rebase_usage, 0);
1230 if (preserve_merges_selected)
1231 die(_("--preserve-merges was replaced by --rebase-merges\n"
1232 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1233 "which is no longer supported; use 'merges' instead"));
1235 if (options.action != ACTION_NONE && total_argc != 2) {
1236 usage_with_options(builtin_rebase_usage,
1237 builtin_rebase_options);
1240 if (argc > 2)
1241 usage_with_options(builtin_rebase_usage,
1242 builtin_rebase_options);
1244 if (keep_base) {
1245 if (options.onto_name)
1246 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1247 if (options.root)
1248 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1250 * --keep-base defaults to --no-fork-point to keep the
1251 * base the same.
1253 if (options.fork_point < 0)
1254 options.fork_point = 0;
1256 if (options.root && options.fork_point > 0)
1257 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1259 if (options.action != ACTION_NONE && !in_progress)
1260 die(_("No rebase in progress?"));
1262 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1263 die(_("The --edit-todo action can only be used during "
1264 "interactive rebase."));
1266 if (trace2_is_enabled()) {
1267 if (is_merge(&options))
1268 trace2_cmd_mode("interactive");
1269 else if (options.exec.nr)
1270 trace2_cmd_mode("interactive-exec");
1271 else
1272 trace2_cmd_mode(action_names[options.action]);
1275 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1276 options.reflog_action =
1277 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1279 switch (options.action) {
1280 case ACTION_CONTINUE: {
1281 struct object_id head;
1282 struct lock_file lock_file = LOCK_INIT;
1283 int fd;
1285 /* Sanity check */
1286 if (repo_get_oid(the_repository, "HEAD", &head))
1287 die(_("Cannot read HEAD"));
1289 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1290 if (repo_read_index(the_repository) < 0)
1291 die(_("could not read index"));
1292 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1293 NULL);
1294 if (0 <= fd)
1295 repo_update_index_if_able(the_repository, &lock_file);
1296 rollback_lock_file(&lock_file);
1298 if (has_unstaged_changes(the_repository, 1)) {
1299 puts(_("You must edit all merge conflicts and then\n"
1300 "mark them as resolved using git add"));
1301 exit(1);
1303 if (read_basic_state(&options))
1304 exit(1);
1305 goto run_rebase;
1307 case ACTION_SKIP: {
1308 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1310 rerere_clear(the_repository, &merge_rr);
1311 string_list_clear(&merge_rr, 1);
1312 ropts.flags = RESET_HEAD_HARD;
1313 if (reset_head(the_repository, &ropts) < 0)
1314 die(_("could not discard worktree changes"));
1315 remove_branch_state(the_repository, 0);
1316 if (read_basic_state(&options))
1317 exit(1);
1318 goto run_rebase;
1320 case ACTION_ABORT: {
1321 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1322 struct strbuf head_msg = STRBUF_INIT;
1324 rerere_clear(the_repository, &merge_rr);
1325 string_list_clear(&merge_rr, 1);
1327 if (read_basic_state(&options))
1328 exit(1);
1330 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1331 options.reflog_action,
1332 options.head_name ? options.head_name
1333 : oid_to_hex(&options.orig_head->object.oid));
1334 ropts.oid = &options.orig_head->object.oid;
1335 ropts.head_msg = head_msg.buf;
1336 ropts.branch = options.head_name;
1337 ropts.flags = RESET_HEAD_HARD;
1338 if (reset_head(the_repository, &ropts) < 0)
1339 die(_("could not move back to %s"),
1340 oid_to_hex(&options.orig_head->object.oid));
1341 strbuf_release(&head_msg);
1342 remove_branch_state(the_repository, 0);
1343 ret = finish_rebase(&options);
1344 goto cleanup;
1346 case ACTION_QUIT: {
1347 save_autostash(state_dir_path("autostash", &options));
1348 if (options.type == REBASE_MERGE) {
1349 struct replay_opts replay = REPLAY_OPTS_INIT;
1351 replay.action = REPLAY_INTERACTIVE_REBASE;
1352 ret = sequencer_remove_state(&replay);
1353 replay_opts_release(&replay);
1354 } else {
1355 strbuf_reset(&buf);
1356 strbuf_addstr(&buf, options.state_dir);
1357 ret = remove_dir_recursively(&buf, 0);
1358 if (ret)
1359 error(_("could not remove '%s'"),
1360 options.state_dir);
1362 goto cleanup;
1364 case ACTION_EDIT_TODO:
1365 options.dont_finish_rebase = 1;
1366 goto run_rebase;
1367 case ACTION_SHOW_CURRENT_PATCH:
1368 options.dont_finish_rebase = 1;
1369 goto run_rebase;
1370 case ACTION_NONE:
1371 break;
1372 default:
1373 BUG("action: %d", options.action);
1376 /* Make sure no rebase is in progress */
1377 if (in_progress) {
1378 const char *last_slash = strrchr(options.state_dir, '/');
1379 const char *state_dir_base =
1380 last_slash ? last_slash + 1 : options.state_dir;
1381 const char *cmd_live_rebase =
1382 "git rebase (--continue | --abort | --skip)";
1383 strbuf_reset(&buf);
1384 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1385 die(_("It seems that there is already a %s directory, and\n"
1386 "I wonder if you are in the middle of another rebase. "
1387 "If that is the\n"
1388 "case, please try\n\t%s\n"
1389 "If that is not the case, please\n\t%s\n"
1390 "and run me again. I am stopping in case you still "
1391 "have something\n"
1392 "valuable there.\n"),
1393 state_dir_base, cmd_live_rebase, buf.buf);
1396 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1397 (options.action != ACTION_NONE) ||
1398 (options.exec.nr > 0) ||
1399 (options.autosquash == -1 && options.config_autosquash == 1) ||
1400 options.autosquash == 1) {
1401 allow_preemptive_ff = 0;
1403 if (options.committer_date_is_author_date || options.ignore_date)
1404 options.flags |= REBASE_FORCE;
1406 for (i = 0; i < options.git_am_opts.nr; i++) {
1407 const char *option = options.git_am_opts.v[i], *p;
1408 if (!strcmp(option, "--whitespace=fix") ||
1409 !strcmp(option, "--whitespace=strip"))
1410 allow_preemptive_ff = 0;
1411 else if (skip_prefix(option, "-C", &p)) {
1412 while (*p)
1413 if (!isdigit(*(p++)))
1414 die(_("switch `C' expects a "
1415 "numerical value"));
1416 } else if (skip_prefix(option, "--whitespace=", &p)) {
1417 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1418 strcmp(p, "error") && strcmp(p, "error-all"))
1419 die("Invalid whitespace option: '%s'", p);
1423 for (i = 0; i < options.exec.nr; i++)
1424 if (check_exec_cmd(options.exec.items[i].string))
1425 exit(1);
1427 if (!(options.flags & REBASE_NO_QUIET))
1428 strvec_push(&options.git_am_opts, "-q");
1430 if (options.empty != EMPTY_UNSPECIFIED)
1431 imply_merge(&options, "--empty");
1433 if (options.reapply_cherry_picks < 0)
1435 * We default to --no-reapply-cherry-picks unless
1436 * --keep-base is given; when --keep-base is given, we want
1437 * to default to --reapply-cherry-picks.
1439 options.reapply_cherry_picks = keep_base;
1440 else if (!keep_base)
1442 * The apply backend always searches for and drops cherry
1443 * picks. This is often not wanted with --keep-base, so
1444 * --keep-base allows --reapply-cherry-picks to be
1445 * simulated by altering the upstream such that
1446 * cherry-picks cannot be detected and thus all commits are
1447 * reapplied. Thus, --[no-]reapply-cherry-picks is
1448 * supported when --keep-base is specified, but not when
1449 * --keep-base is left out.
1451 imply_merge(&options, options.reapply_cherry_picks ?
1452 "--reapply-cherry-picks" :
1453 "--no-reapply-cherry-picks");
1455 if (gpg_sign)
1456 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1458 if (options.exec.nr)
1459 imply_merge(&options, "--exec");
1461 if (options.type == REBASE_APPLY) {
1462 if (ignore_whitespace)
1463 strvec_push(&options.git_am_opts,
1464 "--ignore-whitespace");
1465 if (options.committer_date_is_author_date)
1466 strvec_push(&options.git_am_opts,
1467 "--committer-date-is-author-date");
1468 if (options.ignore_date)
1469 strvec_push(&options.git_am_opts, "--ignore-date");
1470 } else {
1471 /* REBASE_MERGE */
1472 if (ignore_whitespace) {
1473 string_list_append(&options.strategy_opts,
1474 "ignore-space-change");
1478 if (options.strategy_opts.nr && !options.strategy)
1479 options.strategy = "ort";
1481 if (options.strategy) {
1482 options.strategy = xstrdup(options.strategy);
1483 imply_merge(&options, "--strategy");
1486 if (options.root && !options.onto_name)
1487 imply_merge(&options, "--root without --onto");
1489 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1490 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1492 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1493 /* all am options except -q are compatible only with --apply */
1494 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1495 if (strcmp(options.git_am_opts.v[i], "-q"))
1496 break;
1498 if (i >= 0 || options.type == REBASE_APPLY) {
1499 if (is_merge(&options))
1500 die(_("apply options and merge options "
1501 "cannot be used together"));
1502 else if (options.autosquash == -1 && options.config_autosquash == 1)
1503 die(_("apply options are incompatible with rebase.autoSquash. Consider adding --no-autosquash"));
1504 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1505 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1506 else if (options.update_refs == -1 && options.config_update_refs == 1)
1507 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1508 else
1509 options.type = REBASE_APPLY;
1513 if (options.update_refs == 1)
1514 imply_merge(&options, "--update-refs");
1515 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1516 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1518 if (options.rebase_merges == 1)
1519 imply_merge(&options, "--rebase-merges");
1520 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1521 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1523 if (options.autosquash == 1)
1524 imply_merge(&options, "--autosquash");
1525 options.autosquash = (options.autosquash >= 0) ? options.autosquash :
1526 ((options.config_autosquash >= 0) ? options.config_autosquash : 0);
1528 if (options.type == REBASE_UNSPECIFIED) {
1529 if (!strcmp(options.default_backend, "merge"))
1530 options.type = REBASE_MERGE;
1531 else if (!strcmp(options.default_backend, "apply"))
1532 options.type = REBASE_APPLY;
1533 else
1534 die(_("Unknown rebase backend: %s"),
1535 options.default_backend);
1538 if (options.type == REBASE_MERGE &&
1539 !options.strategy &&
1540 getenv("GIT_TEST_MERGE_ALGORITHM"))
1541 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1543 switch (options.type) {
1544 case REBASE_MERGE:
1545 options.state_dir = merge_dir();
1546 break;
1547 case REBASE_APPLY:
1548 options.state_dir = apply_dir();
1549 break;
1550 default:
1551 BUG("options.type was just set above; should be unreachable.");
1554 if (options.empty == EMPTY_UNSPECIFIED) {
1555 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1556 options.empty = EMPTY_ASK;
1557 else if (options.exec.nr > 0)
1558 options.empty = EMPTY_KEEP;
1559 else
1560 options.empty = EMPTY_DROP;
1562 if (reschedule_failed_exec > 0 && !is_merge(&options))
1563 die(_("--reschedule-failed-exec requires "
1564 "--exec or --interactive"));
1565 if (reschedule_failed_exec >= 0)
1566 options.reschedule_failed_exec = reschedule_failed_exec;
1568 if (options.signoff) {
1569 strvec_push(&options.git_am_opts, "--signoff");
1570 options.flags |= REBASE_FORCE;
1573 if (!options.root) {
1574 if (argc < 1) {
1575 struct branch *branch;
1577 branch = branch_get(NULL);
1578 options.upstream_name = branch_get_upstream(branch,
1579 NULL);
1580 if (!options.upstream_name)
1581 error_on_missing_default_upstream();
1582 if (options.fork_point < 0)
1583 options.fork_point = 1;
1584 } else {
1585 options.upstream_name = argv[0];
1586 argc--;
1587 argv++;
1588 if (!strcmp(options.upstream_name, "-"))
1589 options.upstream_name = "@{-1}";
1591 options.upstream =
1592 lookup_commit_reference_by_name(options.upstream_name);
1593 if (!options.upstream)
1594 die(_("invalid upstream '%s'"), options.upstream_name);
1595 options.upstream_arg = options.upstream_name;
1596 } else {
1597 if (!options.onto_name) {
1598 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1599 &squash_onto, NULL, NULL) < 0)
1600 die(_("Could not create new root commit"));
1601 options.squash_onto = &squash_onto;
1602 options.onto_name = squash_onto_name =
1603 xstrdup(oid_to_hex(&squash_onto));
1604 } else
1605 options.root_with_onto = 1;
1607 options.upstream_name = NULL;
1608 options.upstream = NULL;
1609 if (argc > 1)
1610 usage_with_options(builtin_rebase_usage,
1611 builtin_rebase_options);
1612 options.upstream_arg = "--root";
1616 * If the branch to rebase is given, that is the branch we will rebase
1617 * branch_name -- branch/commit being rebased, or
1618 * HEAD (already detached)
1619 * orig_head -- commit object name of tip of the branch before rebasing
1620 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1622 if (argc == 1) {
1623 /* Is it "rebase other branchname" or "rebase other commit"? */
1624 struct object_id branch_oid;
1625 branch_name = argv[0];
1626 options.switch_to = argv[0];
1628 /* Is it a local branch? */
1629 strbuf_reset(&buf);
1630 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1631 if (!read_ref(buf.buf, &branch_oid)) {
1632 die_if_checked_out(buf.buf, 1);
1633 options.head_name = xstrdup(buf.buf);
1634 options.orig_head =
1635 lookup_commit_object(the_repository,
1636 &branch_oid);
1637 /* If not is it a valid ref (branch or commit)? */
1638 } else {
1639 options.orig_head =
1640 lookup_commit_reference_by_name(branch_name);
1641 options.head_name = NULL;
1643 if (!options.orig_head)
1644 die(_("no such branch/commit '%s'"), branch_name);
1645 } else if (argc == 0) {
1646 /* Do not need to switch branches, we are already on it. */
1647 options.head_name =
1648 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1649 &flags));
1650 if (!options.head_name)
1651 die(_("No such ref: %s"), "HEAD");
1652 if (flags & REF_ISSYMREF) {
1653 if (!skip_prefix(options.head_name,
1654 "refs/heads/", &branch_name))
1655 branch_name = options.head_name;
1657 } else {
1658 FREE_AND_NULL(options.head_name);
1659 branch_name = "HEAD";
1661 options.orig_head = lookup_commit_reference_by_name("HEAD");
1662 if (!options.orig_head)
1663 die(_("Could not resolve HEAD to a commit"));
1664 } else
1665 BUG("unexpected number of arguments left to parse");
1667 /* Make sure the branch to rebase onto is valid. */
1668 if (keep_base) {
1669 strbuf_reset(&buf);
1670 strbuf_addstr(&buf, options.upstream_name);
1671 strbuf_addstr(&buf, "...");
1672 strbuf_addstr(&buf, branch_name);
1673 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1674 } else if (!options.onto_name)
1675 options.onto_name = options.upstream_name;
1676 if (strstr(options.onto_name, "...")) {
1677 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1678 if (keep_base)
1679 die(_("'%s': need exactly one merge base with branch"),
1680 options.upstream_name);
1681 else
1682 die(_("'%s': need exactly one merge base"),
1683 options.onto_name);
1685 options.onto = lookup_commit_or_die(&branch_base,
1686 options.onto_name);
1687 } else {
1688 options.onto =
1689 lookup_commit_reference_by_name(options.onto_name);
1690 if (!options.onto)
1691 die(_("Does not point to a valid commit '%s'"),
1692 options.onto_name);
1693 fill_branch_base(&options, &branch_base);
1696 if (keep_base && options.reapply_cherry_picks)
1697 options.upstream = options.onto;
1699 if (options.fork_point > 0)
1700 options.restrict_revision =
1701 get_fork_point(options.upstream_name, options.orig_head);
1703 if (repo_read_index(the_repository) < 0)
1704 die(_("could not read index"));
1706 if (options.autostash)
1707 create_autostash(the_repository,
1708 state_dir_path("autostash", &options));
1711 if (require_clean_work_tree(the_repository, "rebase",
1712 _("Please commit or stash them."), 1, 1)) {
1713 ret = -1;
1714 goto cleanup;
1718 * Now we are rebasing commits upstream..orig_head (or with --root,
1719 * everything leading up to orig_head) on top of onto.
1723 * Check if we are already based on onto with linear history,
1724 * in which case we could fast-forward without replacing the commits
1725 * with new commits recreated by replaying their changes.
1727 if (allow_preemptive_ff &&
1728 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1729 options.orig_head, &branch_base)) {
1730 int flag;
1732 if (!(options.flags & REBASE_FORCE)) {
1733 /* Lazily switch to the target branch if needed... */
1734 if (options.switch_to) {
1735 ret = checkout_up_to_date(&options);
1736 if (ret)
1737 goto cleanup;
1740 if (!(options.flags & REBASE_NO_QUIET))
1741 ; /* be quiet */
1742 else if (!strcmp(branch_name, "HEAD") &&
1743 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1744 puts(_("HEAD is up to date."));
1745 else
1746 printf(_("Current branch %s is up to date.\n"),
1747 branch_name);
1748 ret = finish_rebase(&options);
1749 goto cleanup;
1750 } else if (!(options.flags & REBASE_NO_QUIET))
1751 ; /* be quiet */
1752 else if (!strcmp(branch_name, "HEAD") &&
1753 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1754 puts(_("HEAD is up to date, rebase forced."));
1755 else
1756 printf(_("Current branch %s is up to date, rebase "
1757 "forced.\n"), branch_name);
1760 /* If a hook exists, give it a chance to interrupt*/
1761 if (!ok_to_skip_pre_rebase &&
1762 run_hooks_l("pre-rebase", options.upstream_arg,
1763 argc ? argv[0] : NULL, NULL))
1764 die(_("The pre-rebase hook refused to rebase."));
1766 if (options.flags & REBASE_DIFFSTAT) {
1767 struct diff_options opts;
1769 if (options.flags & REBASE_VERBOSE) {
1770 if (is_null_oid(&branch_base))
1771 printf(_("Changes to %s:\n"),
1772 oid_to_hex(&options.onto->object.oid));
1773 else
1774 printf(_("Changes from %s to %s:\n"),
1775 oid_to_hex(&branch_base),
1776 oid_to_hex(&options.onto->object.oid));
1779 /* We want color (if set), but no pager */
1780 repo_diff_setup(the_repository, &opts);
1781 init_diffstat_widths(&opts);
1782 opts.output_format |=
1783 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1784 opts.detect_rename = DIFF_DETECT_RENAME;
1785 diff_setup_done(&opts);
1786 diff_tree_oid(is_null_oid(&branch_base) ?
1787 the_hash_algo->empty_tree : &branch_base,
1788 &options.onto->object.oid, "", &opts);
1789 diffcore_std(&opts);
1790 diff_flush(&opts);
1793 if (is_merge(&options))
1794 goto run_rebase;
1796 /* Detach HEAD and reset the tree */
1797 if (options.flags & REBASE_NO_QUIET)
1798 printf(_("First, rewinding head to replay your work on top of "
1799 "it...\n"));
1801 strbuf_addf(&msg, "%s (start): checkout %s",
1802 options.reflog_action, options.onto_name);
1803 ropts.oid = &options.onto->object.oid;
1804 ropts.orig_head = &options.orig_head->object.oid,
1805 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1806 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1807 ropts.head_msg = msg.buf;
1808 ropts.default_reflog_action = options.reflog_action;
1809 if (reset_head(the_repository, &ropts))
1810 die(_("Could not detach HEAD"));
1811 strbuf_release(&msg);
1814 * If the onto is a proper descendant of the tip of the branch, then
1815 * we just fast-forwarded.
1817 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1818 printf(_("Fast-forwarded %s to %s.\n"),
1819 branch_name, options.onto_name);
1820 move_to_original_branch(&options);
1821 ret = finish_rebase(&options);
1822 goto cleanup;
1825 strbuf_addf(&revisions, "%s..%s",
1826 options.root ? oid_to_hex(&options.onto->object.oid) :
1827 (options.restrict_revision ?
1828 oid_to_hex(&options.restrict_revision->object.oid) :
1829 oid_to_hex(&options.upstream->object.oid)),
1830 oid_to_hex(&options.orig_head->object.oid));
1832 options.revisions = revisions.buf;
1834 run_rebase:
1835 ret = run_specific_rebase(&options);
1837 cleanup:
1838 strbuf_release(&buf);
1839 strbuf_release(&revisions);
1840 free(options.reflog_action);
1841 free(options.head_name);
1842 strvec_clear(&options.git_am_opts);
1843 free(options.gpg_sign_opt);
1844 string_list_clear(&options.exec, 0);
1845 free(options.strategy);
1846 string_list_clear(&options.strategy_opts, 0);
1847 strbuf_release(&options.git_format_patch_opt);
1848 free(squash_onto_name);
1849 free(keep_base_onto_name);
1850 return !!ret;