The ninth batch
[alt-git.git] / builtin / rebase.c
blob1b3f68d9b0f1ab18439c625361342a71587c10c4
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 "exec-cmd.h"
15 #include "strvec.h"
16 #include "dir.h"
17 #include "packfile.h"
18 #include "refs.h"
19 #include "quote.h"
20 #include "config.h"
21 #include "cache-tree.h"
22 #include "unpack-trees.h"
23 #include "lockfile.h"
24 #include "object-file.h"
25 #include "object-name.h"
26 #include "parse-options.h"
27 #include "path.h"
28 #include "commit.h"
29 #include "diff.h"
30 #include "wt-status.h"
31 #include "revision.h"
32 #include "commit-reach.h"
33 #include "rerere.h"
34 #include "branch.h"
35 #include "sequencer.h"
36 #include "rebase-interactive.h"
37 #include "reset.h"
38 #include "trace2.h"
39 #include "hook.h"
40 #include "wrapper.h"
42 static char const * const builtin_rebase_usage[] = {
43 N_("git rebase [-i] [options] [--exec <cmd>] "
44 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
45 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
46 "--root [<branch>]"),
47 "git rebase --continue | --abort | --skip | --edit-todo",
48 NULL
51 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
52 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
53 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
54 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
56 enum rebase_type {
57 REBASE_UNSPECIFIED = -1,
58 REBASE_APPLY,
59 REBASE_MERGE
62 enum empty_type {
63 EMPTY_UNSPECIFIED = -1,
64 EMPTY_DROP,
65 EMPTY_KEEP,
66 EMPTY_ASK
69 enum action {
70 ACTION_NONE = 0,
71 ACTION_CONTINUE,
72 ACTION_SKIP,
73 ACTION_ABORT,
74 ACTION_QUIT,
75 ACTION_EDIT_TODO,
76 ACTION_SHOW_CURRENT_PATCH
79 static const char *action_names[] = {
80 "undefined",
81 "continue",
82 "skip",
83 "abort",
84 "quit",
85 "edit_todo",
86 "show_current_patch"
89 struct rebase_options {
90 enum rebase_type type;
91 enum empty_type empty;
92 const char *default_backend;
93 const char *state_dir;
94 struct commit *upstream;
95 const char *upstream_name;
96 const char *upstream_arg;
97 char *head_name;
98 struct commit *orig_head;
99 struct commit *onto;
100 const char *onto_name;
101 const char *revisions;
102 const char *switch_to;
103 int root, root_with_onto;
104 struct object_id *squash_onto;
105 struct commit *restrict_revision;
106 int dont_finish_rebase;
107 enum {
108 REBASE_NO_QUIET = 1<<0,
109 REBASE_VERBOSE = 1<<1,
110 REBASE_DIFFSTAT = 1<<2,
111 REBASE_FORCE = 1<<3,
112 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
113 } flags;
114 struct strvec git_am_opts;
115 enum action action;
116 char *reflog_action;
117 int signoff;
118 int allow_rerere_autoupdate;
119 int keep_empty;
120 int autosquash;
121 char *gpg_sign_opt;
122 int autostash;
123 int committer_date_is_author_date;
124 int ignore_date;
125 struct string_list exec;
126 int allow_empty_message;
127 int rebase_merges, rebase_cousins;
128 char *strategy;
129 struct string_list strategy_opts;
130 struct strbuf git_format_patch_opt;
131 int reschedule_failed_exec;
132 int reapply_cherry_picks;
133 int fork_point;
134 int update_refs;
135 int config_autosquash;
136 int config_rebase_merges;
137 int config_update_refs;
140 #define REBASE_OPTIONS_INIT { \
141 .type = REBASE_UNSPECIFIED, \
142 .empty = EMPTY_UNSPECIFIED, \
143 .keep_empty = 1, \
144 .default_backend = "merge", \
145 .flags = REBASE_NO_QUIET, \
146 .git_am_opts = STRVEC_INIT, \
147 .exec = STRING_LIST_INIT_NODUP, \
148 .git_format_patch_opt = STRBUF_INIT, \
149 .fork_point = -1, \
150 .reapply_cherry_picks = -1, \
151 .allow_empty_message = 1, \
152 .autosquash = -1, \
153 .config_autosquash = -1, \
154 .rebase_merges = -1, \
155 .config_rebase_merges = -1, \
156 .update_refs = -1, \
157 .config_update_refs = -1, \
158 .strategy_opts = STRING_LIST_INIT_NODUP,\
161 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
163 struct replay_opts replay = REPLAY_OPTS_INIT;
165 replay.action = REPLAY_INTERACTIVE_REBASE;
166 replay.strategy = NULL;
167 sequencer_init_config(&replay);
169 replay.signoff = opts->signoff;
170 replay.allow_ff = !(opts->flags & REBASE_FORCE);
171 if (opts->allow_rerere_autoupdate)
172 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
173 replay.allow_empty = 1;
174 replay.allow_empty_message = opts->allow_empty_message;
175 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
176 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
177 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
178 replay.verbose = opts->flags & REBASE_VERBOSE;
179 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
180 replay.committer_date_is_author_date =
181 opts->committer_date_is_author_date;
182 replay.ignore_date = opts->ignore_date;
183 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
184 replay.reflog_action = xstrdup(opts->reflog_action);
185 if (opts->strategy)
186 replay.strategy = xstrdup_or_null(opts->strategy);
187 else if (!replay.strategy && replay.default_strategy) {
188 replay.strategy = replay.default_strategy;
189 replay.default_strategy = NULL;
192 for (size_t i = 0; i < opts->strategy_opts.nr; i++)
193 strvec_push(&replay.xopts, opts->strategy_opts.items[i].string);
195 if (opts->squash_onto) {
196 oidcpy(&replay.squash_onto, opts->squash_onto);
197 replay.have_squash_onto = 1;
200 return replay;
203 static int edit_todo_file(unsigned flags)
205 const char *todo_file = rebase_path_todo();
206 struct todo_list todo_list = TODO_LIST_INIT,
207 new_todo = TODO_LIST_INIT;
208 int res = 0;
210 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
211 return error_errno(_("could not read '%s'."), todo_file);
213 strbuf_stripspace(&todo_list.buf, comment_line_char);
214 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
215 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
216 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
217 res = error_errno(_("could not write '%s'"), todo_file);
219 todo_list_release(&todo_list);
220 todo_list_release(&new_todo);
222 return res;
225 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
226 struct object_id *orig_head, char **revisions,
227 char **shortrevisions)
229 struct commit *base_rev = upstream ? upstream : onto;
230 const char *shorthead;
232 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
233 oid_to_hex(orig_head));
235 shorthead = repo_find_unique_abbrev(the_repository, orig_head,
236 DEFAULT_ABBREV);
238 if (upstream) {
239 const char *shortrev;
241 shortrev = repo_find_unique_abbrev(the_repository,
242 &base_rev->object.oid,
243 DEFAULT_ABBREV);
245 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
246 } else
247 *shortrevisions = xstrdup(shorthead);
249 return 0;
252 static int init_basic_state(struct replay_opts *opts, const char *head_name,
253 struct commit *onto,
254 const struct object_id *orig_head)
256 FILE *interactive;
258 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
259 return error_errno(_("could not create temporary %s"), merge_dir());
261 delete_reflog("REBASE_HEAD");
263 interactive = fopen(path_interactive(), "w");
264 if (!interactive)
265 return error_errno(_("could not mark as interactive"));
266 fclose(interactive);
268 return write_basic_state(opts, head_name, onto, orig_head);
271 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
273 int ret = -1;
274 char *revisions = NULL, *shortrevisions = NULL;
275 struct strvec make_script_args = STRVEC_INIT;
276 struct todo_list todo_list = TODO_LIST_INIT;
277 struct replay_opts replay = get_replay_opts(opts);
279 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
280 &revisions, &shortrevisions))
281 goto cleanup;
283 if (init_basic_state(&replay,
284 opts->head_name ? opts->head_name : "detached HEAD",
285 opts->onto, &opts->orig_head->object.oid))
286 goto cleanup;
288 if (!opts->upstream && opts->squash_onto)
289 write_file(path_squash_onto(), "%s\n",
290 oid_to_hex(opts->squash_onto));
292 strvec_pushl(&make_script_args, "", revisions, NULL);
293 if (opts->restrict_revision)
294 strvec_pushf(&make_script_args, "^%s",
295 oid_to_hex(&opts->restrict_revision->object.oid));
297 ret = sequencer_make_script(the_repository, &todo_list.buf,
298 make_script_args.nr, make_script_args.v,
299 flags);
301 if (ret)
302 error(_("could not generate todo list"));
303 else {
304 discard_index(&the_index);
305 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
306 &todo_list))
307 BUG("unusable todo list");
309 ret = complete_action(the_repository, &replay, flags,
310 shortrevisions, opts->onto_name, opts->onto,
311 &opts->orig_head->object.oid, &opts->exec,
312 opts->autosquash, opts->update_refs, &todo_list);
315 cleanup:
316 replay_opts_release(&replay);
317 free(revisions);
318 free(shortrevisions);
319 todo_list_release(&todo_list);
320 strvec_clear(&make_script_args);
322 return ret;
325 static int run_sequencer_rebase(struct rebase_options *opts)
327 unsigned flags = 0;
328 int abbreviate_commands = 0, ret = 0;
330 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
332 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
333 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
334 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
335 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
336 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
337 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
338 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
340 switch (opts->action) {
341 case ACTION_NONE: {
342 if (!opts->onto && !opts->upstream)
343 die(_("a base commit must be provided with --upstream or --onto"));
345 ret = do_interactive_rebase(opts, flags);
346 break;
348 case ACTION_SKIP: {
349 struct string_list merge_rr = STRING_LIST_INIT_DUP;
351 rerere_clear(the_repository, &merge_rr);
353 /* fallthrough */
354 case ACTION_CONTINUE: {
355 struct replay_opts replay_opts = get_replay_opts(opts);
357 ret = sequencer_continue(the_repository, &replay_opts);
358 replay_opts_release(&replay_opts);
359 break;
361 case ACTION_EDIT_TODO:
362 ret = edit_todo_file(flags);
363 break;
364 case ACTION_SHOW_CURRENT_PATCH: {
365 struct child_process cmd = CHILD_PROCESS_INIT;
367 cmd.git_cmd = 1;
368 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
369 ret = run_command(&cmd);
371 break;
373 default:
374 BUG("invalid command '%d'", opts->action);
377 return ret;
380 static void imply_merge(struct rebase_options *opts, const char *option);
381 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
382 int unset)
384 struct rebase_options *opts = opt->value;
386 BUG_ON_OPT_ARG(arg);
388 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
389 opts->keep_empty = !unset;
390 opts->type = REBASE_MERGE;
391 return 0;
394 static int is_merge(struct rebase_options *opts)
396 return opts->type == REBASE_MERGE;
399 static void imply_merge(struct rebase_options *opts, const char *option)
401 switch (opts->type) {
402 case REBASE_APPLY:
403 die(_("%s requires the merge backend"), option);
404 break;
405 case REBASE_MERGE:
406 break;
407 default:
408 opts->type = REBASE_MERGE; /* implied */
409 break;
413 /* Returns the filename prefixed by the state_dir */
414 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
416 static struct strbuf path = STRBUF_INIT;
417 static size_t prefix_len;
419 if (!prefix_len) {
420 strbuf_addf(&path, "%s/", opts->state_dir);
421 prefix_len = path.len;
424 strbuf_setlen(&path, prefix_len);
425 strbuf_addstr(&path, filename);
426 return path.buf;
429 /* Initialize the rebase options from the state directory. */
430 static int read_basic_state(struct rebase_options *opts)
432 struct strbuf head_name = STRBUF_INIT;
433 struct strbuf buf = STRBUF_INIT;
434 struct object_id oid;
436 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
437 READ_ONELINER_WARN_MISSING) ||
438 !read_oneliner(&buf, state_dir_path("onto", opts),
439 READ_ONELINER_WARN_MISSING))
440 return -1;
441 opts->head_name = starts_with(head_name.buf, "refs/") ?
442 xstrdup(head_name.buf) : NULL;
443 strbuf_release(&head_name);
444 if (get_oid_hex(buf.buf, &oid) ||
445 !(opts->onto = lookup_commit_object(the_repository, &oid)))
446 return error(_("invalid onto: '%s'"), buf.buf);
449 * We always write to orig-head, but interactive rebase used to write to
450 * head. Fall back to reading from head to cover for the case that the
451 * user upgraded git with an ongoing interactive rebase.
453 strbuf_reset(&buf);
454 if (file_exists(state_dir_path("orig-head", opts))) {
455 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
456 READ_ONELINER_WARN_MISSING))
457 return -1;
458 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
459 READ_ONELINER_WARN_MISSING))
460 return -1;
461 if (get_oid_hex(buf.buf, &oid) ||
462 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
463 return error(_("invalid orig-head: '%s'"), buf.buf);
465 if (file_exists(state_dir_path("quiet", opts)))
466 opts->flags &= ~REBASE_NO_QUIET;
467 else
468 opts->flags |= REBASE_NO_QUIET;
470 if (file_exists(state_dir_path("verbose", opts)))
471 opts->flags |= REBASE_VERBOSE;
473 if (file_exists(state_dir_path("signoff", opts))) {
474 opts->signoff = 1;
475 opts->flags |= REBASE_FORCE;
478 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
479 strbuf_reset(&buf);
480 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
481 READ_ONELINER_WARN_MISSING))
482 return -1;
483 if (!strcmp(buf.buf, "--rerere-autoupdate"))
484 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
485 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
486 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
487 else
488 warning(_("ignoring invalid allow_rerere_autoupdate: "
489 "'%s'"), buf.buf);
492 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
493 strbuf_reset(&buf);
494 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
495 READ_ONELINER_WARN_MISSING))
496 return -1;
497 free(opts->gpg_sign_opt);
498 opts->gpg_sign_opt = xstrdup(buf.buf);
501 strbuf_release(&buf);
503 return 0;
506 static int rebase_write_basic_state(struct rebase_options *opts)
508 write_file(state_dir_path("head-name", opts), "%s",
509 opts->head_name ? opts->head_name : "detached HEAD");
510 write_file(state_dir_path("onto", opts), "%s",
511 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
512 write_file(state_dir_path("orig-head", opts), "%s",
513 oid_to_hex(&opts->orig_head->object.oid));
514 if (!(opts->flags & REBASE_NO_QUIET))
515 write_file(state_dir_path("quiet", opts), "%s", "");
516 if (opts->flags & REBASE_VERBOSE)
517 write_file(state_dir_path("verbose", opts), "%s", "");
518 if (opts->allow_rerere_autoupdate > 0)
519 write_file(state_dir_path("allow_rerere_autoupdate", opts),
520 "-%s-rerere-autoupdate",
521 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
522 "" : "-no");
523 if (opts->gpg_sign_opt)
524 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
525 opts->gpg_sign_opt);
526 if (opts->signoff)
527 write_file(state_dir_path("signoff", opts), "--signoff");
529 return 0;
532 static int finish_rebase(struct rebase_options *opts)
534 struct strbuf dir = STRBUF_INIT;
535 int ret = 0;
537 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
538 unlink(git_path_auto_merge(the_repository));
539 apply_autostash(state_dir_path("autostash", opts));
541 * We ignore errors in 'git maintenance run --auto', since the
542 * user should see them.
544 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
545 if (opts->type == REBASE_MERGE) {
546 struct replay_opts replay = REPLAY_OPTS_INIT;
548 replay.action = REPLAY_INTERACTIVE_REBASE;
549 ret = sequencer_remove_state(&replay);
550 replay_opts_release(&replay);
551 } else {
552 strbuf_addstr(&dir, opts->state_dir);
553 if (remove_dir_recursively(&dir, 0))
554 ret = error(_("could not remove '%s'"),
555 opts->state_dir);
556 strbuf_release(&dir);
559 return ret;
562 static int move_to_original_branch(struct rebase_options *opts)
564 struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
565 struct reset_head_opts ropts = { 0 };
566 int ret;
568 if (!opts->head_name)
569 return 0; /* nothing to move back to */
571 if (!opts->onto)
572 BUG("move_to_original_branch without onto");
574 strbuf_addf(&branch_reflog, "%s (finish): %s onto %s",
575 opts->reflog_action,
576 opts->head_name, oid_to_hex(&opts->onto->object.oid));
577 strbuf_addf(&head_reflog, "%s (finish): returning to %s",
578 opts->reflog_action, opts->head_name);
579 ropts.branch = opts->head_name;
580 ropts.flags = RESET_HEAD_REFS_ONLY;
581 ropts.branch_msg = branch_reflog.buf;
582 ropts.head_msg = head_reflog.buf;
583 ret = reset_head(the_repository, &ropts);
585 strbuf_release(&branch_reflog);
586 strbuf_release(&head_reflog);
587 return ret;
590 static const char *resolvemsg =
591 N_("Resolve all conflicts manually, mark them as resolved with\n"
592 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
593 "You can instead skip this commit: run \"git rebase --skip\".\n"
594 "To abort and get back to the state before \"git rebase\", run "
595 "\"git rebase --abort\".");
597 static int run_am(struct rebase_options *opts)
599 struct child_process am = CHILD_PROCESS_INIT;
600 struct child_process format_patch = CHILD_PROCESS_INIT;
601 struct strbuf revisions = STRBUF_INIT;
602 int status;
603 char *rebased_patches;
605 am.git_cmd = 1;
606 strvec_push(&am.args, "am");
607 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
608 opts->reflog_action);
609 if (opts->action == ACTION_CONTINUE) {
610 strvec_push(&am.args, "--resolved");
611 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
612 if (opts->gpg_sign_opt)
613 strvec_push(&am.args, opts->gpg_sign_opt);
614 status = run_command(&am);
615 if (status)
616 return status;
618 return move_to_original_branch(opts);
620 if (opts->action == ACTION_SKIP) {
621 strvec_push(&am.args, "--skip");
622 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
623 status = run_command(&am);
624 if (status)
625 return status;
627 return move_to_original_branch(opts);
629 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
630 strvec_push(&am.args, "--show-current-patch");
631 return run_command(&am);
634 strbuf_addf(&revisions, "%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));
641 rebased_patches = xstrdup(git_path("rebased-patches"));
642 format_patch.out = open(rebased_patches,
643 O_WRONLY | O_CREAT | O_TRUNC, 0666);
644 if (format_patch.out < 0) {
645 status = error_errno(_("could not open '%s' for writing"),
646 rebased_patches);
647 free(rebased_patches);
648 strvec_clear(&am.args);
649 return status;
652 format_patch.git_cmd = 1;
653 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
654 "--full-index", "--cherry-pick", "--right-only",
655 "--default-prefix", "--no-renames",
656 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
657 "--no-base", NULL);
658 if (opts->git_format_patch_opt.len)
659 strvec_split(&format_patch.args,
660 opts->git_format_patch_opt.buf);
661 strvec_push(&format_patch.args, revisions.buf);
662 if (opts->restrict_revision)
663 strvec_pushf(&format_patch.args, "^%s",
664 oid_to_hex(&opts->restrict_revision->object.oid));
666 status = run_command(&format_patch);
667 if (status) {
668 struct reset_head_opts ropts = { 0 };
669 unlink(rebased_patches);
670 free(rebased_patches);
671 strvec_clear(&am.args);
673 ropts.oid = &opts->orig_head->object.oid;
674 ropts.branch = opts->head_name;
675 ropts.default_reflog_action = opts->reflog_action;
676 reset_head(the_repository, &ropts);
677 error(_("\ngit encountered an error while preparing the "
678 "patches to replay\n"
679 "these revisions:\n"
680 "\n %s\n\n"
681 "As a result, git cannot rebase them."),
682 opts->revisions);
684 strbuf_release(&revisions);
685 return status;
687 strbuf_release(&revisions);
689 am.in = open(rebased_patches, O_RDONLY);
690 if (am.in < 0) {
691 status = error_errno(_("could not open '%s' for reading"),
692 rebased_patches);
693 free(rebased_patches);
694 strvec_clear(&am.args);
695 return status;
698 strvec_pushv(&am.args, opts->git_am_opts.v);
699 strvec_push(&am.args, "--rebasing");
700 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
701 strvec_push(&am.args, "--patch-format=mboxrd");
702 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
703 strvec_push(&am.args, "--rerere-autoupdate");
704 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
705 strvec_push(&am.args, "--no-rerere-autoupdate");
706 if (opts->gpg_sign_opt)
707 strvec_push(&am.args, opts->gpg_sign_opt);
708 status = run_command(&am);
709 unlink(rebased_patches);
710 free(rebased_patches);
712 if (!status) {
713 return move_to_original_branch(opts);
716 if (is_directory(opts->state_dir))
717 rebase_write_basic_state(opts);
719 return status;
722 static int run_specific_rebase(struct rebase_options *opts)
724 int status;
726 if (opts->type == REBASE_MERGE) {
727 /* Run sequencer-based rebase */
728 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
729 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
730 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
731 opts->autosquash = 0;
733 if (opts->gpg_sign_opt) {
734 /* remove the leading "-S" */
735 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
736 free(opts->gpg_sign_opt);
737 opts->gpg_sign_opt = tmp;
740 status = run_sequencer_rebase(opts);
741 } else if (opts->type == REBASE_APPLY)
742 status = run_am(opts);
743 else
744 BUG("Unhandled rebase type %d", opts->type);
746 if (opts->dont_finish_rebase)
747 ; /* do nothing */
748 else if (opts->type == REBASE_MERGE)
749 ; /* merge backend cleans up after itself */
750 else if (status == 0) {
751 if (!file_exists(state_dir_path("stopped-sha", opts)))
752 finish_rebase(opts);
753 } else if (status == 2) {
754 struct strbuf dir = STRBUF_INIT;
756 apply_autostash(state_dir_path("autostash", opts));
757 strbuf_addstr(&dir, opts->state_dir);
758 remove_dir_recursively(&dir, 0);
759 strbuf_release(&dir);
760 die("Nothing to do");
763 return status ? -1 : 0;
766 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
768 if (!strcmp("no-rebase-cousins", value))
769 options->rebase_cousins = 0;
770 else if (!strcmp("rebase-cousins", value))
771 options->rebase_cousins = 1;
772 else
773 die(_("Unknown rebase-merges mode: %s"), value);
776 static int rebase_config(const char *var, const char *value,
777 const struct config_context *ctx, void *data)
779 struct rebase_options *opts = data;
781 if (!strcmp(var, "rebase.stat")) {
782 if (git_config_bool(var, value))
783 opts->flags |= REBASE_DIFFSTAT;
784 else
785 opts->flags &= ~REBASE_DIFFSTAT;
786 return 0;
789 if (!strcmp(var, "rebase.autosquash")) {
790 opts->config_autosquash = git_config_bool(var, value);
791 return 0;
794 if (!strcmp(var, "commit.gpgsign")) {
795 free(opts->gpg_sign_opt);
796 opts->gpg_sign_opt = git_config_bool(var, value) ?
797 xstrdup("-S") : NULL;
798 return 0;
801 if (!strcmp(var, "rebase.autostash")) {
802 opts->autostash = git_config_bool(var, value);
803 return 0;
806 if (!strcmp(var, "rebase.rebasemerges")) {
807 opts->config_rebase_merges = git_parse_maybe_bool(value);
808 if (opts->config_rebase_merges < 0) {
809 opts->config_rebase_merges = 1;
810 parse_rebase_merges_value(opts, value);
811 } else {
812 opts->rebase_cousins = 0;
814 return 0;
817 if (!strcmp(var, "rebase.updaterefs")) {
818 opts->config_update_refs = git_config_bool(var, value);
819 return 0;
822 if (!strcmp(var, "rebase.reschedulefailedexec")) {
823 opts->reschedule_failed_exec = git_config_bool(var, value);
824 return 0;
827 if (!strcmp(var, "rebase.forkpoint")) {
828 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
829 return 0;
832 if (!strcmp(var, "rebase.backend")) {
833 return git_config_string(&opts->default_backend, var, value);
836 return git_default_config(var, value, ctx, data);
839 static int checkout_up_to_date(struct rebase_options *options)
841 struct strbuf buf = STRBUF_INIT;
842 struct reset_head_opts ropts = { 0 };
843 int ret = 0;
845 strbuf_addf(&buf, "%s: checkout %s",
846 options->reflog_action, options->switch_to);
847 ropts.oid = &options->orig_head->object.oid;
848 ropts.branch = options->head_name;
849 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
850 if (!ropts.branch)
851 ropts.flags |= RESET_HEAD_DETACH;
852 ropts.head_msg = buf.buf;
853 if (reset_head(the_repository, &ropts) < 0)
854 ret = error(_("could not switch to %s"), options->switch_to);
855 strbuf_release(&buf);
857 return ret;
861 * Determines whether the commits in from..to are linear, i.e. contain
862 * no merge commits. This function *expects* `from` to be an ancestor of
863 * `to`.
865 static int is_linear_history(struct commit *from, struct commit *to)
867 while (to && to != from) {
868 repo_parse_commit(the_repository, to);
869 if (!to->parents)
870 return 1;
871 if (to->parents->next)
872 return 0;
873 to = to->parents->item;
875 return 1;
878 static int can_fast_forward(struct commit *onto, struct commit *upstream,
879 struct commit *restrict_revision,
880 struct commit *head, struct object_id *branch_base)
882 struct commit_list *merge_bases = NULL;
883 int res = 0;
885 if (is_null_oid(branch_base))
886 goto done; /* fill_branch_base() found multiple merge bases */
888 if (!oideq(branch_base, &onto->object.oid))
889 goto done;
891 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
892 goto done;
894 if (!upstream)
895 goto done;
897 merge_bases = repo_get_merge_bases(the_repository, upstream, head);
898 if (!merge_bases || merge_bases->next)
899 goto done;
901 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
902 goto done;
904 res = 1;
906 done:
907 free_commit_list(merge_bases);
908 return res && is_linear_history(onto, head);
911 static void fill_branch_base(struct rebase_options *options,
912 struct object_id *branch_base)
914 struct commit_list *merge_bases = NULL;
916 merge_bases = repo_get_merge_bases(the_repository, options->onto,
917 options->orig_head);
918 if (!merge_bases || merge_bases->next)
919 oidcpy(branch_base, null_oid());
920 else
921 oidcpy(branch_base, &merge_bases->item->object.oid);
923 free_commit_list(merge_bases);
926 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
928 struct rebase_options *opts = opt->value;
930 BUG_ON_OPT_NEG(unset);
931 BUG_ON_OPT_ARG(arg);
933 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
934 die(_("apply options and merge options cannot be used together"));
936 opts->type = REBASE_APPLY;
938 return 0;
941 /* -i followed by -m is still -i */
942 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
944 struct rebase_options *opts = opt->value;
946 BUG_ON_OPT_NEG(unset);
947 BUG_ON_OPT_ARG(arg);
949 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
950 die(_("apply options and merge options cannot be used together"));
952 opts->type = REBASE_MERGE;
954 return 0;
957 /* -i followed by -r is still explicitly interactive, but -r alone is not */
958 static int parse_opt_interactive(const struct option *opt, const char *arg,
959 int unset)
961 struct rebase_options *opts = opt->value;
963 BUG_ON_OPT_NEG(unset);
964 BUG_ON_OPT_ARG(arg);
966 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
967 die(_("apply options and merge options cannot be used together"));
969 opts->type = REBASE_MERGE;
970 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
972 return 0;
975 static enum empty_type parse_empty_value(const char *value)
977 if (!strcasecmp(value, "drop"))
978 return EMPTY_DROP;
979 else if (!strcasecmp(value, "keep"))
980 return EMPTY_KEEP;
981 else if (!strcasecmp(value, "ask"))
982 return EMPTY_ASK;
984 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
987 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
989 struct rebase_options *options = opt->value;
990 enum empty_type value = parse_empty_value(arg);
992 BUG_ON_OPT_NEG(unset);
994 options->empty = value;
995 return 0;
998 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
1000 struct rebase_options *options = opt->value;
1002 options->rebase_merges = !unset;
1003 options->rebase_cousins = 0;
1005 if (arg) {
1006 if (!*arg) {
1007 warning(_("--rebase-merges with an empty string "
1008 "argument is deprecated and will stop "
1009 "working in a future version of Git. Use "
1010 "--rebase-merges without an argument "
1011 "instead, which does the same thing."));
1012 return 0;
1014 parse_rebase_merges_value(options, arg);
1017 return 0;
1020 static void NORETURN error_on_missing_default_upstream(void)
1022 struct branch *current_branch = branch_get(NULL);
1024 printf(_("%s\n"
1025 "Please specify which branch you want to rebase against.\n"
1026 "See git-rebase(1) for details.\n"
1027 "\n"
1028 " git rebase '<branch>'\n"
1029 "\n"),
1030 current_branch ? _("There is no tracking information for "
1031 "the current branch.") :
1032 _("You are not currently on a branch."));
1034 if (current_branch) {
1035 const char *remote = current_branch->remote_name;
1037 if (!remote)
1038 remote = _("<remote>");
1040 printf(_("If you wish to set tracking information for this "
1041 "branch you can do so with:\n"
1042 "\n"
1043 " git branch --set-upstream-to=%s/<branch> %s\n"
1044 "\n"),
1045 remote, current_branch->name);
1047 exit(1);
1050 static int check_exec_cmd(const char *cmd)
1052 if (strchr(cmd, '\n'))
1053 return error(_("exec commands cannot contain newlines"));
1055 /* Does the command consist purely of whitespace? */
1056 if (!cmd[strspn(cmd, " \t\r\f\v")])
1057 return error(_("empty exec command"));
1059 return 0;
1062 int cmd_rebase(int argc, const char **argv, const char *prefix)
1064 struct rebase_options options = REBASE_OPTIONS_INIT;
1065 const char *branch_name;
1066 int ret, flags, total_argc, in_progress = 0;
1067 int keep_base = 0;
1068 int ok_to_skip_pre_rebase = 0;
1069 struct strbuf msg = STRBUF_INIT;
1070 struct strbuf revisions = STRBUF_INIT;
1071 struct strbuf buf = STRBUF_INIT;
1072 struct object_id branch_base;
1073 int ignore_whitespace = 0;
1074 const char *gpg_sign = NULL;
1075 struct object_id squash_onto;
1076 char *squash_onto_name = NULL;
1077 char *keep_base_onto_name = NULL;
1078 int reschedule_failed_exec = -1;
1079 int allow_preemptive_ff = 1;
1080 int preserve_merges_selected = 0;
1081 struct reset_head_opts ropts = { 0 };
1082 struct option builtin_rebase_options[] = {
1083 OPT_STRING(0, "onto", &options.onto_name,
1084 N_("revision"),
1085 N_("rebase onto given branch instead of upstream")),
1086 OPT_BOOL(0, "keep-base", &keep_base,
1087 N_("use the merge-base of upstream and branch as the current base")),
1088 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1089 N_("allow pre-rebase hook to run")),
1090 OPT_NEGBIT('q', "quiet", &options.flags,
1091 N_("be quiet. implies --no-stat"),
1092 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1093 OPT_BIT('v', "verbose", &options.flags,
1094 N_("display a diffstat of what changed upstream"),
1095 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1096 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1097 N_("do not show diffstat of what changed upstream"),
1098 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1099 OPT_BOOL(0, "signoff", &options.signoff,
1100 N_("add a Signed-off-by trailer to each commit")),
1101 OPT_BOOL(0, "committer-date-is-author-date",
1102 &options.committer_date_is_author_date,
1103 N_("make committer date match author date")),
1104 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1105 N_("ignore author date and use current date")),
1106 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1107 N_("synonym of --reset-author-date")),
1108 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1109 N_("passed to 'git apply'"), 0),
1110 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1111 N_("ignore changes in whitespace")),
1112 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1113 N_("action"), N_("passed to 'git apply'"), 0),
1114 OPT_BIT('f', "force-rebase", &options.flags,
1115 N_("cherry-pick all commits, even if unchanged"),
1116 REBASE_FORCE),
1117 OPT_BIT(0, "no-ff", &options.flags,
1118 N_("cherry-pick all commits, even if unchanged"),
1119 REBASE_FORCE),
1120 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1121 ACTION_CONTINUE),
1122 OPT_CMDMODE(0, "skip", &options.action,
1123 N_("skip current patch and continue"), ACTION_SKIP),
1124 OPT_CMDMODE(0, "abort", &options.action,
1125 N_("abort and check out the original branch"),
1126 ACTION_ABORT),
1127 OPT_CMDMODE(0, "quit", &options.action,
1128 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1129 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1130 "during an interactive rebase"), ACTION_EDIT_TODO),
1131 OPT_CMDMODE(0, "show-current-patch", &options.action,
1132 N_("show the patch file being applied or merged"),
1133 ACTION_SHOW_CURRENT_PATCH),
1134 OPT_CALLBACK_F(0, "apply", &options, NULL,
1135 N_("use apply strategies to rebase"),
1136 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1137 parse_opt_am),
1138 OPT_CALLBACK_F('m', "merge", &options, NULL,
1139 N_("use merging strategies to rebase"),
1140 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1141 parse_opt_merge),
1142 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1143 N_("let the user edit the list of commits to rebase"),
1144 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1145 parse_opt_interactive),
1146 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1147 N_("(REMOVED) was: try to recreate merges "
1148 "instead of ignoring them"),
1149 1, PARSE_OPT_HIDDEN),
1150 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1151 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1152 N_("how to handle commits that become empty"),
1153 PARSE_OPT_NONEG, parse_opt_empty),
1154 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1155 N_("keep commits which start empty"),
1156 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1157 parse_opt_keep_empty),
1158 OPT_BOOL(0, "autosquash", &options.autosquash,
1159 N_("move commits that begin with "
1160 "squash!/fixup! under -i")),
1161 OPT_BOOL(0, "update-refs", &options.update_refs,
1162 N_("update branches that point to commits "
1163 "that are being rebased")),
1164 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1165 N_("GPG-sign commits"),
1166 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1167 OPT_AUTOSTASH(&options.autostash),
1168 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1169 N_("add exec lines after each commit of the "
1170 "editable list")),
1171 OPT_BOOL_F(0, "allow-empty-message",
1172 &options.allow_empty_message,
1173 N_("allow rebasing commits with empty messages"),
1174 PARSE_OPT_HIDDEN),
1175 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1176 N_("try to rebase merges instead of skipping them"),
1177 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1178 OPT_BOOL(0, "fork-point", &options.fork_point,
1179 N_("use 'merge-base --fork-point' to refine upstream")),
1180 OPT_STRING('s', "strategy", &options.strategy,
1181 N_("strategy"), N_("use the given merge strategy")),
1182 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1183 N_("option"),
1184 N_("pass the argument through to the merge "
1185 "strategy")),
1186 OPT_BOOL(0, "root", &options.root,
1187 N_("rebase all reachable commits up to the root(s)")),
1188 OPT_BOOL(0, "reschedule-failed-exec",
1189 &reschedule_failed_exec,
1190 N_("automatically re-schedule any `exec` that fails")),
1191 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1192 N_("apply all changes, even those already present upstream")),
1193 OPT_END(),
1195 int i;
1197 if (argc == 2 && !strcmp(argv[1], "-h"))
1198 usage_with_options(builtin_rebase_usage,
1199 builtin_rebase_options);
1201 prepare_repo_settings(the_repository);
1202 the_repository->settings.command_requires_full_index = 0;
1204 git_config(rebase_config, &options);
1205 /* options.gpg_sign_opt will be either "-S" or NULL */
1206 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1207 FREE_AND_NULL(options.gpg_sign_opt);
1209 strbuf_reset(&buf);
1210 strbuf_addf(&buf, "%s/applying", apply_dir());
1211 if(file_exists(buf.buf))
1212 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1214 if (is_directory(apply_dir())) {
1215 options.type = REBASE_APPLY;
1216 options.state_dir = apply_dir();
1217 } else if (is_directory(merge_dir())) {
1218 strbuf_reset(&buf);
1219 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1220 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1221 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1222 "Use `git rebase --abort` to terminate current rebase.\n"
1223 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1224 } else {
1225 strbuf_reset(&buf);
1226 strbuf_addf(&buf, "%s/interactive", merge_dir());
1227 options.type = REBASE_MERGE;
1228 if (file_exists(buf.buf))
1229 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1231 options.state_dir = merge_dir();
1234 if (options.type != REBASE_UNSPECIFIED)
1235 in_progress = 1;
1237 total_argc = argc;
1238 argc = parse_options(argc, argv, prefix,
1239 builtin_rebase_options,
1240 builtin_rebase_usage, 0);
1242 if (preserve_merges_selected)
1243 die(_("--preserve-merges was replaced by --rebase-merges\n"
1244 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1245 "which is no longer supported; use 'merges' instead"));
1247 if (options.action != ACTION_NONE && total_argc != 2) {
1248 usage_with_options(builtin_rebase_usage,
1249 builtin_rebase_options);
1252 if (argc > 2)
1253 usage_with_options(builtin_rebase_usage,
1254 builtin_rebase_options);
1256 if (keep_base) {
1257 if (options.onto_name)
1258 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1259 if (options.root)
1260 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1262 * --keep-base defaults to --no-fork-point to keep the
1263 * base the same.
1265 if (options.fork_point < 0)
1266 options.fork_point = 0;
1268 if (options.root && options.fork_point > 0)
1269 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1271 if (options.action != ACTION_NONE && !in_progress)
1272 die(_("No rebase in progress?"));
1274 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1275 die(_("The --edit-todo action can only be used during "
1276 "interactive rebase."));
1278 if (trace2_is_enabled()) {
1279 if (is_merge(&options))
1280 trace2_cmd_mode("interactive");
1281 else if (options.exec.nr)
1282 trace2_cmd_mode("interactive-exec");
1283 else
1284 trace2_cmd_mode(action_names[options.action]);
1287 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1288 options.reflog_action =
1289 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1291 switch (options.action) {
1292 case ACTION_CONTINUE: {
1293 struct object_id head;
1294 struct lock_file lock_file = LOCK_INIT;
1295 int fd;
1297 /* Sanity check */
1298 if (repo_get_oid(the_repository, "HEAD", &head))
1299 die(_("Cannot read HEAD"));
1301 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1302 if (repo_read_index(the_repository) < 0)
1303 die(_("could not read index"));
1304 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1305 NULL);
1306 if (0 <= fd)
1307 repo_update_index_if_able(the_repository, &lock_file);
1308 rollback_lock_file(&lock_file);
1310 if (has_unstaged_changes(the_repository, 1)) {
1311 puts(_("You must edit all merge conflicts and then\n"
1312 "mark them as resolved using git add"));
1313 exit(1);
1315 if (read_basic_state(&options))
1316 exit(1);
1317 goto run_rebase;
1319 case ACTION_SKIP: {
1320 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1322 rerere_clear(the_repository, &merge_rr);
1323 string_list_clear(&merge_rr, 1);
1324 ropts.flags = RESET_HEAD_HARD;
1325 if (reset_head(the_repository, &ropts) < 0)
1326 die(_("could not discard worktree changes"));
1327 remove_branch_state(the_repository, 0);
1328 if (read_basic_state(&options))
1329 exit(1);
1330 goto run_rebase;
1332 case ACTION_ABORT: {
1333 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1334 struct strbuf head_msg = STRBUF_INIT;
1336 rerere_clear(the_repository, &merge_rr);
1337 string_list_clear(&merge_rr, 1);
1339 if (read_basic_state(&options))
1340 exit(1);
1342 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1343 options.reflog_action,
1344 options.head_name ? options.head_name
1345 : oid_to_hex(&options.orig_head->object.oid));
1346 ropts.oid = &options.orig_head->object.oid;
1347 ropts.head_msg = head_msg.buf;
1348 ropts.branch = options.head_name;
1349 ropts.flags = RESET_HEAD_HARD;
1350 if (reset_head(the_repository, &ropts) < 0)
1351 die(_("could not move back to %s"),
1352 oid_to_hex(&options.orig_head->object.oid));
1353 strbuf_release(&head_msg);
1354 remove_branch_state(the_repository, 0);
1355 ret = finish_rebase(&options);
1356 goto cleanup;
1358 case ACTION_QUIT: {
1359 save_autostash(state_dir_path("autostash", &options));
1360 if (options.type == REBASE_MERGE) {
1361 struct replay_opts replay = REPLAY_OPTS_INIT;
1363 replay.action = REPLAY_INTERACTIVE_REBASE;
1364 ret = sequencer_remove_state(&replay);
1365 replay_opts_release(&replay);
1366 } else {
1367 strbuf_reset(&buf);
1368 strbuf_addstr(&buf, options.state_dir);
1369 ret = remove_dir_recursively(&buf, 0);
1370 if (ret)
1371 error(_("could not remove '%s'"),
1372 options.state_dir);
1374 goto cleanup;
1376 case ACTION_EDIT_TODO:
1377 options.dont_finish_rebase = 1;
1378 goto run_rebase;
1379 case ACTION_SHOW_CURRENT_PATCH:
1380 options.dont_finish_rebase = 1;
1381 goto run_rebase;
1382 case ACTION_NONE:
1383 break;
1384 default:
1385 BUG("action: %d", options.action);
1388 /* Make sure no rebase is in progress */
1389 if (in_progress) {
1390 const char *last_slash = strrchr(options.state_dir, '/');
1391 const char *state_dir_base =
1392 last_slash ? last_slash + 1 : options.state_dir;
1393 const char *cmd_live_rebase =
1394 "git rebase (--continue | --abort | --skip)";
1395 strbuf_reset(&buf);
1396 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1397 die(_("It seems that there is already a %s directory, and\n"
1398 "I wonder if you are in the middle of another rebase. "
1399 "If that is the\n"
1400 "case, please try\n\t%s\n"
1401 "If that is not the case, please\n\t%s\n"
1402 "and run me again. I am stopping in case you still "
1403 "have something\n"
1404 "valuable there.\n"),
1405 state_dir_base, cmd_live_rebase, buf.buf);
1408 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1409 (options.action != ACTION_NONE) ||
1410 (options.exec.nr > 0) ||
1411 (options.autosquash == -1 && options.config_autosquash == 1) ||
1412 options.autosquash == 1) {
1413 allow_preemptive_ff = 0;
1415 if (options.committer_date_is_author_date || options.ignore_date)
1416 options.flags |= REBASE_FORCE;
1418 for (i = 0; i < options.git_am_opts.nr; i++) {
1419 const char *option = options.git_am_opts.v[i], *p;
1420 if (!strcmp(option, "--whitespace=fix") ||
1421 !strcmp(option, "--whitespace=strip"))
1422 allow_preemptive_ff = 0;
1423 else if (skip_prefix(option, "-C", &p)) {
1424 while (*p)
1425 if (!isdigit(*(p++)))
1426 die(_("switch `C' expects a "
1427 "numerical value"));
1428 } else if (skip_prefix(option, "--whitespace=", &p)) {
1429 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1430 strcmp(p, "error") && strcmp(p, "error-all"))
1431 die("Invalid whitespace option: '%s'", p);
1435 for (i = 0; i < options.exec.nr; i++)
1436 if (check_exec_cmd(options.exec.items[i].string))
1437 exit(1);
1439 if (!(options.flags & REBASE_NO_QUIET))
1440 strvec_push(&options.git_am_opts, "-q");
1442 if (options.empty != EMPTY_UNSPECIFIED)
1443 imply_merge(&options, "--empty");
1445 if (options.reapply_cherry_picks < 0)
1447 * We default to --no-reapply-cherry-picks unless
1448 * --keep-base is given; when --keep-base is given, we want
1449 * to default to --reapply-cherry-picks.
1451 options.reapply_cherry_picks = keep_base;
1452 else if (!keep_base)
1454 * The apply backend always searches for and drops cherry
1455 * picks. This is often not wanted with --keep-base, so
1456 * --keep-base allows --reapply-cherry-picks to be
1457 * simulated by altering the upstream such that
1458 * cherry-picks cannot be detected and thus all commits are
1459 * reapplied. Thus, --[no-]reapply-cherry-picks is
1460 * supported when --keep-base is specified, but not when
1461 * --keep-base is left out.
1463 imply_merge(&options, options.reapply_cherry_picks ?
1464 "--reapply-cherry-picks" :
1465 "--no-reapply-cherry-picks");
1467 if (gpg_sign)
1468 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1470 if (options.exec.nr)
1471 imply_merge(&options, "--exec");
1473 if (options.type == REBASE_APPLY) {
1474 if (ignore_whitespace)
1475 strvec_push(&options.git_am_opts,
1476 "--ignore-whitespace");
1477 if (options.committer_date_is_author_date)
1478 strvec_push(&options.git_am_opts,
1479 "--committer-date-is-author-date");
1480 if (options.ignore_date)
1481 strvec_push(&options.git_am_opts, "--ignore-date");
1482 } else {
1483 /* REBASE_MERGE */
1484 if (ignore_whitespace) {
1485 string_list_append(&options.strategy_opts,
1486 "ignore-space-change");
1490 if (options.strategy_opts.nr && !options.strategy)
1491 options.strategy = "ort";
1493 if (options.strategy) {
1494 options.strategy = xstrdup(options.strategy);
1495 switch (options.type) {
1496 case REBASE_APPLY:
1497 die(_("--strategy requires --merge or --interactive"));
1498 case REBASE_MERGE:
1499 /* compatible */
1500 break;
1501 case REBASE_UNSPECIFIED:
1502 options.type = REBASE_MERGE;
1503 break;
1504 default:
1505 BUG("unhandled rebase type (%d)", options.type);
1509 if (options.type == REBASE_MERGE)
1510 imply_merge(&options, "--merge");
1512 if (options.root && !options.onto_name)
1513 imply_merge(&options, "--root without --onto");
1515 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1516 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1518 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1519 /* all am options except -q are compatible only with --apply */
1520 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1521 if (strcmp(options.git_am_opts.v[i], "-q"))
1522 break;
1524 if (i >= 0 || options.type == REBASE_APPLY) {
1525 if (is_merge(&options))
1526 die(_("apply options and merge options "
1527 "cannot be used together"));
1528 else if (options.autosquash == -1 && options.config_autosquash == 1)
1529 die(_("apply options are incompatible with rebase.autoSquash. Consider adding --no-autosquash"));
1530 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1531 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1532 else if (options.update_refs == -1 && options.config_update_refs == 1)
1533 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1534 else
1535 options.type = REBASE_APPLY;
1539 if (options.update_refs == 1)
1540 imply_merge(&options, "--update-refs");
1541 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1542 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1544 if (options.rebase_merges == 1)
1545 imply_merge(&options, "--rebase-merges");
1546 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1547 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1549 if (options.autosquash == 1)
1550 imply_merge(&options, "--autosquash");
1551 options.autosquash = (options.autosquash >= 0) ? options.autosquash :
1552 ((options.config_autosquash >= 0) ? options.config_autosquash : 0);
1554 if (options.type == REBASE_UNSPECIFIED) {
1555 if (!strcmp(options.default_backend, "merge"))
1556 imply_merge(&options, "--merge");
1557 else if (!strcmp(options.default_backend, "apply"))
1558 options.type = REBASE_APPLY;
1559 else
1560 die(_("Unknown rebase backend: %s"),
1561 options.default_backend);
1564 if (options.type == REBASE_MERGE &&
1565 !options.strategy &&
1566 getenv("GIT_TEST_MERGE_ALGORITHM"))
1567 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1569 switch (options.type) {
1570 case REBASE_MERGE:
1571 options.state_dir = merge_dir();
1572 break;
1573 case REBASE_APPLY:
1574 options.state_dir = apply_dir();
1575 break;
1576 default:
1577 BUG("options.type was just set above; should be unreachable.");
1580 if (options.empty == EMPTY_UNSPECIFIED) {
1581 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1582 options.empty = EMPTY_ASK;
1583 else if (options.exec.nr > 0)
1584 options.empty = EMPTY_KEEP;
1585 else
1586 options.empty = EMPTY_DROP;
1588 if (reschedule_failed_exec > 0 && !is_merge(&options))
1589 die(_("--reschedule-failed-exec requires "
1590 "--exec or --interactive"));
1591 if (reschedule_failed_exec >= 0)
1592 options.reschedule_failed_exec = reschedule_failed_exec;
1594 if (options.signoff) {
1595 strvec_push(&options.git_am_opts, "--signoff");
1596 options.flags |= REBASE_FORCE;
1599 if (!options.root) {
1600 if (argc < 1) {
1601 struct branch *branch;
1603 branch = branch_get(NULL);
1604 options.upstream_name = branch_get_upstream(branch,
1605 NULL);
1606 if (!options.upstream_name)
1607 error_on_missing_default_upstream();
1608 if (options.fork_point < 0)
1609 options.fork_point = 1;
1610 } else {
1611 options.upstream_name = argv[0];
1612 argc--;
1613 argv++;
1614 if (!strcmp(options.upstream_name, "-"))
1615 options.upstream_name = "@{-1}";
1617 options.upstream =
1618 lookup_commit_reference_by_name(options.upstream_name);
1619 if (!options.upstream)
1620 die(_("invalid upstream '%s'"), options.upstream_name);
1621 options.upstream_arg = options.upstream_name;
1622 } else {
1623 if (!options.onto_name) {
1624 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1625 &squash_onto, NULL, NULL) < 0)
1626 die(_("Could not create new root commit"));
1627 options.squash_onto = &squash_onto;
1628 options.onto_name = squash_onto_name =
1629 xstrdup(oid_to_hex(&squash_onto));
1630 } else
1631 options.root_with_onto = 1;
1633 options.upstream_name = NULL;
1634 options.upstream = NULL;
1635 if (argc > 1)
1636 usage_with_options(builtin_rebase_usage,
1637 builtin_rebase_options);
1638 options.upstream_arg = "--root";
1642 * If the branch to rebase is given, that is the branch we will rebase
1643 * branch_name -- branch/commit being rebased, or
1644 * HEAD (already detached)
1645 * orig_head -- commit object name of tip of the branch before rebasing
1646 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1648 if (argc == 1) {
1649 /* Is it "rebase other branchname" or "rebase other commit"? */
1650 struct object_id branch_oid;
1651 branch_name = argv[0];
1652 options.switch_to = argv[0];
1654 /* Is it a local branch? */
1655 strbuf_reset(&buf);
1656 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1657 if (!read_ref(buf.buf, &branch_oid)) {
1658 die_if_checked_out(buf.buf, 1);
1659 options.head_name = xstrdup(buf.buf);
1660 options.orig_head =
1661 lookup_commit_object(the_repository,
1662 &branch_oid);
1663 /* If not is it a valid ref (branch or commit)? */
1664 } else {
1665 options.orig_head =
1666 lookup_commit_reference_by_name(branch_name);
1667 options.head_name = NULL;
1669 if (!options.orig_head)
1670 die(_("no such branch/commit '%s'"), branch_name);
1671 } else if (argc == 0) {
1672 /* Do not need to switch branches, we are already on it. */
1673 options.head_name =
1674 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1675 &flags));
1676 if (!options.head_name)
1677 die(_("No such ref: %s"), "HEAD");
1678 if (flags & REF_ISSYMREF) {
1679 if (!skip_prefix(options.head_name,
1680 "refs/heads/", &branch_name))
1681 branch_name = options.head_name;
1683 } else {
1684 FREE_AND_NULL(options.head_name);
1685 branch_name = "HEAD";
1687 options.orig_head = lookup_commit_reference_by_name("HEAD");
1688 if (!options.orig_head)
1689 die(_("Could not resolve HEAD to a commit"));
1690 } else
1691 BUG("unexpected number of arguments left to parse");
1693 /* Make sure the branch to rebase onto is valid. */
1694 if (keep_base) {
1695 strbuf_reset(&buf);
1696 strbuf_addstr(&buf, options.upstream_name);
1697 strbuf_addstr(&buf, "...");
1698 strbuf_addstr(&buf, branch_name);
1699 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1700 } else if (!options.onto_name)
1701 options.onto_name = options.upstream_name;
1702 if (strstr(options.onto_name, "...")) {
1703 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1704 if (keep_base)
1705 die(_("'%s': need exactly one merge base with branch"),
1706 options.upstream_name);
1707 else
1708 die(_("'%s': need exactly one merge base"),
1709 options.onto_name);
1711 options.onto = lookup_commit_or_die(&branch_base,
1712 options.onto_name);
1713 } else {
1714 options.onto =
1715 lookup_commit_reference_by_name(options.onto_name);
1716 if (!options.onto)
1717 die(_("Does not point to a valid commit '%s'"),
1718 options.onto_name);
1719 fill_branch_base(&options, &branch_base);
1722 if (keep_base && options.reapply_cherry_picks)
1723 options.upstream = options.onto;
1725 if (options.fork_point > 0)
1726 options.restrict_revision =
1727 get_fork_point(options.upstream_name, options.orig_head);
1729 if (repo_read_index(the_repository) < 0)
1730 die(_("could not read index"));
1732 if (options.autostash)
1733 create_autostash(the_repository,
1734 state_dir_path("autostash", &options));
1737 if (require_clean_work_tree(the_repository, "rebase",
1738 _("Please commit or stash them."), 1, 1)) {
1739 ret = -1;
1740 goto cleanup;
1744 * Now we are rebasing commits upstream..orig_head (or with --root,
1745 * everything leading up to orig_head) on top of onto.
1749 * Check if we are already based on onto with linear history,
1750 * in which case we could fast-forward without replacing the commits
1751 * with new commits recreated by replaying their changes.
1753 if (allow_preemptive_ff &&
1754 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1755 options.orig_head, &branch_base)) {
1756 int flag;
1758 if (!(options.flags & REBASE_FORCE)) {
1759 /* Lazily switch to the target branch if needed... */
1760 if (options.switch_to) {
1761 ret = checkout_up_to_date(&options);
1762 if (ret)
1763 goto cleanup;
1766 if (!(options.flags & REBASE_NO_QUIET))
1767 ; /* be quiet */
1768 else if (!strcmp(branch_name, "HEAD") &&
1769 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1770 puts(_("HEAD is up to date."));
1771 else
1772 printf(_("Current branch %s is up to date.\n"),
1773 branch_name);
1774 ret = finish_rebase(&options);
1775 goto cleanup;
1776 } else if (!(options.flags & REBASE_NO_QUIET))
1777 ; /* be quiet */
1778 else if (!strcmp(branch_name, "HEAD") &&
1779 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1780 puts(_("HEAD is up to date, rebase forced."));
1781 else
1782 printf(_("Current branch %s is up to date, rebase "
1783 "forced.\n"), branch_name);
1786 /* If a hook exists, give it a chance to interrupt*/
1787 if (!ok_to_skip_pre_rebase &&
1788 run_hooks_l("pre-rebase", options.upstream_arg,
1789 argc ? argv[0] : NULL, NULL))
1790 die(_("The pre-rebase hook refused to rebase."));
1792 if (options.flags & REBASE_DIFFSTAT) {
1793 struct diff_options opts;
1795 if (options.flags & REBASE_VERBOSE) {
1796 if (is_null_oid(&branch_base))
1797 printf(_("Changes to %s:\n"),
1798 oid_to_hex(&options.onto->object.oid));
1799 else
1800 printf(_("Changes from %s to %s:\n"),
1801 oid_to_hex(&branch_base),
1802 oid_to_hex(&options.onto->object.oid));
1805 /* We want color (if set), but no pager */
1806 repo_diff_setup(the_repository, &opts);
1807 opts.stat_width = -1; /* use full terminal width */
1808 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1809 opts.output_format |=
1810 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1811 opts.detect_rename = DIFF_DETECT_RENAME;
1812 diff_setup_done(&opts);
1813 diff_tree_oid(is_null_oid(&branch_base) ?
1814 the_hash_algo->empty_tree : &branch_base,
1815 &options.onto->object.oid, "", &opts);
1816 diffcore_std(&opts);
1817 diff_flush(&opts);
1820 if (is_merge(&options))
1821 goto run_rebase;
1823 /* Detach HEAD and reset the tree */
1824 if (options.flags & REBASE_NO_QUIET)
1825 printf(_("First, rewinding head to replay your work on top of "
1826 "it...\n"));
1828 strbuf_addf(&msg, "%s (start): checkout %s",
1829 options.reflog_action, options.onto_name);
1830 ropts.oid = &options.onto->object.oid;
1831 ropts.orig_head = &options.orig_head->object.oid,
1832 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1833 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1834 ropts.head_msg = msg.buf;
1835 ropts.default_reflog_action = options.reflog_action;
1836 if (reset_head(the_repository, &ropts))
1837 die(_("Could not detach HEAD"));
1838 strbuf_release(&msg);
1841 * If the onto is a proper descendant of the tip of the branch, then
1842 * we just fast-forwarded.
1844 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1845 printf(_("Fast-forwarded %s to %s.\n"),
1846 branch_name, options.onto_name);
1847 move_to_original_branch(&options);
1848 ret = finish_rebase(&options);
1849 goto cleanup;
1852 strbuf_addf(&revisions, "%s..%s",
1853 options.root ? oid_to_hex(&options.onto->object.oid) :
1854 (options.restrict_revision ?
1855 oid_to_hex(&options.restrict_revision->object.oid) :
1856 oid_to_hex(&options.upstream->object.oid)),
1857 oid_to_hex(&options.orig_head->object.oid));
1859 options.revisions = revisions.buf;
1861 run_rebase:
1862 ret = run_specific_rebase(&options);
1864 cleanup:
1865 strbuf_release(&buf);
1866 strbuf_release(&revisions);
1867 free(options.reflog_action);
1868 free(options.head_name);
1869 strvec_clear(&options.git_am_opts);
1870 free(options.gpg_sign_opt);
1871 string_list_clear(&options.exec, 0);
1872 free(options.strategy);
1873 string_list_clear(&options.strategy_opts, 0);
1874 strbuf_release(&options.git_format_patch_opt);
1875 free(squash_onto_name);
1876 free(keep_base_onto_name);
1877 return !!ret;