merge-ort: initialize repo in index state
[git/gitster.git] / builtin / rebase.c
blobace1d5e8d11afee64ce0e400867b97b627282f2f
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 "commit.h"
28 #include "diff.h"
29 #include "wt-status.h"
30 #include "revision.h"
31 #include "commit-reach.h"
32 #include "rerere.h"
33 #include "branch.h"
34 #include "sequencer.h"
35 #include "rebase-interactive.h"
36 #include "reset.h"
37 #include "trace2.h"
38 #include "hook.h"
39 #include "wrapper.h"
41 static char const * const builtin_rebase_usage[] = {
42 N_("git rebase [-i] [options] [--exec <cmd>] "
43 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
44 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
45 "--root [<branch>]"),
46 "git rebase --continue | --abort | --skip | --edit-todo",
47 NULL
50 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
51 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
52 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
53 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
55 enum rebase_type {
56 REBASE_UNSPECIFIED = -1,
57 REBASE_APPLY,
58 REBASE_MERGE
61 enum empty_type {
62 EMPTY_UNSPECIFIED = -1,
63 EMPTY_DROP,
64 EMPTY_KEEP,
65 EMPTY_ASK
68 enum action {
69 ACTION_NONE = 0,
70 ACTION_CONTINUE,
71 ACTION_SKIP,
72 ACTION_ABORT,
73 ACTION_QUIT,
74 ACTION_EDIT_TODO,
75 ACTION_SHOW_CURRENT_PATCH
78 static const char *action_names[] = {
79 "undefined",
80 "continue",
81 "skip",
82 "abort",
83 "quit",
84 "edit_todo",
85 "show_current_patch"
88 struct rebase_options {
89 enum rebase_type type;
90 enum empty_type empty;
91 const char *default_backend;
92 const char *state_dir;
93 struct commit *upstream;
94 const char *upstream_name;
95 const char *upstream_arg;
96 char *head_name;
97 struct commit *orig_head;
98 struct commit *onto;
99 const char *onto_name;
100 const char *revisions;
101 const char *switch_to;
102 int root, root_with_onto;
103 struct object_id *squash_onto;
104 struct commit *restrict_revision;
105 int dont_finish_rebase;
106 enum {
107 REBASE_NO_QUIET = 1<<0,
108 REBASE_VERBOSE = 1<<1,
109 REBASE_DIFFSTAT = 1<<2,
110 REBASE_FORCE = 1<<3,
111 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
112 } flags;
113 struct strvec git_am_opts;
114 enum action action;
115 char *reflog_action;
116 int signoff;
117 int allow_rerere_autoupdate;
118 int keep_empty;
119 int autosquash;
120 char *gpg_sign_opt;
121 int autostash;
122 int committer_date_is_author_date;
123 int ignore_date;
124 struct string_list exec;
125 int allow_empty_message;
126 int rebase_merges, rebase_cousins;
127 char *strategy;
128 struct string_list strategy_opts;
129 struct strbuf git_format_patch_opt;
130 int reschedule_failed_exec;
131 int reapply_cherry_picks;
132 int fork_point;
133 int update_refs;
134 int config_autosquash;
135 int config_rebase_merges;
136 int config_update_refs;
139 #define REBASE_OPTIONS_INIT { \
140 .type = REBASE_UNSPECIFIED, \
141 .empty = EMPTY_UNSPECIFIED, \
142 .keep_empty = 1, \
143 .default_backend = "merge", \
144 .flags = REBASE_NO_QUIET, \
145 .git_am_opts = STRVEC_INIT, \
146 .exec = STRING_LIST_INIT_NODUP, \
147 .git_format_patch_opt = STRBUF_INIT, \
148 .fork_point = -1, \
149 .reapply_cherry_picks = -1, \
150 .allow_empty_message = 1, \
151 .autosquash = -1, \
152 .config_autosquash = -1, \
153 .rebase_merges = -1, \
154 .config_rebase_merges = -1, \
155 .update_refs = -1, \
156 .config_update_refs = -1, \
157 .strategy_opts = STRING_LIST_INIT_NODUP,\
160 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
162 struct replay_opts replay = REPLAY_OPTS_INIT;
164 replay.action = REPLAY_INTERACTIVE_REBASE;
165 replay.strategy = NULL;
166 sequencer_init_config(&replay);
168 replay.signoff = opts->signoff;
169 replay.allow_ff = !(opts->flags & REBASE_FORCE);
170 if (opts->allow_rerere_autoupdate)
171 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
172 replay.allow_empty = 1;
173 replay.allow_empty_message = opts->allow_empty_message;
174 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
175 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
176 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
177 replay.verbose = opts->flags & REBASE_VERBOSE;
178 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
179 replay.committer_date_is_author_date =
180 opts->committer_date_is_author_date;
181 replay.ignore_date = opts->ignore_date;
182 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
183 replay.reflog_action = xstrdup(opts->reflog_action);
184 if (opts->strategy)
185 replay.strategy = xstrdup_or_null(opts->strategy);
186 else if (!replay.strategy && replay.default_strategy) {
187 replay.strategy = replay.default_strategy;
188 replay.default_strategy = NULL;
191 for (size_t i = 0; i < opts->strategy_opts.nr; i++)
192 strvec_push(&replay.xopts, opts->strategy_opts.items[i].string);
194 if (opts->squash_onto) {
195 oidcpy(&replay.squash_onto, opts->squash_onto);
196 replay.have_squash_onto = 1;
199 return replay;
202 static int edit_todo_file(unsigned flags)
204 const char *todo_file = rebase_path_todo();
205 struct todo_list todo_list = TODO_LIST_INIT,
206 new_todo = TODO_LIST_INIT;
207 int res = 0;
209 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
210 return error_errno(_("could not read '%s'."), todo_file);
212 strbuf_stripspace(&todo_list.buf, 1);
213 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
214 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
215 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
216 res = error_errno(_("could not write '%s'"), todo_file);
218 todo_list_release(&todo_list);
219 todo_list_release(&new_todo);
221 return res;
224 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
225 struct object_id *orig_head, char **revisions,
226 char **shortrevisions)
228 struct commit *base_rev = upstream ? upstream : onto;
229 const char *shorthead;
231 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
232 oid_to_hex(orig_head));
234 shorthead = repo_find_unique_abbrev(the_repository, orig_head,
235 DEFAULT_ABBREV);
237 if (upstream) {
238 const char *shortrev;
240 shortrev = repo_find_unique_abbrev(the_repository,
241 &base_rev->object.oid,
242 DEFAULT_ABBREV);
244 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
245 } else
246 *shortrevisions = xstrdup(shorthead);
248 return 0;
251 static int init_basic_state(struct replay_opts *opts, const char *head_name,
252 struct commit *onto,
253 const struct object_id *orig_head)
255 FILE *interactive;
257 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
258 return error_errno(_("could not create temporary %s"), merge_dir());
260 delete_reflog("REBASE_HEAD");
262 interactive = fopen(path_interactive(), "w");
263 if (!interactive)
264 return error_errno(_("could not mark as interactive"));
265 fclose(interactive);
267 return write_basic_state(opts, head_name, onto, orig_head);
270 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
272 int ret = -1;
273 char *revisions = NULL, *shortrevisions = NULL;
274 struct strvec make_script_args = STRVEC_INIT;
275 struct todo_list todo_list = TODO_LIST_INIT;
276 struct replay_opts replay = get_replay_opts(opts);
278 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
279 &revisions, &shortrevisions))
280 goto cleanup;
282 if (init_basic_state(&replay,
283 opts->head_name ? opts->head_name : "detached HEAD",
284 opts->onto, &opts->orig_head->object.oid))
285 goto cleanup;
287 if (!opts->upstream && opts->squash_onto)
288 write_file(path_squash_onto(), "%s\n",
289 oid_to_hex(opts->squash_onto));
291 strvec_pushl(&make_script_args, "", revisions, NULL);
292 if (opts->restrict_revision)
293 strvec_pushf(&make_script_args, "^%s",
294 oid_to_hex(&opts->restrict_revision->object.oid));
296 ret = sequencer_make_script(the_repository, &todo_list.buf,
297 make_script_args.nr, make_script_args.v,
298 flags);
300 if (ret)
301 error(_("could not generate todo list"));
302 else {
303 discard_index(&the_index);
304 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
305 &todo_list))
306 BUG("unusable todo list");
308 ret = complete_action(the_repository, &replay, flags,
309 shortrevisions, opts->onto_name, opts->onto,
310 &opts->orig_head->object.oid, &opts->exec,
311 opts->autosquash, opts->update_refs, &todo_list);
314 cleanup:
315 replay_opts_release(&replay);
316 free(revisions);
317 free(shortrevisions);
318 todo_list_release(&todo_list);
319 strvec_clear(&make_script_args);
321 return ret;
324 static int run_sequencer_rebase(struct rebase_options *opts)
326 unsigned flags = 0;
327 int abbreviate_commands = 0, ret = 0;
329 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
331 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
332 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
333 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
334 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
335 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
336 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
337 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
339 switch (opts->action) {
340 case ACTION_NONE: {
341 if (!opts->onto && !opts->upstream)
342 die(_("a base commit must be provided with --upstream or --onto"));
344 ret = do_interactive_rebase(opts, flags);
345 break;
347 case ACTION_SKIP: {
348 struct string_list merge_rr = STRING_LIST_INIT_DUP;
350 rerere_clear(the_repository, &merge_rr);
352 /* fallthrough */
353 case ACTION_CONTINUE: {
354 struct replay_opts replay_opts = get_replay_opts(opts);
356 ret = sequencer_continue(the_repository, &replay_opts);
357 replay_opts_release(&replay_opts);
358 break;
360 case ACTION_EDIT_TODO:
361 ret = edit_todo_file(flags);
362 break;
363 case ACTION_SHOW_CURRENT_PATCH: {
364 struct child_process cmd = CHILD_PROCESS_INIT;
366 cmd.git_cmd = 1;
367 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
368 ret = run_command(&cmd);
370 break;
372 default:
373 BUG("invalid command '%d'", opts->action);
376 return ret;
379 static void imply_merge(struct rebase_options *opts, const char *option);
380 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
381 int unset)
383 struct rebase_options *opts = opt->value;
385 BUG_ON_OPT_ARG(arg);
387 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
388 opts->keep_empty = !unset;
389 opts->type = REBASE_MERGE;
390 return 0;
393 static int is_merge(struct rebase_options *opts)
395 return opts->type == REBASE_MERGE;
398 static void imply_merge(struct rebase_options *opts, const char *option)
400 switch (opts->type) {
401 case REBASE_APPLY:
402 die(_("%s requires the merge backend"), option);
403 break;
404 case REBASE_MERGE:
405 break;
406 default:
407 opts->type = REBASE_MERGE; /* implied */
408 break;
412 /* Returns the filename prefixed by the state_dir */
413 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
415 static struct strbuf path = STRBUF_INIT;
416 static size_t prefix_len;
418 if (!prefix_len) {
419 strbuf_addf(&path, "%s/", opts->state_dir);
420 prefix_len = path.len;
423 strbuf_setlen(&path, prefix_len);
424 strbuf_addstr(&path, filename);
425 return path.buf;
428 /* Initialize the rebase options from the state directory. */
429 static int read_basic_state(struct rebase_options *opts)
431 struct strbuf head_name = STRBUF_INIT;
432 struct strbuf buf = STRBUF_INIT;
433 struct object_id oid;
435 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
436 READ_ONELINER_WARN_MISSING) ||
437 !read_oneliner(&buf, state_dir_path("onto", opts),
438 READ_ONELINER_WARN_MISSING))
439 return -1;
440 opts->head_name = starts_with(head_name.buf, "refs/") ?
441 xstrdup(head_name.buf) : NULL;
442 strbuf_release(&head_name);
443 if (get_oid_hex(buf.buf, &oid) ||
444 !(opts->onto = lookup_commit_object(the_repository, &oid)))
445 return error(_("invalid onto: '%s'"), buf.buf);
448 * We always write to orig-head, but interactive rebase used to write to
449 * head. Fall back to reading from head to cover for the case that the
450 * user upgraded git with an ongoing interactive rebase.
452 strbuf_reset(&buf);
453 if (file_exists(state_dir_path("orig-head", opts))) {
454 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
455 READ_ONELINER_WARN_MISSING))
456 return -1;
457 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
458 READ_ONELINER_WARN_MISSING))
459 return -1;
460 if (get_oid_hex(buf.buf, &oid) ||
461 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
462 return error(_("invalid orig-head: '%s'"), buf.buf);
464 if (file_exists(state_dir_path("quiet", opts)))
465 opts->flags &= ~REBASE_NO_QUIET;
466 else
467 opts->flags |= REBASE_NO_QUIET;
469 if (file_exists(state_dir_path("verbose", opts)))
470 opts->flags |= REBASE_VERBOSE;
472 if (file_exists(state_dir_path("signoff", opts))) {
473 opts->signoff = 1;
474 opts->flags |= REBASE_FORCE;
477 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
478 strbuf_reset(&buf);
479 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
480 READ_ONELINER_WARN_MISSING))
481 return -1;
482 if (!strcmp(buf.buf, "--rerere-autoupdate"))
483 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
484 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
485 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
486 else
487 warning(_("ignoring invalid allow_rerere_autoupdate: "
488 "'%s'"), buf.buf);
491 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
492 strbuf_reset(&buf);
493 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
494 READ_ONELINER_WARN_MISSING))
495 return -1;
496 free(opts->gpg_sign_opt);
497 opts->gpg_sign_opt = xstrdup(buf.buf);
500 strbuf_release(&buf);
502 return 0;
505 static int rebase_write_basic_state(struct rebase_options *opts)
507 write_file(state_dir_path("head-name", opts), "%s",
508 opts->head_name ? opts->head_name : "detached HEAD");
509 write_file(state_dir_path("onto", opts), "%s",
510 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
511 write_file(state_dir_path("orig-head", opts), "%s",
512 oid_to_hex(&opts->orig_head->object.oid));
513 if (!(opts->flags & REBASE_NO_QUIET))
514 write_file(state_dir_path("quiet", opts), "%s", "");
515 if (opts->flags & REBASE_VERBOSE)
516 write_file(state_dir_path("verbose", opts), "%s", "");
517 if (opts->allow_rerere_autoupdate > 0)
518 write_file(state_dir_path("allow_rerere_autoupdate", opts),
519 "-%s-rerere-autoupdate",
520 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
521 "" : "-no");
522 if (opts->gpg_sign_opt)
523 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
524 opts->gpg_sign_opt);
525 if (opts->signoff)
526 write_file(state_dir_path("signoff", opts), "--signoff");
528 return 0;
531 static int finish_rebase(struct rebase_options *opts)
533 struct strbuf dir = STRBUF_INIT;
534 int ret = 0;
536 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
537 unlink(git_path_auto_merge(the_repository));
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 const char *resolvemsg =
590 N_("Resolve all conflicts manually, mark them as resolved with\n"
591 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
592 "You can instead skip this commit: run \"git rebase --skip\".\n"
593 "To abort and get back to the state before \"git rebase\", run "
594 "\"git rebase --abort\".");
596 static int run_am(struct rebase_options *opts)
598 struct child_process am = CHILD_PROCESS_INIT;
599 struct child_process format_patch = CHILD_PROCESS_INIT;
600 struct strbuf revisions = STRBUF_INIT;
601 int status;
602 char *rebased_patches;
604 am.git_cmd = 1;
605 strvec_push(&am.args, "am");
606 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
607 opts->reflog_action);
608 if (opts->action == ACTION_CONTINUE) {
609 strvec_push(&am.args, "--resolved");
610 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
611 if (opts->gpg_sign_opt)
612 strvec_push(&am.args, opts->gpg_sign_opt);
613 status = run_command(&am);
614 if (status)
615 return status;
617 return move_to_original_branch(opts);
619 if (opts->action == ACTION_SKIP) {
620 strvec_push(&am.args, "--skip");
621 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
622 status = run_command(&am);
623 if (status)
624 return status;
626 return move_to_original_branch(opts);
628 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
629 strvec_push(&am.args, "--show-current-patch");
630 return run_command(&am);
633 strbuf_addf(&revisions, "%s...%s",
634 oid_to_hex(opts->root ?
635 /* this is now equivalent to !opts->upstream */
636 &opts->onto->object.oid :
637 &opts->upstream->object.oid),
638 oid_to_hex(&opts->orig_head->object.oid));
640 rebased_patches = xstrdup(git_path("rebased-patches"));
641 format_patch.out = open(rebased_patches,
642 O_WRONLY | O_CREAT | O_TRUNC, 0666);
643 if (format_patch.out < 0) {
644 status = error_errno(_("could not open '%s' for writing"),
645 rebased_patches);
646 free(rebased_patches);
647 strvec_clear(&am.args);
648 return status;
651 format_patch.git_cmd = 1;
652 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
653 "--full-index", "--cherry-pick", "--right-only",
654 "--default-prefix", "--no-renames",
655 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
656 "--no-base", NULL);
657 if (opts->git_format_patch_opt.len)
658 strvec_split(&format_patch.args,
659 opts->git_format_patch_opt.buf);
660 strvec_push(&format_patch.args, revisions.buf);
661 if (opts->restrict_revision)
662 strvec_pushf(&format_patch.args, "^%s",
663 oid_to_hex(&opts->restrict_revision->object.oid));
665 status = run_command(&format_patch);
666 if (status) {
667 struct reset_head_opts ropts = { 0 };
668 unlink(rebased_patches);
669 free(rebased_patches);
670 strvec_clear(&am.args);
672 ropts.oid = &opts->orig_head->object.oid;
673 ropts.branch = opts->head_name;
674 ropts.default_reflog_action = opts->reflog_action;
675 reset_head(the_repository, &ropts);
676 error(_("\ngit encountered an error while preparing the "
677 "patches to replay\n"
678 "these revisions:\n"
679 "\n %s\n\n"
680 "As a result, git cannot rebase them."),
681 opts->revisions);
683 strbuf_release(&revisions);
684 return status;
686 strbuf_release(&revisions);
688 am.in = open(rebased_patches, O_RDONLY);
689 if (am.in < 0) {
690 status = error_errno(_("could not open '%s' for reading"),
691 rebased_patches);
692 free(rebased_patches);
693 strvec_clear(&am.args);
694 return status;
697 strvec_pushv(&am.args, opts->git_am_opts.v);
698 strvec_push(&am.args, "--rebasing");
699 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
700 strvec_push(&am.args, "--patch-format=mboxrd");
701 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
702 strvec_push(&am.args, "--rerere-autoupdate");
703 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
704 strvec_push(&am.args, "--no-rerere-autoupdate");
705 if (opts->gpg_sign_opt)
706 strvec_push(&am.args, opts->gpg_sign_opt);
707 status = run_command(&am);
708 unlink(rebased_patches);
709 free(rebased_patches);
711 if (!status) {
712 return move_to_original_branch(opts);
715 if (is_directory(opts->state_dir))
716 rebase_write_basic_state(opts);
718 return status;
721 static int run_specific_rebase(struct rebase_options *opts)
723 int status;
725 if (opts->type == REBASE_MERGE) {
726 /* Run sequencer-based rebase */
727 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
728 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
729 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
730 opts->autosquash = 0;
732 if (opts->gpg_sign_opt) {
733 /* remove the leading "-S" */
734 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
735 free(opts->gpg_sign_opt);
736 opts->gpg_sign_opt = tmp;
739 status = run_sequencer_rebase(opts);
740 } else if (opts->type == REBASE_APPLY)
741 status = run_am(opts);
742 else
743 BUG("Unhandled rebase type %d", opts->type);
745 if (opts->dont_finish_rebase)
746 ; /* do nothing */
747 else if (opts->type == REBASE_MERGE)
748 ; /* merge backend cleans up after itself */
749 else if (status == 0) {
750 if (!file_exists(state_dir_path("stopped-sha", opts)))
751 finish_rebase(opts);
752 } else if (status == 2) {
753 struct strbuf dir = STRBUF_INIT;
755 apply_autostash(state_dir_path("autostash", opts));
756 strbuf_addstr(&dir, opts->state_dir);
757 remove_dir_recursively(&dir, 0);
758 strbuf_release(&dir);
759 die("Nothing to do");
762 return status ? -1 : 0;
765 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
767 if (!strcmp("no-rebase-cousins", value))
768 options->rebase_cousins = 0;
769 else if (!strcmp("rebase-cousins", value))
770 options->rebase_cousins = 1;
771 else
772 die(_("Unknown rebase-merges mode: %s"), value);
775 static int rebase_config(const char *var, const char *value, void *data)
777 struct rebase_options *opts = data;
779 if (!strcmp(var, "rebase.stat")) {
780 if (git_config_bool(var, value))
781 opts->flags |= REBASE_DIFFSTAT;
782 else
783 opts->flags &= ~REBASE_DIFFSTAT;
784 return 0;
787 if (!strcmp(var, "rebase.autosquash")) {
788 opts->config_autosquash = git_config_bool(var, value);
789 return 0;
792 if (!strcmp(var, "commit.gpgsign")) {
793 free(opts->gpg_sign_opt);
794 opts->gpg_sign_opt = git_config_bool(var, value) ?
795 xstrdup("-S") : NULL;
796 return 0;
799 if (!strcmp(var, "rebase.autostash")) {
800 opts->autostash = git_config_bool(var, value);
801 return 0;
804 if (!strcmp(var, "rebase.rebasemerges")) {
805 opts->config_rebase_merges = git_parse_maybe_bool(value);
806 if (opts->config_rebase_merges < 0) {
807 opts->config_rebase_merges = 1;
808 parse_rebase_merges_value(opts, value);
809 } else {
810 opts->rebase_cousins = 0;
812 return 0;
815 if (!strcmp(var, "rebase.updaterefs")) {
816 opts->config_update_refs = git_config_bool(var, value);
817 return 0;
820 if (!strcmp(var, "rebase.reschedulefailedexec")) {
821 opts->reschedule_failed_exec = git_config_bool(var, value);
822 return 0;
825 if (!strcmp(var, "rebase.forkpoint")) {
826 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
827 return 0;
830 if (!strcmp(var, "rebase.backend")) {
831 return git_config_string(&opts->default_backend, var, value);
834 return git_default_config(var, value, data);
837 static int checkout_up_to_date(struct rebase_options *options)
839 struct strbuf buf = STRBUF_INIT;
840 struct reset_head_opts ropts = { 0 };
841 int ret = 0;
843 strbuf_addf(&buf, "%s: checkout %s",
844 options->reflog_action, options->switch_to);
845 ropts.oid = &options->orig_head->object.oid;
846 ropts.branch = options->head_name;
847 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
848 if (!ropts.branch)
849 ropts.flags |= RESET_HEAD_DETACH;
850 ropts.head_msg = buf.buf;
851 if (reset_head(the_repository, &ropts) < 0)
852 ret = error(_("could not switch to %s"), options->switch_to);
853 strbuf_release(&buf);
855 return ret;
859 * Determines whether the commits in from..to are linear, i.e. contain
860 * no merge commits. This function *expects* `from` to be an ancestor of
861 * `to`.
863 static int is_linear_history(struct commit *from, struct commit *to)
865 while (to && to != from) {
866 repo_parse_commit(the_repository, to);
867 if (!to->parents)
868 return 1;
869 if (to->parents->next)
870 return 0;
871 to = to->parents->item;
873 return 1;
876 static int can_fast_forward(struct commit *onto, struct commit *upstream,
877 struct commit *restrict_revision,
878 struct commit *head, struct object_id *branch_base)
880 struct commit_list *merge_bases = NULL;
881 int res = 0;
883 if (is_null_oid(branch_base))
884 goto done; /* fill_branch_base() found multiple merge bases */
886 if (!oideq(branch_base, &onto->object.oid))
887 goto done;
889 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
890 goto done;
892 if (!upstream)
893 goto done;
895 merge_bases = repo_get_merge_bases(the_repository, upstream, head);
896 if (!merge_bases || merge_bases->next)
897 goto done;
899 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
900 goto done;
902 res = 1;
904 done:
905 free_commit_list(merge_bases);
906 return res && is_linear_history(onto, head);
909 static void fill_branch_base(struct rebase_options *options,
910 struct object_id *branch_base)
912 struct commit_list *merge_bases = NULL;
914 merge_bases = repo_get_merge_bases(the_repository, options->onto,
915 options->orig_head);
916 if (!merge_bases || merge_bases->next)
917 oidcpy(branch_base, null_oid());
918 else
919 oidcpy(branch_base, &merge_bases->item->object.oid);
921 free_commit_list(merge_bases);
924 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
926 struct rebase_options *opts = opt->value;
928 BUG_ON_OPT_NEG(unset);
929 BUG_ON_OPT_ARG(arg);
931 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
932 die(_("apply options and merge options cannot be used together"));
934 opts->type = REBASE_APPLY;
936 return 0;
939 /* -i followed by -m is still -i */
940 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
942 struct rebase_options *opts = opt->value;
944 BUG_ON_OPT_NEG(unset);
945 BUG_ON_OPT_ARG(arg);
947 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
948 die(_("apply options and merge options cannot be used together"));
950 opts->type = REBASE_MERGE;
952 return 0;
955 /* -i followed by -r is still explicitly interactive, but -r alone is not */
956 static int parse_opt_interactive(const struct option *opt, const char *arg,
957 int unset)
959 struct rebase_options *opts = opt->value;
961 BUG_ON_OPT_NEG(unset);
962 BUG_ON_OPT_ARG(arg);
964 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
965 die(_("apply options and merge options cannot be used together"));
967 opts->type = REBASE_MERGE;
968 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
970 return 0;
973 static enum empty_type parse_empty_value(const char *value)
975 if (!strcasecmp(value, "drop"))
976 return EMPTY_DROP;
977 else if (!strcasecmp(value, "keep"))
978 return EMPTY_KEEP;
979 else if (!strcasecmp(value, "ask"))
980 return EMPTY_ASK;
982 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
985 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
987 struct rebase_options *options = opt->value;
988 enum empty_type value = parse_empty_value(arg);
990 BUG_ON_OPT_NEG(unset);
992 options->empty = value;
993 return 0;
996 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
998 struct rebase_options *options = opt->value;
1000 options->rebase_merges = !unset;
1001 options->rebase_cousins = 0;
1003 if (arg) {
1004 if (!*arg) {
1005 warning(_("--rebase-merges with an empty string "
1006 "argument is deprecated and will stop "
1007 "working in a future version of Git. Use "
1008 "--rebase-merges without an argument "
1009 "instead, which does the same thing."));
1010 return 0;
1012 parse_rebase_merges_value(options, arg);
1015 return 0;
1018 static void NORETURN error_on_missing_default_upstream(void)
1020 struct branch *current_branch = branch_get(NULL);
1022 printf(_("%s\n"
1023 "Please specify which branch you want to rebase against.\n"
1024 "See git-rebase(1) for details.\n"
1025 "\n"
1026 " git rebase '<branch>'\n"
1027 "\n"),
1028 current_branch ? _("There is no tracking information for "
1029 "the current branch.") :
1030 _("You are not currently on a branch."));
1032 if (current_branch) {
1033 const char *remote = current_branch->remote_name;
1035 if (!remote)
1036 remote = _("<remote>");
1038 printf(_("If you wish to set tracking information for this "
1039 "branch you can do so with:\n"
1040 "\n"
1041 " git branch --set-upstream-to=%s/<branch> %s\n"
1042 "\n"),
1043 remote, current_branch->name);
1045 exit(1);
1048 static int check_exec_cmd(const char *cmd)
1050 if (strchr(cmd, '\n'))
1051 return error(_("exec commands cannot contain newlines"));
1053 /* Does the command consist purely of whitespace? */
1054 if (!cmd[strspn(cmd, " \t\r\f\v")])
1055 return error(_("empty exec command"));
1057 return 0;
1060 int cmd_rebase(int argc, const char **argv, const char *prefix)
1062 struct rebase_options options = REBASE_OPTIONS_INIT;
1063 const char *branch_name;
1064 int ret, flags, total_argc, in_progress = 0;
1065 int keep_base = 0;
1066 int ok_to_skip_pre_rebase = 0;
1067 struct strbuf msg = STRBUF_INIT;
1068 struct strbuf revisions = STRBUF_INIT;
1069 struct strbuf buf = STRBUF_INIT;
1070 struct object_id branch_base;
1071 int ignore_whitespace = 0;
1072 const char *gpg_sign = NULL;
1073 struct object_id squash_onto;
1074 char *squash_onto_name = NULL;
1075 char *keep_base_onto_name = NULL;
1076 int reschedule_failed_exec = -1;
1077 int allow_preemptive_ff = 1;
1078 int preserve_merges_selected = 0;
1079 struct reset_head_opts ropts = { 0 };
1080 struct option builtin_rebase_options[] = {
1081 OPT_STRING(0, "onto", &options.onto_name,
1082 N_("revision"),
1083 N_("rebase onto given branch instead of upstream")),
1084 OPT_BOOL(0, "keep-base", &keep_base,
1085 N_("use the merge-base of upstream and branch as the current base")),
1086 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1087 N_("allow pre-rebase hook to run")),
1088 OPT_NEGBIT('q', "quiet", &options.flags,
1089 N_("be quiet. implies --no-stat"),
1090 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1091 OPT_BIT('v', "verbose", &options.flags,
1092 N_("display a diffstat of what changed upstream"),
1093 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1094 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1095 N_("do not show diffstat of what changed upstream"),
1096 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1097 OPT_BOOL(0, "signoff", &options.signoff,
1098 N_("add a Signed-off-by trailer to each commit")),
1099 OPT_BOOL(0, "committer-date-is-author-date",
1100 &options.committer_date_is_author_date,
1101 N_("make committer date match author date")),
1102 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1103 N_("ignore author date and use current date")),
1104 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1105 N_("synonym of --reset-author-date")),
1106 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1107 N_("passed to 'git apply'"), 0),
1108 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1109 N_("ignore changes in whitespace")),
1110 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1111 N_("action"), N_("passed to 'git apply'"), 0),
1112 OPT_BIT('f', "force-rebase", &options.flags,
1113 N_("cherry-pick all commits, even if unchanged"),
1114 REBASE_FORCE),
1115 OPT_BIT(0, "no-ff", &options.flags,
1116 N_("cherry-pick all commits, even if unchanged"),
1117 REBASE_FORCE),
1118 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1119 ACTION_CONTINUE),
1120 OPT_CMDMODE(0, "skip", &options.action,
1121 N_("skip current patch and continue"), ACTION_SKIP),
1122 OPT_CMDMODE(0, "abort", &options.action,
1123 N_("abort and check out the original branch"),
1124 ACTION_ABORT),
1125 OPT_CMDMODE(0, "quit", &options.action,
1126 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1127 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1128 "during an interactive rebase"), ACTION_EDIT_TODO),
1129 OPT_CMDMODE(0, "show-current-patch", &options.action,
1130 N_("show the patch file being applied or merged"),
1131 ACTION_SHOW_CURRENT_PATCH),
1132 OPT_CALLBACK_F(0, "apply", &options, NULL,
1133 N_("use apply strategies to rebase"),
1134 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1135 parse_opt_am),
1136 OPT_CALLBACK_F('m', "merge", &options, NULL,
1137 N_("use merging strategies to rebase"),
1138 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1139 parse_opt_merge),
1140 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1141 N_("let the user edit the list of commits to rebase"),
1142 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1143 parse_opt_interactive),
1144 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1145 N_("(REMOVED) was: try to recreate merges "
1146 "instead of ignoring them"),
1147 1, PARSE_OPT_HIDDEN),
1148 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1149 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1150 N_("how to handle commits that become empty"),
1151 PARSE_OPT_NONEG, parse_opt_empty),
1152 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1153 N_("keep commits which start empty"),
1154 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1155 parse_opt_keep_empty),
1156 OPT_BOOL(0, "autosquash", &options.autosquash,
1157 N_("move commits that begin with "
1158 "squash!/fixup! under -i")),
1159 OPT_BOOL(0, "update-refs", &options.update_refs,
1160 N_("update branches that point to commits "
1161 "that are being rebased")),
1162 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1163 N_("GPG-sign commits"),
1164 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1165 OPT_AUTOSTASH(&options.autostash),
1166 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1167 N_("add exec lines after each commit of the "
1168 "editable list")),
1169 OPT_BOOL_F(0, "allow-empty-message",
1170 &options.allow_empty_message,
1171 N_("allow rebasing commits with empty messages"),
1172 PARSE_OPT_HIDDEN),
1173 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1174 N_("try to rebase merges instead of skipping them"),
1175 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1176 OPT_BOOL(0, "fork-point", &options.fork_point,
1177 N_("use 'merge-base --fork-point' to refine upstream")),
1178 OPT_STRING('s', "strategy", &options.strategy,
1179 N_("strategy"), N_("use the given merge strategy")),
1180 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1181 N_("option"),
1182 N_("pass the argument through to the merge "
1183 "strategy")),
1184 OPT_BOOL(0, "root", &options.root,
1185 N_("rebase all reachable commits up to the root(s)")),
1186 OPT_BOOL(0, "reschedule-failed-exec",
1187 &reschedule_failed_exec,
1188 N_("automatically re-schedule any `exec` that fails")),
1189 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1190 N_("apply all changes, even those already present upstream")),
1191 OPT_END(),
1193 int i;
1195 if (argc == 2 && !strcmp(argv[1], "-h"))
1196 usage_with_options(builtin_rebase_usage,
1197 builtin_rebase_options);
1199 prepare_repo_settings(the_repository);
1200 the_repository->settings.command_requires_full_index = 0;
1202 git_config(rebase_config, &options);
1203 /* options.gpg_sign_opt will be either "-S" or NULL */
1204 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1205 FREE_AND_NULL(options.gpg_sign_opt);
1207 strbuf_reset(&buf);
1208 strbuf_addf(&buf, "%s/applying", apply_dir());
1209 if(file_exists(buf.buf))
1210 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1212 if (is_directory(apply_dir())) {
1213 options.type = REBASE_APPLY;
1214 options.state_dir = apply_dir();
1215 } else if (is_directory(merge_dir())) {
1216 strbuf_reset(&buf);
1217 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1218 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1219 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1220 "Use `git rebase --abort` to terminate current rebase.\n"
1221 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1222 } else {
1223 strbuf_reset(&buf);
1224 strbuf_addf(&buf, "%s/interactive", merge_dir());
1225 options.type = REBASE_MERGE;
1226 if (file_exists(buf.buf))
1227 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1229 options.state_dir = merge_dir();
1232 if (options.type != REBASE_UNSPECIFIED)
1233 in_progress = 1;
1235 total_argc = argc;
1236 argc = parse_options(argc, argv, prefix,
1237 builtin_rebase_options,
1238 builtin_rebase_usage, 0);
1240 if (preserve_merges_selected)
1241 die(_("--preserve-merges was replaced by --rebase-merges\n"
1242 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1243 "which is no longer supported; use 'merges' instead"));
1245 if (options.action != ACTION_NONE && total_argc != 2) {
1246 usage_with_options(builtin_rebase_usage,
1247 builtin_rebase_options);
1250 if (argc > 2)
1251 usage_with_options(builtin_rebase_usage,
1252 builtin_rebase_options);
1254 if (keep_base) {
1255 if (options.onto_name)
1256 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1257 if (options.root)
1258 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1260 * --keep-base defaults to --no-fork-point to keep the
1261 * base the same.
1263 if (options.fork_point < 0)
1264 options.fork_point = 0;
1266 if (options.root && options.fork_point > 0)
1267 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1269 if (options.action != ACTION_NONE && !in_progress)
1270 die(_("No rebase in progress?"));
1272 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1273 die(_("The --edit-todo action can only be used during "
1274 "interactive rebase."));
1276 if (trace2_is_enabled()) {
1277 if (is_merge(&options))
1278 trace2_cmd_mode("interactive");
1279 else if (options.exec.nr)
1280 trace2_cmd_mode("interactive-exec");
1281 else
1282 trace2_cmd_mode(action_names[options.action]);
1285 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1286 options.reflog_action =
1287 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1289 switch (options.action) {
1290 case ACTION_CONTINUE: {
1291 struct object_id head;
1292 struct lock_file lock_file = LOCK_INIT;
1293 int fd;
1295 /* Sanity check */
1296 if (repo_get_oid(the_repository, "HEAD", &head))
1297 die(_("Cannot read HEAD"));
1299 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1300 if (repo_read_index(the_repository) < 0)
1301 die(_("could not read index"));
1302 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1303 NULL);
1304 if (0 <= fd)
1305 repo_update_index_if_able(the_repository, &lock_file);
1306 rollback_lock_file(&lock_file);
1308 if (has_unstaged_changes(the_repository, 1)) {
1309 puts(_("You must edit all merge conflicts and then\n"
1310 "mark them as resolved using git add"));
1311 exit(1);
1313 if (read_basic_state(&options))
1314 exit(1);
1315 goto run_rebase;
1317 case ACTION_SKIP: {
1318 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1320 rerere_clear(the_repository, &merge_rr);
1321 string_list_clear(&merge_rr, 1);
1322 ropts.flags = RESET_HEAD_HARD;
1323 if (reset_head(the_repository, &ropts) < 0)
1324 die(_("could not discard worktree changes"));
1325 remove_branch_state(the_repository, 0);
1326 if (read_basic_state(&options))
1327 exit(1);
1328 goto run_rebase;
1330 case ACTION_ABORT: {
1331 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1332 struct strbuf head_msg = STRBUF_INIT;
1334 rerere_clear(the_repository, &merge_rr);
1335 string_list_clear(&merge_rr, 1);
1337 if (read_basic_state(&options))
1338 exit(1);
1340 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1341 options.reflog_action,
1342 options.head_name ? options.head_name
1343 : oid_to_hex(&options.orig_head->object.oid));
1344 ropts.oid = &options.orig_head->object.oid;
1345 ropts.head_msg = head_msg.buf;
1346 ropts.branch = options.head_name;
1347 ropts.flags = RESET_HEAD_HARD;
1348 if (reset_head(the_repository, &ropts) < 0)
1349 die(_("could not move back to %s"),
1350 oid_to_hex(&options.orig_head->object.oid));
1351 strbuf_release(&head_msg);
1352 remove_branch_state(the_repository, 0);
1353 ret = finish_rebase(&options);
1354 goto cleanup;
1356 case ACTION_QUIT: {
1357 save_autostash(state_dir_path("autostash", &options));
1358 if (options.type == REBASE_MERGE) {
1359 struct replay_opts replay = REPLAY_OPTS_INIT;
1361 replay.action = REPLAY_INTERACTIVE_REBASE;
1362 ret = sequencer_remove_state(&replay);
1363 replay_opts_release(&replay);
1364 } else {
1365 strbuf_reset(&buf);
1366 strbuf_addstr(&buf, options.state_dir);
1367 ret = remove_dir_recursively(&buf, 0);
1368 if (ret)
1369 error(_("could not remove '%s'"),
1370 options.state_dir);
1372 goto cleanup;
1374 case ACTION_EDIT_TODO:
1375 options.dont_finish_rebase = 1;
1376 goto run_rebase;
1377 case ACTION_SHOW_CURRENT_PATCH:
1378 options.dont_finish_rebase = 1;
1379 goto run_rebase;
1380 case ACTION_NONE:
1381 break;
1382 default:
1383 BUG("action: %d", options.action);
1386 /* Make sure no rebase is in progress */
1387 if (in_progress) {
1388 const char *last_slash = strrchr(options.state_dir, '/');
1389 const char *state_dir_base =
1390 last_slash ? last_slash + 1 : options.state_dir;
1391 const char *cmd_live_rebase =
1392 "git rebase (--continue | --abort | --skip)";
1393 strbuf_reset(&buf);
1394 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1395 die(_("It seems that there is already a %s directory, and\n"
1396 "I wonder if you are in the middle of another rebase. "
1397 "If that is the\n"
1398 "case, please try\n\t%s\n"
1399 "If that is not the case, please\n\t%s\n"
1400 "and run me again. I am stopping in case you still "
1401 "have something\n"
1402 "valuable there.\n"),
1403 state_dir_base, cmd_live_rebase, buf.buf);
1406 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1407 (options.action != ACTION_NONE) ||
1408 (options.exec.nr > 0) ||
1409 (options.autosquash == -1 && options.config_autosquash == 1) ||
1410 options.autosquash == 1) {
1411 allow_preemptive_ff = 0;
1413 if (options.committer_date_is_author_date || options.ignore_date)
1414 options.flags |= REBASE_FORCE;
1416 for (i = 0; i < options.git_am_opts.nr; i++) {
1417 const char *option = options.git_am_opts.v[i], *p;
1418 if (!strcmp(option, "--whitespace=fix") ||
1419 !strcmp(option, "--whitespace=strip"))
1420 allow_preemptive_ff = 0;
1421 else if (skip_prefix(option, "-C", &p)) {
1422 while (*p)
1423 if (!isdigit(*(p++)))
1424 die(_("switch `C' expects a "
1425 "numerical value"));
1426 } else if (skip_prefix(option, "--whitespace=", &p)) {
1427 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1428 strcmp(p, "error") && strcmp(p, "error-all"))
1429 die("Invalid whitespace option: '%s'", p);
1433 for (i = 0; i < options.exec.nr; i++)
1434 if (check_exec_cmd(options.exec.items[i].string))
1435 exit(1);
1437 if (!(options.flags & REBASE_NO_QUIET))
1438 strvec_push(&options.git_am_opts, "-q");
1440 if (options.empty != EMPTY_UNSPECIFIED)
1441 imply_merge(&options, "--empty");
1443 if (options.reapply_cherry_picks < 0)
1445 * We default to --no-reapply-cherry-picks unless
1446 * --keep-base is given; when --keep-base is given, we want
1447 * to default to --reapply-cherry-picks.
1449 options.reapply_cherry_picks = keep_base;
1450 else if (!keep_base)
1452 * The apply backend always searches for and drops cherry
1453 * picks. This is often not wanted with --keep-base, so
1454 * --keep-base allows --reapply-cherry-picks to be
1455 * simulated by altering the upstream such that
1456 * cherry-picks cannot be detected and thus all commits are
1457 * reapplied. Thus, --[no-]reapply-cherry-picks is
1458 * supported when --keep-base is specified, but not when
1459 * --keep-base is left out.
1461 imply_merge(&options, options.reapply_cherry_picks ?
1462 "--reapply-cherry-picks" :
1463 "--no-reapply-cherry-picks");
1465 if (gpg_sign)
1466 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1468 if (options.exec.nr)
1469 imply_merge(&options, "--exec");
1471 if (options.type == REBASE_APPLY) {
1472 if (ignore_whitespace)
1473 strvec_push(&options.git_am_opts,
1474 "--ignore-whitespace");
1475 if (options.committer_date_is_author_date)
1476 strvec_push(&options.git_am_opts,
1477 "--committer-date-is-author-date");
1478 if (options.ignore_date)
1479 strvec_push(&options.git_am_opts, "--ignore-date");
1480 } else {
1481 /* REBASE_MERGE */
1482 if (ignore_whitespace) {
1483 string_list_append(&options.strategy_opts,
1484 "ignore-space-change");
1488 if (options.strategy_opts.nr && !options.strategy)
1489 options.strategy = "ort";
1491 if (options.strategy) {
1492 options.strategy = xstrdup(options.strategy);
1493 switch (options.type) {
1494 case REBASE_APPLY:
1495 die(_("--strategy requires --merge or --interactive"));
1496 case REBASE_MERGE:
1497 /* compatible */
1498 break;
1499 case REBASE_UNSPECIFIED:
1500 options.type = REBASE_MERGE;
1501 break;
1502 default:
1503 BUG("unhandled rebase type (%d)", options.type);
1507 if (options.type == REBASE_MERGE)
1508 imply_merge(&options, "--merge");
1510 if (options.root && !options.onto_name)
1511 imply_merge(&options, "--root without --onto");
1513 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1514 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1516 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1517 /* all am options except -q are compatible only with --apply */
1518 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1519 if (strcmp(options.git_am_opts.v[i], "-q"))
1520 break;
1522 if (i >= 0 || options.type == REBASE_APPLY) {
1523 if (is_merge(&options))
1524 die(_("apply options and merge options "
1525 "cannot be used together"));
1526 else if (options.autosquash == -1 && options.config_autosquash == 1)
1527 die(_("apply options are incompatible with rebase.autoSquash. Consider adding --no-autosquash"));
1528 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1529 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1530 else if (options.update_refs == -1 && options.config_update_refs == 1)
1531 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1532 else
1533 options.type = REBASE_APPLY;
1537 if (options.update_refs == 1)
1538 imply_merge(&options, "--update-refs");
1539 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1540 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1542 if (options.rebase_merges == 1)
1543 imply_merge(&options, "--rebase-merges");
1544 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1545 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1547 if (options.autosquash == 1)
1548 imply_merge(&options, "--autosquash");
1549 options.autosquash = (options.autosquash >= 0) ? options.autosquash :
1550 ((options.config_autosquash >= 0) ? options.config_autosquash : 0);
1552 if (options.type == REBASE_UNSPECIFIED) {
1553 if (!strcmp(options.default_backend, "merge"))
1554 imply_merge(&options, "--merge");
1555 else if (!strcmp(options.default_backend, "apply"))
1556 options.type = REBASE_APPLY;
1557 else
1558 die(_("Unknown rebase backend: %s"),
1559 options.default_backend);
1562 if (options.type == REBASE_MERGE &&
1563 !options.strategy &&
1564 getenv("GIT_TEST_MERGE_ALGORITHM"))
1565 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1567 switch (options.type) {
1568 case REBASE_MERGE:
1569 options.state_dir = merge_dir();
1570 break;
1571 case REBASE_APPLY:
1572 options.state_dir = apply_dir();
1573 break;
1574 default:
1575 BUG("options.type was just set above; should be unreachable.");
1578 if (options.empty == EMPTY_UNSPECIFIED) {
1579 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1580 options.empty = EMPTY_ASK;
1581 else if (options.exec.nr > 0)
1582 options.empty = EMPTY_KEEP;
1583 else
1584 options.empty = EMPTY_DROP;
1586 if (reschedule_failed_exec > 0 && !is_merge(&options))
1587 die(_("--reschedule-failed-exec requires "
1588 "--exec or --interactive"));
1589 if (reschedule_failed_exec >= 0)
1590 options.reschedule_failed_exec = reschedule_failed_exec;
1592 if (options.signoff) {
1593 strvec_push(&options.git_am_opts, "--signoff");
1594 options.flags |= REBASE_FORCE;
1597 if (!options.root) {
1598 if (argc < 1) {
1599 struct branch *branch;
1601 branch = branch_get(NULL);
1602 options.upstream_name = branch_get_upstream(branch,
1603 NULL);
1604 if (!options.upstream_name)
1605 error_on_missing_default_upstream();
1606 if (options.fork_point < 0)
1607 options.fork_point = 1;
1608 } else {
1609 options.upstream_name = argv[0];
1610 argc--;
1611 argv++;
1612 if (!strcmp(options.upstream_name, "-"))
1613 options.upstream_name = "@{-1}";
1615 options.upstream =
1616 lookup_commit_reference_by_name(options.upstream_name);
1617 if (!options.upstream)
1618 die(_("invalid upstream '%s'"), options.upstream_name);
1619 options.upstream_arg = options.upstream_name;
1620 } else {
1621 if (!options.onto_name) {
1622 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1623 &squash_onto, NULL, NULL) < 0)
1624 die(_("Could not create new root commit"));
1625 options.squash_onto = &squash_onto;
1626 options.onto_name = squash_onto_name =
1627 xstrdup(oid_to_hex(&squash_onto));
1628 } else
1629 options.root_with_onto = 1;
1631 options.upstream_name = NULL;
1632 options.upstream = NULL;
1633 if (argc > 1)
1634 usage_with_options(builtin_rebase_usage,
1635 builtin_rebase_options);
1636 options.upstream_arg = "--root";
1640 * If the branch to rebase is given, that is the branch we will rebase
1641 * branch_name -- branch/commit being rebased, or
1642 * HEAD (already detached)
1643 * orig_head -- commit object name of tip of the branch before rebasing
1644 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1646 if (argc == 1) {
1647 /* Is it "rebase other branchname" or "rebase other commit"? */
1648 struct object_id branch_oid;
1649 branch_name = argv[0];
1650 options.switch_to = argv[0];
1652 /* Is it a local branch? */
1653 strbuf_reset(&buf);
1654 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1655 if (!read_ref(buf.buf, &branch_oid)) {
1656 die_if_checked_out(buf.buf, 1);
1657 options.head_name = xstrdup(buf.buf);
1658 options.orig_head =
1659 lookup_commit_object(the_repository,
1660 &branch_oid);
1661 /* If not is it a valid ref (branch or commit)? */
1662 } else {
1663 options.orig_head =
1664 lookup_commit_reference_by_name(branch_name);
1665 options.head_name = NULL;
1667 if (!options.orig_head)
1668 die(_("no such branch/commit '%s'"), branch_name);
1669 } else if (argc == 0) {
1670 /* Do not need to switch branches, we are already on it. */
1671 options.head_name =
1672 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1673 &flags));
1674 if (!options.head_name)
1675 die(_("No such ref: %s"), "HEAD");
1676 if (flags & REF_ISSYMREF) {
1677 if (!skip_prefix(options.head_name,
1678 "refs/heads/", &branch_name))
1679 branch_name = options.head_name;
1681 } else {
1682 FREE_AND_NULL(options.head_name);
1683 branch_name = "HEAD";
1685 options.orig_head = lookup_commit_reference_by_name("HEAD");
1686 if (!options.orig_head)
1687 die(_("Could not resolve HEAD to a commit"));
1688 } else
1689 BUG("unexpected number of arguments left to parse");
1691 /* Make sure the branch to rebase onto is valid. */
1692 if (keep_base) {
1693 strbuf_reset(&buf);
1694 strbuf_addstr(&buf, options.upstream_name);
1695 strbuf_addstr(&buf, "...");
1696 strbuf_addstr(&buf, branch_name);
1697 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1698 } else if (!options.onto_name)
1699 options.onto_name = options.upstream_name;
1700 if (strstr(options.onto_name, "...")) {
1701 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1702 if (keep_base)
1703 die(_("'%s': need exactly one merge base with branch"),
1704 options.upstream_name);
1705 else
1706 die(_("'%s': need exactly one merge base"),
1707 options.onto_name);
1709 options.onto = lookup_commit_or_die(&branch_base,
1710 options.onto_name);
1711 } else {
1712 options.onto =
1713 lookup_commit_reference_by_name(options.onto_name);
1714 if (!options.onto)
1715 die(_("Does not point to a valid commit '%s'"),
1716 options.onto_name);
1717 fill_branch_base(&options, &branch_base);
1720 if (keep_base && options.reapply_cherry_picks)
1721 options.upstream = options.onto;
1723 if (options.fork_point > 0)
1724 options.restrict_revision =
1725 get_fork_point(options.upstream_name, options.orig_head);
1727 if (repo_read_index(the_repository) < 0)
1728 die(_("could not read index"));
1730 if (options.autostash)
1731 create_autostash(the_repository,
1732 state_dir_path("autostash", &options));
1735 if (require_clean_work_tree(the_repository, "rebase",
1736 _("Please commit or stash them."), 1, 1)) {
1737 ret = -1;
1738 goto cleanup;
1742 * Now we are rebasing commits upstream..orig_head (or with --root,
1743 * everything leading up to orig_head) on top of onto.
1747 * Check if we are already based on onto with linear history,
1748 * in which case we could fast-forward without replacing the commits
1749 * with new commits recreated by replaying their changes.
1751 if (allow_preemptive_ff &&
1752 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1753 options.orig_head, &branch_base)) {
1754 int flag;
1756 if (!(options.flags & REBASE_FORCE)) {
1757 /* Lazily switch to the target branch if needed... */
1758 if (options.switch_to) {
1759 ret = checkout_up_to_date(&options);
1760 if (ret)
1761 goto cleanup;
1764 if (!(options.flags & REBASE_NO_QUIET))
1765 ; /* be quiet */
1766 else if (!strcmp(branch_name, "HEAD") &&
1767 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1768 puts(_("HEAD is up to date."));
1769 else
1770 printf(_("Current branch %s is up to date.\n"),
1771 branch_name);
1772 ret = finish_rebase(&options);
1773 goto cleanup;
1774 } else if (!(options.flags & REBASE_NO_QUIET))
1775 ; /* be quiet */
1776 else if (!strcmp(branch_name, "HEAD") &&
1777 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1778 puts(_("HEAD is up to date, rebase forced."));
1779 else
1780 printf(_("Current branch %s is up to date, rebase "
1781 "forced.\n"), branch_name);
1784 /* If a hook exists, give it a chance to interrupt*/
1785 if (!ok_to_skip_pre_rebase &&
1786 run_hooks_l("pre-rebase", options.upstream_arg,
1787 argc ? argv[0] : NULL, NULL))
1788 die(_("The pre-rebase hook refused to rebase."));
1790 if (options.flags & REBASE_DIFFSTAT) {
1791 struct diff_options opts;
1793 if (options.flags & REBASE_VERBOSE) {
1794 if (is_null_oid(&branch_base))
1795 printf(_("Changes to %s:\n"),
1796 oid_to_hex(&options.onto->object.oid));
1797 else
1798 printf(_("Changes from %s to %s:\n"),
1799 oid_to_hex(&branch_base),
1800 oid_to_hex(&options.onto->object.oid));
1803 /* We want color (if set), but no pager */
1804 repo_diff_setup(the_repository, &opts);
1805 opts.stat_width = -1; /* use full terminal width */
1806 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1807 opts.output_format |=
1808 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1809 opts.detect_rename = DIFF_DETECT_RENAME;
1810 diff_setup_done(&opts);
1811 diff_tree_oid(is_null_oid(&branch_base) ?
1812 the_hash_algo->empty_tree : &branch_base,
1813 &options.onto->object.oid, "", &opts);
1814 diffcore_std(&opts);
1815 diff_flush(&opts);
1818 if (is_merge(&options))
1819 goto run_rebase;
1821 /* Detach HEAD and reset the tree */
1822 if (options.flags & REBASE_NO_QUIET)
1823 printf(_("First, rewinding head to replay your work on top of "
1824 "it...\n"));
1826 strbuf_addf(&msg, "%s (start): checkout %s",
1827 options.reflog_action, options.onto_name);
1828 ropts.oid = &options.onto->object.oid;
1829 ropts.orig_head = &options.orig_head->object.oid,
1830 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1831 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1832 ropts.head_msg = msg.buf;
1833 ropts.default_reflog_action = options.reflog_action;
1834 if (reset_head(the_repository, &ropts))
1835 die(_("Could not detach HEAD"));
1836 strbuf_release(&msg);
1839 * If the onto is a proper descendant of the tip of the branch, then
1840 * we just fast-forwarded.
1842 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1843 printf(_("Fast-forwarded %s to %s.\n"),
1844 branch_name, options.onto_name);
1845 move_to_original_branch(&options);
1846 ret = finish_rebase(&options);
1847 goto cleanup;
1850 strbuf_addf(&revisions, "%s..%s",
1851 options.root ? oid_to_hex(&options.onto->object.oid) :
1852 (options.restrict_revision ?
1853 oid_to_hex(&options.restrict_revision->object.oid) :
1854 oid_to_hex(&options.upstream->object.oid)),
1855 oid_to_hex(&options.orig_head->object.oid));
1857 options.revisions = revisions.buf;
1859 run_rebase:
1860 ret = run_specific_rebase(&options);
1862 cleanup:
1863 strbuf_release(&buf);
1864 strbuf_release(&revisions);
1865 free(options.reflog_action);
1866 free(options.head_name);
1867 strvec_clear(&options.git_am_opts);
1868 free(options.gpg_sign_opt);
1869 string_list_clear(&options.exec, 0);
1870 free(options.strategy);
1871 string_list_clear(&options.strategy_opts, 0);
1872 strbuf_release(&options.git_format_patch_opt);
1873 free(squash_onto_name);
1874 free(keep_base_onto_name);
1875 return !!ret;