Git 2.46-rc2
[git/gitster.git] / builtin / rebase.c
blobe3a8e74cfc25c89243397f62e3b09b8165c3ed6b
1 /*
2 * "git rebase" builtin command
4 * Copyright (c) 2018 Pratik Karki
5 */
7 #include "builtin.h"
8 #include "abspath.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "run-command.h"
13 #include "strvec.h"
14 #include "dir.h"
15 #include "refs.h"
16 #include "config.h"
17 #include "unpack-trees.h"
18 #include "lockfile.h"
19 #include "object-file.h"
20 #include "object-name.h"
21 #include "parse-options.h"
22 #include "path.h"
23 #include "commit.h"
24 #include "diff.h"
25 #include "wt-status.h"
26 #include "revision.h"
27 #include "commit-reach.h"
28 #include "rerere.h"
29 #include "branch.h"
30 #include "sequencer.h"
31 #include "rebase-interactive.h"
32 #include "reset.h"
33 #include "trace2.h"
34 #include "hook.h"
36 static char const * const builtin_rebase_usage[] = {
37 N_("git rebase [-i] [options] [--exec <cmd>] "
38 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
39 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
40 "--root [<branch>]"),
41 "git rebase --continue | --abort | --skip | --edit-todo",
42 NULL
45 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
46 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
47 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
48 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
50 enum rebase_type {
51 REBASE_UNSPECIFIED = -1,
52 REBASE_APPLY,
53 REBASE_MERGE
56 enum empty_type {
57 EMPTY_UNSPECIFIED = -1,
58 EMPTY_DROP,
59 EMPTY_KEEP,
60 EMPTY_STOP
63 enum action {
64 ACTION_NONE = 0,
65 ACTION_CONTINUE,
66 ACTION_SKIP,
67 ACTION_ABORT,
68 ACTION_QUIT,
69 ACTION_EDIT_TODO,
70 ACTION_SHOW_CURRENT_PATCH
73 static const char *action_names[] = {
74 "undefined",
75 "continue",
76 "skip",
77 "abort",
78 "quit",
79 "edit_todo",
80 "show_current_patch"
83 struct rebase_options {
84 enum rebase_type type;
85 enum empty_type empty;
86 char *default_backend;
87 const char *state_dir;
88 struct commit *upstream;
89 const char *upstream_name;
90 const char *upstream_arg;
91 char *head_name;
92 struct commit *orig_head;
93 struct commit *onto;
94 const char *onto_name;
95 const char *revisions;
96 const char *switch_to;
97 int root, root_with_onto;
98 struct object_id *squash_onto;
99 struct commit *restrict_revision;
100 int dont_finish_rebase;
101 enum {
102 REBASE_NO_QUIET = 1<<0,
103 REBASE_VERBOSE = 1<<1,
104 REBASE_DIFFSTAT = 1<<2,
105 REBASE_FORCE = 1<<3,
106 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
107 } flags;
108 struct strvec git_am_opts;
109 enum action action;
110 char *reflog_action;
111 int signoff;
112 int allow_rerere_autoupdate;
113 int keep_empty;
114 int autosquash;
115 char *gpg_sign_opt;
116 int autostash;
117 int committer_date_is_author_date;
118 int ignore_date;
119 struct string_list exec;
120 int allow_empty_message;
121 int rebase_merges, rebase_cousins;
122 char *strategy;
123 struct string_list strategy_opts;
124 struct strbuf git_format_patch_opt;
125 int reschedule_failed_exec;
126 int reapply_cherry_picks;
127 int fork_point;
128 int update_refs;
129 int config_autosquash;
130 int config_rebase_merges;
131 int config_update_refs;
134 #define REBASE_OPTIONS_INIT { \
135 .type = REBASE_UNSPECIFIED, \
136 .empty = EMPTY_UNSPECIFIED, \
137 .keep_empty = 1, \
138 .default_backend = xstrdup("merge"), \
139 .flags = REBASE_NO_QUIET, \
140 .git_am_opts = STRVEC_INIT, \
141 .exec = STRING_LIST_INIT_NODUP, \
142 .git_format_patch_opt = STRBUF_INIT, \
143 .fork_point = -1, \
144 .reapply_cherry_picks = -1, \
145 .allow_empty_message = 1, \
146 .autosquash = -1, \
147 .rebase_merges = -1, \
148 .config_rebase_merges = -1, \
149 .update_refs = -1, \
150 .config_update_refs = -1, \
151 .strategy_opts = STRING_LIST_INIT_NODUP,\
154 static void rebase_options_release(struct rebase_options *opts)
156 free(opts->default_backend);
157 free(opts->reflog_action);
158 free(opts->head_name);
159 strvec_clear(&opts->git_am_opts);
160 free(opts->gpg_sign_opt);
161 string_list_clear(&opts->exec, 0);
162 free(opts->strategy);
163 string_list_clear(&opts->strategy_opts, 0);
164 strbuf_release(&opts->git_format_patch_opt);
167 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
169 struct replay_opts replay = REPLAY_OPTS_INIT;
171 replay.action = REPLAY_INTERACTIVE_REBASE;
172 replay.strategy = NULL;
173 sequencer_init_config(&replay);
175 replay.signoff = opts->signoff;
176 replay.allow_ff = !(opts->flags & REBASE_FORCE);
177 if (opts->allow_rerere_autoupdate)
178 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
179 replay.allow_empty = 1;
180 replay.allow_empty_message = opts->allow_empty_message;
181 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
182 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
183 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
184 replay.verbose = opts->flags & REBASE_VERBOSE;
185 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
186 replay.committer_date_is_author_date =
187 opts->committer_date_is_author_date;
188 replay.ignore_date = opts->ignore_date;
189 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
190 replay.reflog_action = xstrdup(opts->reflog_action);
191 if (opts->strategy)
192 replay.strategy = xstrdup_or_null(opts->strategy);
193 else if (!replay.strategy && replay.default_strategy) {
194 replay.strategy = replay.default_strategy;
195 replay.default_strategy = NULL;
198 for (size_t i = 0; i < opts->strategy_opts.nr; i++)
199 strvec_push(&replay.xopts, opts->strategy_opts.items[i].string);
201 if (opts->squash_onto) {
202 oidcpy(&replay.squash_onto, opts->squash_onto);
203 replay.have_squash_onto = 1;
206 return replay;
209 static int edit_todo_file(unsigned flags, struct replay_opts *opts)
211 const char *todo_file = rebase_path_todo();
212 struct todo_list todo_list = TODO_LIST_INIT,
213 new_todo = TODO_LIST_INIT;
214 int res = 0;
216 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
217 return error_errno(_("could not read '%s'."), todo_file);
219 strbuf_stripspace(&todo_list.buf, comment_line_str);
220 res = edit_todo_list(the_repository, opts, &todo_list, &new_todo,
221 NULL, NULL, flags);
222 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
223 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
224 res = error_errno(_("could not write '%s'"), todo_file);
226 todo_list_release(&todo_list);
227 todo_list_release(&new_todo);
229 return res;
232 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
233 struct object_id *orig_head, char **revisions,
234 char **shortrevisions)
236 struct commit *base_rev = upstream ? upstream : onto;
237 const char *shorthead;
239 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
240 oid_to_hex(orig_head));
242 shorthead = repo_find_unique_abbrev(the_repository, orig_head,
243 DEFAULT_ABBREV);
245 if (upstream) {
246 const char *shortrev;
248 shortrev = repo_find_unique_abbrev(the_repository,
249 &base_rev->object.oid,
250 DEFAULT_ABBREV);
252 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
253 } else
254 *shortrevisions = xstrdup(shorthead);
256 return 0;
259 static int init_basic_state(struct replay_opts *opts, const char *head_name,
260 struct commit *onto,
261 const struct object_id *orig_head)
263 FILE *interactive;
265 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
266 return error_errno(_("could not create temporary %s"), merge_dir());
268 refs_delete_reflog(get_main_ref_store(the_repository), "REBASE_HEAD");
270 interactive = fopen(path_interactive(), "w");
271 if (!interactive)
272 return error_errno(_("could not mark as interactive"));
273 fclose(interactive);
275 return write_basic_state(opts, head_name, onto, orig_head);
278 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
280 int ret = -1;
281 char *revisions = NULL, *shortrevisions = NULL;
282 struct strvec make_script_args = STRVEC_INIT;
283 struct todo_list todo_list = TODO_LIST_INIT;
284 struct replay_opts replay = get_replay_opts(opts);
286 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
287 &revisions, &shortrevisions))
288 goto cleanup;
290 if (init_basic_state(&replay,
291 opts->head_name ? opts->head_name : "detached HEAD",
292 opts->onto, &opts->orig_head->object.oid))
293 goto cleanup;
295 if (!opts->upstream && opts->squash_onto)
296 write_file(path_squash_onto(), "%s\n",
297 oid_to_hex(opts->squash_onto));
299 strvec_pushl(&make_script_args, "", revisions, NULL);
300 if (opts->restrict_revision)
301 strvec_pushf(&make_script_args, "^%s",
302 oid_to_hex(&opts->restrict_revision->object.oid));
304 ret = sequencer_make_script(the_repository, &todo_list.buf,
305 make_script_args.nr, make_script_args.v,
306 flags);
308 if (ret)
309 error(_("could not generate todo list"));
310 else {
311 discard_index(the_repository->index);
312 if (todo_list_parse_insn_buffer(the_repository, &replay,
313 todo_list.buf.buf, &todo_list))
314 BUG("unusable todo list");
316 ret = complete_action(the_repository, &replay, flags,
317 shortrevisions, opts->onto_name, opts->onto,
318 &opts->orig_head->object.oid, &opts->exec,
319 opts->autosquash, opts->update_refs, &todo_list);
322 cleanup:
323 replay_opts_release(&replay);
324 free(revisions);
325 free(shortrevisions);
326 todo_list_release(&todo_list);
327 strvec_clear(&make_script_args);
329 return ret;
332 static int run_sequencer_rebase(struct rebase_options *opts)
334 unsigned flags = 0;
335 int abbreviate_commands = 0, ret = 0;
337 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
339 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
340 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
341 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
342 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
343 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
344 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
345 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
347 switch (opts->action) {
348 case ACTION_NONE: {
349 if (!opts->onto && !opts->upstream)
350 die(_("a base commit must be provided with --upstream or --onto"));
352 ret = do_interactive_rebase(opts, flags);
353 break;
355 case ACTION_SKIP: {
356 struct string_list merge_rr = STRING_LIST_INIT_DUP;
358 rerere_clear(the_repository, &merge_rr);
360 /* fallthrough */
361 case ACTION_CONTINUE: {
362 struct replay_opts replay_opts = get_replay_opts(opts);
364 ret = sequencer_continue(the_repository, &replay_opts);
365 replay_opts_release(&replay_opts);
366 break;
368 case ACTION_EDIT_TODO: {
369 struct replay_opts replay_opts = get_replay_opts(opts);
371 ret = edit_todo_file(flags, &replay_opts);
372 replay_opts_release(&replay_opts);
373 break;
375 case ACTION_SHOW_CURRENT_PATCH: {
376 struct child_process cmd = CHILD_PROCESS_INIT;
378 cmd.git_cmd = 1;
379 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
380 ret = run_command(&cmd);
382 break;
384 default:
385 BUG("invalid command '%d'", opts->action);
388 return ret;
391 static int is_merge(struct rebase_options *opts)
393 return opts->type == REBASE_MERGE;
396 static void imply_merge(struct rebase_options *opts, const char *option)
398 switch (opts->type) {
399 case REBASE_APPLY:
400 die(_("%s requires the merge backend"), option);
401 break;
402 case REBASE_MERGE:
403 break;
404 default:
405 opts->type = REBASE_MERGE; /* implied */
406 break;
410 /* Returns the filename prefixed by the state_dir */
411 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
413 static struct strbuf path = STRBUF_INIT;
414 static size_t prefix_len;
416 if (!prefix_len) {
417 strbuf_addf(&path, "%s/", opts->state_dir);
418 prefix_len = path.len;
421 strbuf_setlen(&path, prefix_len);
422 strbuf_addstr(&path, filename);
423 return path.buf;
426 /* Initialize the rebase options from the state directory. */
427 static int read_basic_state(struct rebase_options *opts)
429 struct strbuf head_name = STRBUF_INIT;
430 struct strbuf buf = STRBUF_INIT;
431 struct object_id oid;
433 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
434 READ_ONELINER_WARN_MISSING) ||
435 !read_oneliner(&buf, state_dir_path("onto", opts),
436 READ_ONELINER_WARN_MISSING))
437 return -1;
438 opts->head_name = starts_with(head_name.buf, "refs/") ?
439 xstrdup(head_name.buf) : NULL;
440 strbuf_release(&head_name);
441 if (get_oid_hex(buf.buf, &oid) ||
442 !(opts->onto = lookup_commit_object(the_repository, &oid)))
443 return error(_("invalid onto: '%s'"), buf.buf);
446 * We always write to orig-head, but interactive rebase used to write to
447 * head. Fall back to reading from head to cover for the case that the
448 * user upgraded git with an ongoing interactive rebase.
450 strbuf_reset(&buf);
451 if (file_exists(state_dir_path("orig-head", opts))) {
452 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
453 READ_ONELINER_WARN_MISSING))
454 return -1;
455 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
456 READ_ONELINER_WARN_MISSING))
457 return -1;
458 if (get_oid_hex(buf.buf, &oid) ||
459 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
460 return error(_("invalid orig-head: '%s'"), buf.buf);
462 if (file_exists(state_dir_path("quiet", opts)))
463 opts->flags &= ~REBASE_NO_QUIET;
464 else
465 opts->flags |= REBASE_NO_QUIET;
467 if (file_exists(state_dir_path("verbose", opts)))
468 opts->flags |= REBASE_VERBOSE;
470 if (file_exists(state_dir_path("signoff", opts))) {
471 opts->signoff = 1;
472 opts->flags |= REBASE_FORCE;
475 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
476 strbuf_reset(&buf);
477 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
478 READ_ONELINER_WARN_MISSING))
479 return -1;
480 if (!strcmp(buf.buf, "--rerere-autoupdate"))
481 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
482 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
483 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
484 else
485 warning(_("ignoring invalid allow_rerere_autoupdate: "
486 "'%s'"), buf.buf);
489 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
490 strbuf_reset(&buf);
491 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
492 READ_ONELINER_WARN_MISSING))
493 return -1;
494 free(opts->gpg_sign_opt);
495 opts->gpg_sign_opt = xstrdup(buf.buf);
498 strbuf_release(&buf);
500 return 0;
503 static int rebase_write_basic_state(struct rebase_options *opts)
505 write_file(state_dir_path("head-name", opts), "%s",
506 opts->head_name ? opts->head_name : "detached HEAD");
507 write_file(state_dir_path("onto", opts), "%s",
508 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
509 write_file(state_dir_path("orig-head", opts), "%s",
510 oid_to_hex(&opts->orig_head->object.oid));
511 if (!(opts->flags & REBASE_NO_QUIET))
512 write_file(state_dir_path("quiet", opts), "%s", "");
513 if (opts->flags & REBASE_VERBOSE)
514 write_file(state_dir_path("verbose", opts), "%s", "");
515 if (opts->allow_rerere_autoupdate > 0)
516 write_file(state_dir_path("allow_rerere_autoupdate", opts),
517 "-%s-rerere-autoupdate",
518 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
519 "" : "-no");
520 if (opts->gpg_sign_opt)
521 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
522 opts->gpg_sign_opt);
523 if (opts->signoff)
524 write_file(state_dir_path("signoff", opts), "--signoff");
526 return 0;
529 static int finish_rebase(struct rebase_options *opts)
531 struct strbuf dir = STRBUF_INIT;
532 int ret = 0;
534 refs_delete_ref(get_main_ref_store(the_repository), NULL,
535 "REBASE_HEAD", NULL, REF_NO_DEREF);
536 refs_delete_ref(get_main_ref_store(the_repository), NULL,
537 "AUTO_MERGE", NULL, REF_NO_DEREF);
538 apply_autostash(state_dir_path("autostash", opts));
540 * We ignore errors in 'git maintenance run --auto', since the
541 * user should see them.
543 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
544 if (opts->type == REBASE_MERGE) {
545 struct replay_opts replay = REPLAY_OPTS_INIT;
547 replay.action = REPLAY_INTERACTIVE_REBASE;
548 ret = sequencer_remove_state(&replay);
549 replay_opts_release(&replay);
550 } else {
551 strbuf_addstr(&dir, opts->state_dir);
552 if (remove_dir_recursively(&dir, 0))
553 ret = error(_("could not remove '%s'"),
554 opts->state_dir);
555 strbuf_release(&dir);
558 return ret;
561 static int move_to_original_branch(struct rebase_options *opts)
563 struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
564 struct reset_head_opts ropts = { 0 };
565 int ret;
567 if (!opts->head_name)
568 return 0; /* nothing to move back to */
570 if (!opts->onto)
571 BUG("move_to_original_branch without onto");
573 strbuf_addf(&branch_reflog, "%s (finish): %s onto %s",
574 opts->reflog_action,
575 opts->head_name, oid_to_hex(&opts->onto->object.oid));
576 strbuf_addf(&head_reflog, "%s (finish): returning to %s",
577 opts->reflog_action, opts->head_name);
578 ropts.branch = opts->head_name;
579 ropts.flags = RESET_HEAD_REFS_ONLY;
580 ropts.branch_msg = branch_reflog.buf;
581 ropts.head_msg = head_reflog.buf;
582 ret = reset_head(the_repository, &ropts);
584 strbuf_release(&branch_reflog);
585 strbuf_release(&head_reflog);
586 return ret;
589 static int run_am(struct rebase_options *opts)
591 struct child_process am = CHILD_PROCESS_INIT;
592 struct child_process format_patch = CHILD_PROCESS_INIT;
593 int status;
594 char *rebased_patches;
596 am.git_cmd = 1;
597 strvec_push(&am.args, "am");
598 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
599 opts->reflog_action);
600 if (opts->action == ACTION_CONTINUE) {
601 strvec_push(&am.args, "--resolved");
602 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
603 if (opts->gpg_sign_opt)
604 strvec_push(&am.args, opts->gpg_sign_opt);
605 status = run_command(&am);
606 if (status)
607 return status;
609 return move_to_original_branch(opts);
611 if (opts->action == ACTION_SKIP) {
612 strvec_push(&am.args, "--skip");
613 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
614 status = run_command(&am);
615 if (status)
616 return status;
618 return move_to_original_branch(opts);
620 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
621 strvec_push(&am.args, "--show-current-patch");
622 return run_command(&am);
625 rebased_patches = xstrdup(git_path("rebased-patches"));
626 format_patch.out = open(rebased_patches,
627 O_WRONLY | O_CREAT | O_TRUNC, 0666);
628 if (format_patch.out < 0) {
629 status = error_errno(_("could not open '%s' for writing"),
630 rebased_patches);
631 free(rebased_patches);
632 child_process_clear(&am);
633 return status;
636 format_patch.git_cmd = 1;
637 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
638 "--full-index", "--cherry-pick", "--right-only",
639 "--default-prefix", "--no-renames",
640 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
641 "--no-base", NULL);
642 if (opts->git_format_patch_opt.len)
643 strvec_split(&format_patch.args,
644 opts->git_format_patch_opt.buf);
645 strvec_pushf(&format_patch.args, "%s...%s",
646 oid_to_hex(opts->root ?
647 /* this is now equivalent to !opts->upstream */
648 &opts->onto->object.oid :
649 &opts->upstream->object.oid),
650 oid_to_hex(&opts->orig_head->object.oid));
651 if (opts->restrict_revision)
652 strvec_pushf(&format_patch.args, "^%s",
653 oid_to_hex(&opts->restrict_revision->object.oid));
655 status = run_command(&format_patch);
656 if (status) {
657 struct reset_head_opts ropts = { 0 };
658 unlink(rebased_patches);
659 free(rebased_patches);
660 child_process_clear(&am);
662 ropts.oid = &opts->orig_head->object.oid;
663 ropts.branch = opts->head_name;
664 ropts.default_reflog_action = opts->reflog_action;
665 reset_head(the_repository, &ropts);
666 error(_("\ngit encountered an error while preparing the "
667 "patches to replay\n"
668 "these revisions:\n"
669 "\n %s\n\n"
670 "As a result, git cannot rebase them."),
671 opts->revisions);
673 return status;
676 am.in = open(rebased_patches, O_RDONLY);
677 if (am.in < 0) {
678 status = error_errno(_("could not open '%s' for reading"),
679 rebased_patches);
680 free(rebased_patches);
681 child_process_clear(&am);
682 return status;
685 strvec_pushv(&am.args, opts->git_am_opts.v);
686 strvec_push(&am.args, "--rebasing");
687 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
688 strvec_push(&am.args, "--patch-format=mboxrd");
689 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
690 strvec_push(&am.args, "--rerere-autoupdate");
691 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
692 strvec_push(&am.args, "--no-rerere-autoupdate");
693 if (opts->gpg_sign_opt)
694 strvec_push(&am.args, opts->gpg_sign_opt);
695 status = run_command(&am);
696 unlink(rebased_patches);
697 free(rebased_patches);
699 if (!status) {
700 return move_to_original_branch(opts);
703 if (is_directory(opts->state_dir))
704 rebase_write_basic_state(opts);
706 return status;
709 static int run_specific_rebase(struct rebase_options *opts)
711 int status;
713 if (opts->type == REBASE_MERGE) {
714 /* Run sequencer-based rebase */
715 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT))
716 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
717 if (opts->gpg_sign_opt) {
718 /* remove the leading "-S" */
719 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
720 free(opts->gpg_sign_opt);
721 opts->gpg_sign_opt = tmp;
724 status = run_sequencer_rebase(opts);
725 } else if (opts->type == REBASE_APPLY)
726 status = run_am(opts);
727 else
728 BUG("Unhandled rebase type %d", opts->type);
730 if (opts->dont_finish_rebase)
731 ; /* do nothing */
732 else if (opts->type == REBASE_MERGE)
733 ; /* merge backend cleans up after itself */
734 else if (status == 0) {
735 if (!file_exists(state_dir_path("stopped-sha", opts)))
736 finish_rebase(opts);
737 } else if (status == 2) {
738 struct strbuf dir = STRBUF_INIT;
740 apply_autostash(state_dir_path("autostash", opts));
741 strbuf_addstr(&dir, opts->state_dir);
742 remove_dir_recursively(&dir, 0);
743 strbuf_release(&dir);
744 die("Nothing to do");
747 return status ? -1 : 0;
750 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
752 if (!strcmp("no-rebase-cousins", value))
753 options->rebase_cousins = 0;
754 else if (!strcmp("rebase-cousins", value))
755 options->rebase_cousins = 1;
756 else
757 die(_("Unknown rebase-merges mode: %s"), value);
760 static int rebase_config(const char *var, const char *value,
761 const struct config_context *ctx, void *data)
763 struct rebase_options *opts = data;
765 if (!strcmp(var, "rebase.stat")) {
766 if (git_config_bool(var, value))
767 opts->flags |= REBASE_DIFFSTAT;
768 else
769 opts->flags &= ~REBASE_DIFFSTAT;
770 return 0;
773 if (!strcmp(var, "rebase.autosquash")) {
774 opts->config_autosquash = git_config_bool(var, value);
775 return 0;
778 if (!strcmp(var, "commit.gpgsign")) {
779 free(opts->gpg_sign_opt);
780 opts->gpg_sign_opt = git_config_bool(var, value) ?
781 xstrdup("-S") : NULL;
782 return 0;
785 if (!strcmp(var, "rebase.autostash")) {
786 opts->autostash = git_config_bool(var, value);
787 return 0;
790 if (!strcmp(var, "rebase.rebasemerges")) {
791 opts->config_rebase_merges = git_parse_maybe_bool(value);
792 if (opts->config_rebase_merges < 0) {
793 opts->config_rebase_merges = 1;
794 parse_rebase_merges_value(opts, value);
795 } else {
796 opts->rebase_cousins = 0;
798 return 0;
801 if (!strcmp(var, "rebase.updaterefs")) {
802 opts->config_update_refs = git_config_bool(var, value);
803 return 0;
806 if (!strcmp(var, "rebase.reschedulefailedexec")) {
807 opts->reschedule_failed_exec = git_config_bool(var, value);
808 return 0;
811 if (!strcmp(var, "rebase.forkpoint")) {
812 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
813 return 0;
816 if (!strcmp(var, "rebase.backend")) {
817 FREE_AND_NULL(opts->default_backend);
818 return git_config_string(&opts->default_backend, var, value);
821 return git_default_config(var, value, ctx, data);
824 static int checkout_up_to_date(struct rebase_options *options)
826 struct strbuf buf = STRBUF_INIT;
827 struct reset_head_opts ropts = { 0 };
828 int ret = 0;
830 strbuf_addf(&buf, "%s: checkout %s",
831 options->reflog_action, options->switch_to);
832 ropts.oid = &options->orig_head->object.oid;
833 ropts.branch = options->head_name;
834 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
835 if (!ropts.branch)
836 ropts.flags |= RESET_HEAD_DETACH;
837 ropts.head_msg = buf.buf;
838 if (reset_head(the_repository, &ropts) < 0)
839 ret = error(_("could not switch to %s"), options->switch_to);
840 strbuf_release(&buf);
842 return ret;
846 * Determines whether the commits in from..to are linear, i.e. contain
847 * no merge commits. This function *expects* `from` to be an ancestor of
848 * `to`.
850 static int is_linear_history(struct commit *from, struct commit *to)
852 while (to && to != from) {
853 repo_parse_commit(the_repository, to);
854 if (!to->parents)
855 return 1;
856 if (to->parents->next)
857 return 0;
858 to = to->parents->item;
860 return 1;
863 static int can_fast_forward(struct commit *onto, struct commit *upstream,
864 struct commit *restrict_revision,
865 struct commit *head, struct object_id *branch_base)
867 struct commit_list *merge_bases = NULL;
868 int res = 0;
870 if (is_null_oid(branch_base))
871 goto done; /* fill_branch_base() found multiple merge bases */
873 if (!oideq(branch_base, &onto->object.oid))
874 goto done;
876 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
877 goto done;
879 if (!upstream)
880 goto done;
882 if (repo_get_merge_bases(the_repository, upstream, head, &merge_bases) < 0)
883 exit(128);
884 if (!merge_bases || merge_bases->next)
885 goto done;
887 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
888 goto done;
890 res = 1;
892 done:
893 free_commit_list(merge_bases);
894 return res && is_linear_history(onto, head);
897 static void fill_branch_base(struct rebase_options *options,
898 struct object_id *branch_base)
900 struct commit_list *merge_bases = NULL;
902 if (repo_get_merge_bases(the_repository, options->onto,
903 options->orig_head, &merge_bases) < 0)
904 exit(128);
905 if (!merge_bases || merge_bases->next)
906 oidcpy(branch_base, null_oid());
907 else
908 oidcpy(branch_base, &merge_bases->item->object.oid);
910 free_commit_list(merge_bases);
913 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
915 struct rebase_options *opts = opt->value;
917 BUG_ON_OPT_NEG(unset);
918 BUG_ON_OPT_ARG(arg);
920 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
921 die(_("apply options and merge options cannot be used together"));
923 opts->type = REBASE_APPLY;
925 return 0;
928 /* -i followed by -m is still -i */
929 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
931 struct rebase_options *opts = opt->value;
933 BUG_ON_OPT_NEG(unset);
934 BUG_ON_OPT_ARG(arg);
936 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
937 die(_("apply options and merge options cannot be used together"));
939 opts->type = REBASE_MERGE;
941 return 0;
944 /* -i followed by -r is still explicitly interactive, but -r alone is not */
945 static int parse_opt_interactive(const struct option *opt, const char *arg,
946 int unset)
948 struct rebase_options *opts = opt->value;
950 BUG_ON_OPT_NEG(unset);
951 BUG_ON_OPT_ARG(arg);
953 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
954 die(_("apply options and merge options cannot be used together"));
956 opts->type = REBASE_MERGE;
957 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
959 return 0;
962 static enum empty_type parse_empty_value(const char *value)
964 if (!strcasecmp(value, "drop"))
965 return EMPTY_DROP;
966 else if (!strcasecmp(value, "keep"))
967 return EMPTY_KEEP;
968 else if (!strcasecmp(value, "stop"))
969 return EMPTY_STOP;
970 else if (!strcasecmp(value, "ask")) {
971 warning(_("--empty=ask is deprecated; use '--empty=stop' instead."));
972 return EMPTY_STOP;
975 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"stop\"."), value);
978 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
979 int unset)
981 struct rebase_options *opts = opt->value;
983 BUG_ON_OPT_ARG(arg);
985 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
986 opts->keep_empty = !unset;
987 return 0;
990 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
992 struct rebase_options *options = opt->value;
993 enum empty_type value = parse_empty_value(arg);
995 BUG_ON_OPT_NEG(unset);
997 options->empty = value;
998 return 0;
1001 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
1003 struct rebase_options *options = opt->value;
1005 options->rebase_merges = !unset;
1006 options->rebase_cousins = 0;
1008 if (arg) {
1009 if (!*arg) {
1010 warning(_("--rebase-merges with an empty string "
1011 "argument is deprecated and will stop "
1012 "working in a future version of Git. Use "
1013 "--rebase-merges without an argument "
1014 "instead, which does the same thing."));
1015 return 0;
1017 parse_rebase_merges_value(options, arg);
1020 return 0;
1023 static void NORETURN error_on_missing_default_upstream(void)
1025 struct branch *current_branch = branch_get(NULL);
1027 printf(_("%s\n"
1028 "Please specify which branch you want to rebase against.\n"
1029 "See git-rebase(1) for details.\n"
1030 "\n"
1031 " git rebase '<branch>'\n"
1032 "\n"),
1033 current_branch ? _("There is no tracking information for "
1034 "the current branch.") :
1035 _("You are not currently on a branch."));
1037 if (current_branch) {
1038 const char *remote = current_branch->remote_name;
1040 if (!remote)
1041 remote = _("<remote>");
1043 printf(_("If you wish to set tracking information for this "
1044 "branch you can do so with:\n"
1045 "\n"
1046 " git branch --set-upstream-to=%s/<branch> %s\n"
1047 "\n"),
1048 remote, current_branch->name);
1050 exit(1);
1053 static int check_exec_cmd(const char *cmd)
1055 if (strchr(cmd, '\n'))
1056 return error(_("exec commands cannot contain newlines"));
1058 /* Does the command consist purely of whitespace? */
1059 if (!cmd[strspn(cmd, " \t\r\f\v")])
1060 return error(_("empty exec command"));
1062 return 0;
1065 int cmd_rebase(int argc, const char **argv, const char *prefix)
1067 struct rebase_options options = REBASE_OPTIONS_INIT;
1068 const char *branch_name;
1069 const char *strategy_opt = NULL;
1070 int ret, flags, total_argc, in_progress = 0;
1071 int keep_base = 0;
1072 int ok_to_skip_pre_rebase = 0;
1073 struct strbuf msg = STRBUF_INIT;
1074 struct strbuf revisions = STRBUF_INIT;
1075 struct strbuf buf = STRBUF_INIT;
1076 struct object_id branch_base;
1077 int ignore_whitespace = 0;
1078 const char *gpg_sign = NULL;
1079 struct object_id squash_onto;
1080 char *squash_onto_name = NULL;
1081 char *keep_base_onto_name = NULL;
1082 int reschedule_failed_exec = -1;
1083 int allow_preemptive_ff = 1;
1084 int preserve_merges_selected = 0;
1085 struct reset_head_opts ropts = { 0 };
1086 struct option builtin_rebase_options[] = {
1087 OPT_STRING(0, "onto", &options.onto_name,
1088 N_("revision"),
1089 N_("rebase onto given branch instead of upstream")),
1090 OPT_BOOL(0, "keep-base", &keep_base,
1091 N_("use the merge-base of upstream and branch as the current base")),
1092 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1093 N_("allow pre-rebase hook to run")),
1094 OPT_NEGBIT('q', "quiet", &options.flags,
1095 N_("be quiet. implies --no-stat"),
1096 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1097 OPT_BIT('v', "verbose", &options.flags,
1098 N_("display a diffstat of what changed upstream"),
1099 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1100 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1101 N_("do not show diffstat of what changed upstream"),
1102 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1103 OPT_BOOL(0, "signoff", &options.signoff,
1104 N_("add a Signed-off-by trailer to each commit")),
1105 OPT_BOOL(0, "committer-date-is-author-date",
1106 &options.committer_date_is_author_date,
1107 N_("make committer date match author date")),
1108 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1109 N_("ignore author date and use current date")),
1110 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1111 N_("synonym of --reset-author-date")),
1112 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1113 N_("passed to 'git apply'"), 0),
1114 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1115 N_("ignore changes in whitespace")),
1116 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1117 N_("action"), N_("passed to 'git apply'"), 0),
1118 OPT_BIT('f', "force-rebase", &options.flags,
1119 N_("cherry-pick all commits, even if unchanged"),
1120 REBASE_FORCE),
1121 OPT_BIT(0, "no-ff", &options.flags,
1122 N_("cherry-pick all commits, even if unchanged"),
1123 REBASE_FORCE),
1124 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1125 ACTION_CONTINUE),
1126 OPT_CMDMODE(0, "skip", &options.action,
1127 N_("skip current patch and continue"), ACTION_SKIP),
1128 OPT_CMDMODE(0, "abort", &options.action,
1129 N_("abort and check out the original branch"),
1130 ACTION_ABORT),
1131 OPT_CMDMODE(0, "quit", &options.action,
1132 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1133 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1134 "during an interactive rebase"), ACTION_EDIT_TODO),
1135 OPT_CMDMODE(0, "show-current-patch", &options.action,
1136 N_("show the patch file being applied or merged"),
1137 ACTION_SHOW_CURRENT_PATCH),
1138 OPT_CALLBACK_F(0, "apply", &options, NULL,
1139 N_("use apply strategies to rebase"),
1140 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1141 parse_opt_am),
1142 OPT_CALLBACK_F('m', "merge", &options, NULL,
1143 N_("use merging strategies to rebase"),
1144 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1145 parse_opt_merge),
1146 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1147 N_("let the user edit the list of commits to rebase"),
1148 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1149 parse_opt_interactive),
1150 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1151 N_("(REMOVED) was: try to recreate merges "
1152 "instead of ignoring them"),
1153 1, PARSE_OPT_HIDDEN),
1154 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1155 OPT_CALLBACK_F(0, "empty", &options, "(drop|keep|stop)",
1156 N_("how to handle commits that become empty"),
1157 PARSE_OPT_NONEG, parse_opt_empty),
1158 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1159 N_("keep commits which start empty"),
1160 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1161 parse_opt_keep_empty),
1162 OPT_BOOL(0, "autosquash", &options.autosquash,
1163 N_("move commits that begin with "
1164 "squash!/fixup! under -i")),
1165 OPT_BOOL(0, "update-refs", &options.update_refs,
1166 N_("update branches that point to commits "
1167 "that are being rebased")),
1168 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1169 N_("GPG-sign commits"),
1170 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1171 OPT_AUTOSTASH(&options.autostash),
1172 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1173 N_("add exec lines after each commit of the "
1174 "editable list")),
1175 OPT_BOOL_F(0, "allow-empty-message",
1176 &options.allow_empty_message,
1177 N_("allow rebasing commits with empty messages"),
1178 PARSE_OPT_HIDDEN),
1179 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1180 N_("try to rebase merges instead of skipping them"),
1181 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1182 OPT_BOOL(0, "fork-point", &options.fork_point,
1183 N_("use 'merge-base --fork-point' to refine upstream")),
1184 OPT_STRING('s', "strategy", &strategy_opt,
1185 N_("strategy"), N_("use the given merge strategy")),
1186 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1187 N_("option"),
1188 N_("pass the argument through to the merge "
1189 "strategy")),
1190 OPT_BOOL(0, "root", &options.root,
1191 N_("rebase all reachable commits up to the root(s)")),
1192 OPT_BOOL(0, "reschedule-failed-exec",
1193 &reschedule_failed_exec,
1194 N_("automatically re-schedule any `exec` that fails")),
1195 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1196 N_("apply all changes, even those already present upstream")),
1197 OPT_END(),
1199 int i;
1201 if (argc == 2 && !strcmp(argv[1], "-h"))
1202 usage_with_options(builtin_rebase_usage,
1203 builtin_rebase_options);
1205 prepare_repo_settings(the_repository);
1206 the_repository->settings.command_requires_full_index = 0;
1208 git_config(rebase_config, &options);
1209 /* options.gpg_sign_opt will be either "-S" or NULL */
1210 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1211 FREE_AND_NULL(options.gpg_sign_opt);
1213 strbuf_reset(&buf);
1214 strbuf_addf(&buf, "%s/applying", apply_dir());
1215 if(file_exists(buf.buf))
1216 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1218 if (is_directory(apply_dir())) {
1219 options.type = REBASE_APPLY;
1220 options.state_dir = apply_dir();
1221 } else if (is_directory(merge_dir())) {
1222 strbuf_reset(&buf);
1223 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1224 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1225 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1226 "Use `git rebase --abort` to terminate current rebase.\n"
1227 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1228 } else {
1229 strbuf_reset(&buf);
1230 strbuf_addf(&buf, "%s/interactive", merge_dir());
1231 options.type = REBASE_MERGE;
1232 if (file_exists(buf.buf))
1233 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1235 options.state_dir = merge_dir();
1238 if (options.type != REBASE_UNSPECIFIED)
1239 in_progress = 1;
1241 total_argc = argc;
1242 argc = parse_options(argc, argv, prefix,
1243 builtin_rebase_options,
1244 builtin_rebase_usage, 0);
1246 if (preserve_merges_selected)
1247 die(_("--preserve-merges was replaced by --rebase-merges\n"
1248 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1249 "which is no longer supported; use 'merges' instead"));
1251 if (options.action != ACTION_NONE && total_argc != 2) {
1252 usage_with_options(builtin_rebase_usage,
1253 builtin_rebase_options);
1256 if (argc > 2)
1257 usage_with_options(builtin_rebase_usage,
1258 builtin_rebase_options);
1260 if (keep_base) {
1261 if (options.onto_name)
1262 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1263 if (options.root)
1264 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1266 * --keep-base defaults to --no-fork-point to keep the
1267 * base the same.
1269 if (options.fork_point < 0)
1270 options.fork_point = 0;
1272 if (options.root && options.fork_point > 0)
1273 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1275 if (options.action != ACTION_NONE && !in_progress)
1276 die(_("no rebase in progress"));
1278 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1279 die(_("The --edit-todo action can only be used during "
1280 "interactive rebase."));
1282 if (trace2_is_enabled()) {
1283 if (is_merge(&options))
1284 trace2_cmd_mode("interactive");
1285 else if (options.exec.nr)
1286 trace2_cmd_mode("interactive-exec");
1287 else
1288 trace2_cmd_mode(action_names[options.action]);
1291 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1292 options.reflog_action =
1293 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1295 switch (options.action) {
1296 case ACTION_CONTINUE: {
1297 struct object_id head;
1298 struct lock_file lock_file = LOCK_INIT;
1299 int fd;
1301 /* Sanity check */
1302 if (repo_get_oid(the_repository, "HEAD", &head))
1303 die(_("Cannot read HEAD"));
1305 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1306 if (repo_read_index(the_repository) < 0)
1307 die(_("could not read index"));
1308 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1309 NULL);
1310 if (0 <= fd)
1311 repo_update_index_if_able(the_repository, &lock_file);
1312 rollback_lock_file(&lock_file);
1314 if (has_unstaged_changes(the_repository, 1)) {
1315 puts(_("You must edit all merge conflicts and then\n"
1316 "mark them as resolved using git add"));
1317 exit(1);
1319 if (read_basic_state(&options))
1320 exit(1);
1321 goto run_rebase;
1323 case ACTION_SKIP: {
1324 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1326 rerere_clear(the_repository, &merge_rr);
1327 string_list_clear(&merge_rr, 1);
1328 ropts.flags = RESET_HEAD_HARD;
1329 if (reset_head(the_repository, &ropts) < 0)
1330 die(_("could not discard worktree changes"));
1331 remove_branch_state(the_repository, 0);
1332 if (read_basic_state(&options))
1333 exit(1);
1334 goto run_rebase;
1336 case ACTION_ABORT: {
1337 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1338 struct strbuf head_msg = STRBUF_INIT;
1340 rerere_clear(the_repository, &merge_rr);
1341 string_list_clear(&merge_rr, 1);
1343 if (read_basic_state(&options))
1344 exit(1);
1346 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1347 options.reflog_action,
1348 options.head_name ? options.head_name
1349 : oid_to_hex(&options.orig_head->object.oid));
1350 ropts.oid = &options.orig_head->object.oid;
1351 ropts.head_msg = head_msg.buf;
1352 ropts.branch = options.head_name;
1353 ropts.flags = RESET_HEAD_HARD;
1354 if (reset_head(the_repository, &ropts) < 0)
1355 die(_("could not move back to %s"),
1356 oid_to_hex(&options.orig_head->object.oid));
1357 strbuf_release(&head_msg);
1358 remove_branch_state(the_repository, 0);
1359 ret = finish_rebase(&options);
1360 goto cleanup;
1362 case ACTION_QUIT: {
1363 save_autostash(state_dir_path("autostash", &options));
1364 if (options.type == REBASE_MERGE) {
1365 struct replay_opts replay = REPLAY_OPTS_INIT;
1367 replay.action = REPLAY_INTERACTIVE_REBASE;
1368 ret = sequencer_remove_state(&replay);
1369 replay_opts_release(&replay);
1370 } else {
1371 strbuf_reset(&buf);
1372 strbuf_addstr(&buf, options.state_dir);
1373 ret = remove_dir_recursively(&buf, 0);
1374 if (ret)
1375 error(_("could not remove '%s'"),
1376 options.state_dir);
1378 goto cleanup;
1380 case ACTION_EDIT_TODO:
1381 options.dont_finish_rebase = 1;
1382 goto run_rebase;
1383 case ACTION_SHOW_CURRENT_PATCH:
1384 options.dont_finish_rebase = 1;
1385 goto run_rebase;
1386 case ACTION_NONE:
1387 break;
1388 default:
1389 BUG("action: %d", options.action);
1392 /* Make sure no rebase is in progress */
1393 if (in_progress) {
1394 const char *last_slash = strrchr(options.state_dir, '/');
1395 const char *state_dir_base =
1396 last_slash ? last_slash + 1 : options.state_dir;
1397 const char *cmd_live_rebase =
1398 "git rebase (--continue | --abort | --skip)";
1399 strbuf_reset(&buf);
1400 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1401 die(_("It seems that there is already a %s directory, and\n"
1402 "I wonder if you are in the middle of another rebase. "
1403 "If that is the\n"
1404 "case, please try\n\t%s\n"
1405 "If that is not the case, please\n\t%s\n"
1406 "and run me again. I am stopping in case you still "
1407 "have something\n"
1408 "valuable there.\n"),
1409 state_dir_base, cmd_live_rebase, buf.buf);
1412 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1413 (options.action != ACTION_NONE) ||
1414 (options.exec.nr > 0) ||
1415 options.autosquash == 1) {
1416 allow_preemptive_ff = 0;
1418 if (options.committer_date_is_author_date || options.ignore_date)
1419 options.flags |= REBASE_FORCE;
1421 for (i = 0; i < options.git_am_opts.nr; i++) {
1422 const char *option = options.git_am_opts.v[i], *p;
1423 if (!strcmp(option, "--whitespace=fix") ||
1424 !strcmp(option, "--whitespace=strip"))
1425 allow_preemptive_ff = 0;
1426 else if (skip_prefix(option, "-C", &p)) {
1427 while (*p)
1428 if (!isdigit(*(p++)))
1429 die(_("switch `C' expects a "
1430 "numerical value"));
1431 } else if (skip_prefix(option, "--whitespace=", &p)) {
1432 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1433 strcmp(p, "error") && strcmp(p, "error-all"))
1434 die("Invalid whitespace option: '%s'", p);
1438 for (i = 0; i < options.exec.nr; i++)
1439 if (check_exec_cmd(options.exec.items[i].string))
1440 exit(1);
1442 if (!(options.flags & REBASE_NO_QUIET))
1443 strvec_push(&options.git_am_opts, "-q");
1445 if (options.empty != EMPTY_UNSPECIFIED)
1446 imply_merge(&options, "--empty");
1448 if (options.reapply_cherry_picks < 0)
1450 * We default to --no-reapply-cherry-picks unless
1451 * --keep-base is given; when --keep-base is given, we want
1452 * to default to --reapply-cherry-picks.
1454 options.reapply_cherry_picks = keep_base;
1455 else if (!keep_base)
1457 * The apply backend always searches for and drops cherry
1458 * picks. This is often not wanted with --keep-base, so
1459 * --keep-base allows --reapply-cherry-picks to be
1460 * simulated by altering the upstream such that
1461 * cherry-picks cannot be detected and thus all commits are
1462 * reapplied. Thus, --[no-]reapply-cherry-picks is
1463 * supported when --keep-base is specified, but not when
1464 * --keep-base is left out.
1466 imply_merge(&options, options.reapply_cherry_picks ?
1467 "--reapply-cherry-picks" :
1468 "--no-reapply-cherry-picks");
1470 if (gpg_sign)
1471 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1473 if (options.exec.nr)
1474 imply_merge(&options, "--exec");
1476 if (options.type == REBASE_APPLY) {
1477 if (ignore_whitespace)
1478 strvec_push(&options.git_am_opts,
1479 "--ignore-whitespace");
1480 if (options.committer_date_is_author_date)
1481 strvec_push(&options.git_am_opts,
1482 "--committer-date-is-author-date");
1483 if (options.ignore_date)
1484 strvec_push(&options.git_am_opts, "--ignore-date");
1485 } else {
1486 /* REBASE_MERGE */
1487 if (ignore_whitespace) {
1488 string_list_append(&options.strategy_opts,
1489 "ignore-space-change");
1493 if (strategy_opt)
1494 options.strategy = xstrdup(strategy_opt);
1495 else if (options.strategy_opts.nr && !options.strategy)
1496 options.strategy = xstrdup("ort");
1497 if (options.strategy)
1498 imply_merge(&options, "--strategy");
1500 if (options.root && !options.onto_name)
1501 imply_merge(&options, "--root without --onto");
1503 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1504 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1506 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1507 /* all am options except -q are compatible only with --apply */
1508 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1509 if (strcmp(options.git_am_opts.v[i], "-q"))
1510 break;
1512 if (i >= 0 || options.type == REBASE_APPLY) {
1513 if (is_merge(&options))
1514 die(_("apply options and merge options "
1515 "cannot be used together"));
1516 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1517 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1518 else if (options.update_refs == -1 && options.config_update_refs == 1)
1519 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1520 else
1521 options.type = REBASE_APPLY;
1525 if (options.update_refs == 1)
1526 imply_merge(&options, "--update-refs");
1527 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1528 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1530 if (options.rebase_merges == 1)
1531 imply_merge(&options, "--rebase-merges");
1532 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1533 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1535 if (options.autosquash == 1) {
1536 imply_merge(&options, "--autosquash");
1537 } else if (options.autosquash == -1) {
1538 options.autosquash =
1539 options.config_autosquash &&
1540 (options.flags & REBASE_INTERACTIVE_EXPLICIT);
1543 if (options.type == REBASE_UNSPECIFIED) {
1544 if (!strcmp(options.default_backend, "merge"))
1545 options.type = REBASE_MERGE;
1546 else if (!strcmp(options.default_backend, "apply"))
1547 options.type = REBASE_APPLY;
1548 else
1549 die(_("Unknown rebase backend: %s"),
1550 options.default_backend);
1553 if (options.type == REBASE_MERGE &&
1554 !options.strategy &&
1555 getenv("GIT_TEST_MERGE_ALGORITHM"))
1556 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1558 switch (options.type) {
1559 case REBASE_MERGE:
1560 options.state_dir = merge_dir();
1561 break;
1562 case REBASE_APPLY:
1563 options.state_dir = apply_dir();
1564 break;
1565 default:
1566 BUG("options.type was just set above; should be unreachable.");
1569 if (options.empty == EMPTY_UNSPECIFIED) {
1570 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1571 options.empty = EMPTY_STOP;
1572 else if (options.exec.nr > 0)
1573 options.empty = EMPTY_KEEP;
1574 else
1575 options.empty = EMPTY_DROP;
1577 if (reschedule_failed_exec > 0 && !is_merge(&options))
1578 die(_("--reschedule-failed-exec requires "
1579 "--exec or --interactive"));
1580 if (reschedule_failed_exec >= 0)
1581 options.reschedule_failed_exec = reschedule_failed_exec;
1583 if (options.signoff) {
1584 strvec_push(&options.git_am_opts, "--signoff");
1585 options.flags |= REBASE_FORCE;
1588 if (!options.root) {
1589 if (argc < 1) {
1590 struct branch *branch;
1592 branch = branch_get(NULL);
1593 options.upstream_name = branch_get_upstream(branch,
1594 NULL);
1595 if (!options.upstream_name)
1596 error_on_missing_default_upstream();
1597 if (options.fork_point < 0)
1598 options.fork_point = 1;
1599 } else {
1600 options.upstream_name = argv[0];
1601 argc--;
1602 argv++;
1603 if (!strcmp(options.upstream_name, "-"))
1604 options.upstream_name = "@{-1}";
1606 options.upstream =
1607 lookup_commit_reference_by_name(options.upstream_name);
1608 if (!options.upstream)
1609 die(_("invalid upstream '%s'"), options.upstream_name);
1610 options.upstream_arg = options.upstream_name;
1611 } else {
1612 if (!options.onto_name) {
1613 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1614 &squash_onto, NULL, NULL) < 0)
1615 die(_("Could not create new root commit"));
1616 options.squash_onto = &squash_onto;
1617 options.onto_name = squash_onto_name =
1618 xstrdup(oid_to_hex(&squash_onto));
1619 } else
1620 options.root_with_onto = 1;
1622 options.upstream_name = NULL;
1623 options.upstream = NULL;
1624 if (argc > 1)
1625 usage_with_options(builtin_rebase_usage,
1626 builtin_rebase_options);
1627 options.upstream_arg = "--root";
1631 * If the branch to rebase is given, that is the branch we will rebase
1632 * branch_name -- branch/commit being rebased, or
1633 * HEAD (already detached)
1634 * orig_head -- commit object name of tip of the branch before rebasing
1635 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1637 if (argc == 1) {
1638 /* Is it "rebase other branchname" or "rebase other commit"? */
1639 struct object_id branch_oid;
1640 branch_name = argv[0];
1641 options.switch_to = argv[0];
1643 /* Is it a local branch? */
1644 strbuf_reset(&buf);
1645 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1646 if (!refs_read_ref(get_main_ref_store(the_repository), buf.buf, &branch_oid)) {
1647 die_if_checked_out(buf.buf, 1);
1648 options.head_name = xstrdup(buf.buf);
1649 options.orig_head =
1650 lookup_commit_object(the_repository,
1651 &branch_oid);
1652 /* If not is it a valid ref (branch or commit)? */
1653 } else {
1654 options.orig_head =
1655 lookup_commit_reference_by_name(branch_name);
1656 options.head_name = NULL;
1658 if (!options.orig_head)
1659 die(_("no such branch/commit '%s'"), branch_name);
1660 } else if (argc == 0) {
1661 /* Do not need to switch branches, we are already on it. */
1662 options.head_name =
1663 xstrdup_or_null(refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL,
1664 &flags));
1665 if (!options.head_name)
1666 die(_("No such ref: %s"), "HEAD");
1667 if (flags & REF_ISSYMREF) {
1668 if (!skip_prefix(options.head_name,
1669 "refs/heads/", &branch_name))
1670 branch_name = options.head_name;
1672 } else {
1673 FREE_AND_NULL(options.head_name);
1674 branch_name = "HEAD";
1676 options.orig_head = lookup_commit_reference_by_name("HEAD");
1677 if (!options.orig_head)
1678 die(_("Could not resolve HEAD to a commit"));
1679 } else
1680 BUG("unexpected number of arguments left to parse");
1682 /* Make sure the branch to rebase onto is valid. */
1683 if (keep_base) {
1684 strbuf_reset(&buf);
1685 strbuf_addstr(&buf, options.upstream_name);
1686 strbuf_addstr(&buf, "...");
1687 strbuf_addstr(&buf, branch_name);
1688 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1689 } else if (!options.onto_name)
1690 options.onto_name = options.upstream_name;
1691 if (strstr(options.onto_name, "...")) {
1692 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1693 if (keep_base)
1694 die(_("'%s': need exactly one merge base with branch"),
1695 options.upstream_name);
1696 else
1697 die(_("'%s': need exactly one merge base"),
1698 options.onto_name);
1700 options.onto = lookup_commit_or_die(&branch_base,
1701 options.onto_name);
1702 } else {
1703 options.onto =
1704 lookup_commit_reference_by_name(options.onto_name);
1705 if (!options.onto)
1706 die(_("Does not point to a valid commit '%s'"),
1707 options.onto_name);
1708 fill_branch_base(&options, &branch_base);
1711 if (keep_base && options.reapply_cherry_picks)
1712 options.upstream = options.onto;
1714 if (options.fork_point > 0)
1715 options.restrict_revision =
1716 get_fork_point(options.upstream_name, options.orig_head);
1718 if (repo_read_index(the_repository) < 0)
1719 die(_("could not read index"));
1721 if (options.autostash)
1722 create_autostash(the_repository,
1723 state_dir_path("autostash", &options));
1726 if (require_clean_work_tree(the_repository, "rebase",
1727 _("Please commit or stash them."), 1, 1)) {
1728 ret = -1;
1729 goto cleanup;
1733 * Now we are rebasing commits upstream..orig_head (or with --root,
1734 * everything leading up to orig_head) on top of onto.
1738 * Check if we are already based on onto with linear history,
1739 * in which case we could fast-forward without replacing the commits
1740 * with new commits recreated by replaying their changes.
1742 if (allow_preemptive_ff &&
1743 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1744 options.orig_head, &branch_base)) {
1745 int flag;
1747 if (!(options.flags & REBASE_FORCE)) {
1748 /* Lazily switch to the target branch if needed... */
1749 if (options.switch_to) {
1750 ret = checkout_up_to_date(&options);
1751 if (ret)
1752 goto cleanup;
1755 if (!(options.flags & REBASE_NO_QUIET))
1756 ; /* be quiet */
1757 else if (!strcmp(branch_name, "HEAD") &&
1758 refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL, &flag))
1759 puts(_("HEAD is up to date."));
1760 else
1761 printf(_("Current branch %s is up to date.\n"),
1762 branch_name);
1763 ret = finish_rebase(&options);
1764 goto cleanup;
1765 } else if (!(options.flags & REBASE_NO_QUIET))
1766 ; /* be quiet */
1767 else if (!strcmp(branch_name, "HEAD") &&
1768 refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL, &flag))
1769 puts(_("HEAD is up to date, rebase forced."));
1770 else
1771 printf(_("Current branch %s is up to date, rebase "
1772 "forced.\n"), branch_name);
1775 /* If a hook exists, give it a chance to interrupt*/
1776 if (!ok_to_skip_pre_rebase &&
1777 run_hooks_l("pre-rebase", options.upstream_arg,
1778 argc ? argv[0] : NULL, NULL))
1779 die(_("The pre-rebase hook refused to rebase."));
1781 if (options.flags & REBASE_DIFFSTAT) {
1782 struct diff_options opts;
1784 if (options.flags & REBASE_VERBOSE) {
1785 if (is_null_oid(&branch_base))
1786 printf(_("Changes to %s:\n"),
1787 oid_to_hex(&options.onto->object.oid));
1788 else
1789 printf(_("Changes from %s to %s:\n"),
1790 oid_to_hex(&branch_base),
1791 oid_to_hex(&options.onto->object.oid));
1794 /* We want color (if set), but no pager */
1795 repo_diff_setup(the_repository, &opts);
1796 init_diffstat_widths(&opts);
1797 opts.output_format |=
1798 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1799 opts.detect_rename = DIFF_DETECT_RENAME;
1800 diff_setup_done(&opts);
1801 diff_tree_oid(is_null_oid(&branch_base) ?
1802 the_hash_algo->empty_tree : &branch_base,
1803 &options.onto->object.oid, "", &opts);
1804 diffcore_std(&opts);
1805 diff_flush(&opts);
1808 if (is_merge(&options))
1809 goto run_rebase;
1811 /* Detach HEAD and reset the tree */
1812 if (options.flags & REBASE_NO_QUIET)
1813 printf(_("First, rewinding head to replay your work on top of "
1814 "it...\n"));
1816 strbuf_addf(&msg, "%s (start): checkout %s",
1817 options.reflog_action, options.onto_name);
1818 ropts.oid = &options.onto->object.oid;
1819 ropts.orig_head = &options.orig_head->object.oid,
1820 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1821 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1822 ropts.head_msg = msg.buf;
1823 ropts.default_reflog_action = options.reflog_action;
1824 if (reset_head(the_repository, &ropts))
1825 die(_("Could not detach HEAD"));
1826 strbuf_release(&msg);
1829 * If the onto is a proper descendant of the tip of the branch, then
1830 * we just fast-forwarded.
1832 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1833 printf(_("Fast-forwarded %s to %s.\n"),
1834 branch_name, options.onto_name);
1835 move_to_original_branch(&options);
1836 ret = finish_rebase(&options);
1837 goto cleanup;
1840 strbuf_addf(&revisions, "%s..%s",
1841 options.root ? oid_to_hex(&options.onto->object.oid) :
1842 (options.restrict_revision ?
1843 oid_to_hex(&options.restrict_revision->object.oid) :
1844 oid_to_hex(&options.upstream->object.oid)),
1845 oid_to_hex(&options.orig_head->object.oid));
1847 options.revisions = revisions.buf;
1849 run_rebase:
1850 ret = run_specific_rebase(&options);
1852 cleanup:
1853 strbuf_release(&buf);
1854 strbuf_release(&revisions);
1855 rebase_options_release(&options);
1856 free(squash_onto_name);
1857 free(keep_base_onto_name);
1858 return !!ret;