The eighteenth batch
[git.git] / builtin / rebase.c
bloba2c96c080e1526f6fb279bd8eb76c2f277073e3d
1 /*
2 * "git rebase" builtin command
4 * Copyright (c) 2018 Pratik Karki
5 */
7 #include "builtin.h"
8 #include "abspath.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "run-command.h"
13 #include "strvec.h"
14 #include "dir.h"
15 #include "refs.h"
16 #include "config.h"
17 #include "unpack-trees.h"
18 #include "lockfile.h"
19 #include "object-file.h"
20 #include "object-name.h"
21 #include "parse-options.h"
22 #include "path.h"
23 #include "commit.h"
24 #include "diff.h"
25 #include "wt-status.h"
26 #include "revision.h"
27 #include "commit-reach.h"
28 #include "rerere.h"
29 #include "branch.h"
30 #include "sequencer.h"
31 #include "rebase-interactive.h"
32 #include "reset.h"
33 #include "trace2.h"
34 #include "hook.h"
36 static char const * const builtin_rebase_usage[] = {
37 N_("git rebase [-i] [options] [--exec <cmd>] "
38 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
39 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
40 "--root [<branch>]"),
41 "git rebase --continue | --abort | --skip | --edit-todo",
42 NULL
45 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
46 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
47 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
48 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
50 enum rebase_type {
51 REBASE_UNSPECIFIED = -1,
52 REBASE_APPLY,
53 REBASE_MERGE
56 enum empty_type {
57 EMPTY_UNSPECIFIED = -1,
58 EMPTY_DROP,
59 EMPTY_KEEP,
60 EMPTY_STOP
63 enum action {
64 ACTION_NONE = 0,
65 ACTION_CONTINUE,
66 ACTION_SKIP,
67 ACTION_ABORT,
68 ACTION_QUIT,
69 ACTION_EDIT_TODO,
70 ACTION_SHOW_CURRENT_PATCH
73 static const char *action_names[] = {
74 "undefined",
75 "continue",
76 "skip",
77 "abort",
78 "quit",
79 "edit_todo",
80 "show_current_patch"
83 struct rebase_options {
84 enum rebase_type type;
85 enum empty_type empty;
86 char *default_backend;
87 const char *state_dir;
88 struct commit *upstream;
89 const char *upstream_name;
90 const char *upstream_arg;
91 char *head_name;
92 struct commit *orig_head;
93 struct commit *onto;
94 const char *onto_name;
95 const char *revisions;
96 const char *switch_to;
97 int root, root_with_onto;
98 struct object_id *squash_onto;
99 struct commit *restrict_revision;
100 int dont_finish_rebase;
101 enum {
102 REBASE_NO_QUIET = 1<<0,
103 REBASE_VERBOSE = 1<<1,
104 REBASE_DIFFSTAT = 1<<2,
105 REBASE_FORCE = 1<<3,
106 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
107 } flags;
108 struct strvec git_am_opts;
109 enum action action;
110 char *reflog_action;
111 int signoff;
112 int allow_rerere_autoupdate;
113 int keep_empty;
114 int autosquash;
115 char *gpg_sign_opt;
116 int autostash;
117 int committer_date_is_author_date;
118 int ignore_date;
119 struct string_list exec;
120 int allow_empty_message;
121 int rebase_merges, rebase_cousins;
122 char *strategy;
123 struct string_list strategy_opts;
124 struct strbuf git_format_patch_opt;
125 int reschedule_failed_exec;
126 int reapply_cherry_picks;
127 int fork_point;
128 int update_refs;
129 int config_autosquash;
130 int config_rebase_merges;
131 int config_update_refs;
134 #define REBASE_OPTIONS_INIT { \
135 .type = REBASE_UNSPECIFIED, \
136 .empty = EMPTY_UNSPECIFIED, \
137 .keep_empty = 1, \
138 .default_backend = xstrdup("merge"), \
139 .flags = REBASE_NO_QUIET, \
140 .git_am_opts = STRVEC_INIT, \
141 .exec = STRING_LIST_INIT_NODUP, \
142 .git_format_patch_opt = STRBUF_INIT, \
143 .fork_point = -1, \
144 .reapply_cherry_picks = -1, \
145 .allow_empty_message = 1, \
146 .autosquash = -1, \
147 .rebase_merges = -1, \
148 .config_rebase_merges = -1, \
149 .update_refs = -1, \
150 .config_update_refs = -1, \
151 .strategy_opts = STRING_LIST_INIT_NODUP,\
154 static void rebase_options_release(struct rebase_options *opts)
156 free(opts->default_backend);
157 free(opts->reflog_action);
158 free(opts->head_name);
159 strvec_clear(&opts->git_am_opts);
160 free(opts->gpg_sign_opt);
161 string_list_clear(&opts->exec, 0);
162 free(opts->strategy);
163 string_list_clear(&opts->strategy_opts, 0);
164 strbuf_release(&opts->git_format_patch_opt);
167 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
169 struct replay_opts replay = REPLAY_OPTS_INIT;
171 replay.action = REPLAY_INTERACTIVE_REBASE;
172 replay.strategy = NULL;
173 sequencer_init_config(&replay);
175 replay.signoff = opts->signoff;
176 replay.allow_ff = !(opts->flags & REBASE_FORCE);
177 if (opts->allow_rerere_autoupdate)
178 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
179 replay.allow_empty = 1;
180 replay.allow_empty_message = opts->allow_empty_message;
181 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
182 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
183 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
184 replay.verbose = opts->flags & REBASE_VERBOSE;
185 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
186 replay.committer_date_is_author_date =
187 opts->committer_date_is_author_date;
188 replay.ignore_date = opts->ignore_date;
189 free(replay.gpg_sign);
190 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
191 replay.reflog_action = xstrdup(opts->reflog_action);
192 if (opts->strategy)
193 replay.strategy = xstrdup_or_null(opts->strategy);
194 else if (!replay.strategy && replay.default_strategy) {
195 replay.strategy = replay.default_strategy;
196 replay.default_strategy = NULL;
199 for (size_t i = 0; i < opts->strategy_opts.nr; i++)
200 strvec_push(&replay.xopts, opts->strategy_opts.items[i].string);
202 if (opts->squash_onto) {
203 oidcpy(&replay.squash_onto, opts->squash_onto);
204 replay.have_squash_onto = 1;
207 return replay;
210 static int edit_todo_file(unsigned flags, struct replay_opts *opts)
212 const char *todo_file = rebase_path_todo();
213 struct todo_list todo_list = TODO_LIST_INIT,
214 new_todo = TODO_LIST_INIT;
215 int res = 0;
217 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
218 return error_errno(_("could not read '%s'."), todo_file);
220 strbuf_stripspace(&todo_list.buf, comment_line_str);
221 res = edit_todo_list(the_repository, opts, &todo_list, &new_todo,
222 NULL, NULL, flags);
223 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
224 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
225 res = error_errno(_("could not write '%s'"), todo_file);
227 todo_list_release(&todo_list);
228 todo_list_release(&new_todo);
230 return res;
233 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
234 struct object_id *orig_head, char **revisions,
235 char **shortrevisions)
237 struct commit *base_rev = upstream ? upstream : onto;
238 const char *shorthead;
240 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
241 oid_to_hex(orig_head));
243 shorthead = repo_find_unique_abbrev(the_repository, orig_head,
244 DEFAULT_ABBREV);
246 if (upstream) {
247 const char *shortrev;
249 shortrev = repo_find_unique_abbrev(the_repository,
250 &base_rev->object.oid,
251 DEFAULT_ABBREV);
253 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
254 } else
255 *shortrevisions = xstrdup(shorthead);
257 return 0;
260 static int init_basic_state(struct replay_opts *opts, const char *head_name,
261 struct commit *onto,
262 const struct object_id *orig_head)
264 FILE *interactive;
266 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
267 return error_errno(_("could not create temporary %s"), merge_dir());
269 refs_delete_reflog(get_main_ref_store(the_repository), "REBASE_HEAD");
271 interactive = fopen(path_interactive(), "w");
272 if (!interactive)
273 return error_errno(_("could not mark as interactive"));
274 fclose(interactive);
276 return write_basic_state(opts, head_name, onto, orig_head);
279 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
281 int ret = -1;
282 char *revisions = NULL, *shortrevisions = NULL;
283 struct strvec make_script_args = STRVEC_INIT;
284 struct todo_list todo_list = TODO_LIST_INIT;
285 struct replay_opts replay = get_replay_opts(opts);
287 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
288 &revisions, &shortrevisions))
289 goto cleanup;
291 if (init_basic_state(&replay,
292 opts->head_name ? opts->head_name : "detached HEAD",
293 opts->onto, &opts->orig_head->object.oid))
294 goto cleanup;
296 if (!opts->upstream && opts->squash_onto)
297 write_file(path_squash_onto(), "%s\n",
298 oid_to_hex(opts->squash_onto));
300 strvec_pushl(&make_script_args, "", revisions, NULL);
301 if (opts->restrict_revision)
302 strvec_pushf(&make_script_args, "^%s",
303 oid_to_hex(&opts->restrict_revision->object.oid));
305 ret = sequencer_make_script(the_repository, &todo_list.buf,
306 make_script_args.nr, make_script_args.v,
307 flags);
309 if (ret)
310 error(_("could not generate todo list"));
311 else {
312 discard_index(the_repository->index);
313 if (todo_list_parse_insn_buffer(the_repository, &replay,
314 todo_list.buf.buf, &todo_list))
315 BUG("unusable todo list");
317 ret = complete_action(the_repository, &replay, flags,
318 shortrevisions, opts->onto_name, opts->onto,
319 &opts->orig_head->object.oid, &opts->exec,
320 opts->autosquash, opts->update_refs, &todo_list);
323 cleanup:
324 replay_opts_release(&replay);
325 free(revisions);
326 free(shortrevisions);
327 todo_list_release(&todo_list);
328 strvec_clear(&make_script_args);
330 return ret;
333 static int run_sequencer_rebase(struct rebase_options *opts)
335 unsigned flags = 0;
336 int abbreviate_commands = 0, ret = 0;
338 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
340 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
341 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
342 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
343 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
344 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
345 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
346 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
348 switch (opts->action) {
349 case ACTION_NONE: {
350 if (!opts->onto && !opts->upstream)
351 die(_("a base commit must be provided with --upstream or --onto"));
353 ret = do_interactive_rebase(opts, flags);
354 break;
356 case ACTION_SKIP: {
357 struct string_list merge_rr = STRING_LIST_INIT_DUP;
359 rerere_clear(the_repository, &merge_rr);
361 /* fallthrough */
362 case ACTION_CONTINUE: {
363 struct replay_opts replay_opts = get_replay_opts(opts);
365 ret = sequencer_continue(the_repository, &replay_opts);
366 replay_opts_release(&replay_opts);
367 break;
369 case ACTION_EDIT_TODO: {
370 struct replay_opts replay_opts = get_replay_opts(opts);
372 ret = edit_todo_file(flags, &replay_opts);
373 replay_opts_release(&replay_opts);
374 break;
376 case ACTION_SHOW_CURRENT_PATCH: {
377 struct child_process cmd = CHILD_PROCESS_INIT;
379 cmd.git_cmd = 1;
380 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
381 ret = run_command(&cmd);
383 break;
385 default:
386 BUG("invalid command '%d'", opts->action);
389 return ret;
392 static int is_merge(struct rebase_options *opts)
394 return opts->type == REBASE_MERGE;
397 static void imply_merge(struct rebase_options *opts, const char *option)
399 switch (opts->type) {
400 case REBASE_APPLY:
401 die(_("%s requires the merge backend"), option);
402 break;
403 case REBASE_MERGE:
404 break;
405 default:
406 opts->type = REBASE_MERGE; /* implied */
407 break;
411 /* Returns the filename prefixed by the state_dir */
412 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
414 static struct strbuf path = STRBUF_INIT;
415 static size_t prefix_len;
417 if (!prefix_len) {
418 strbuf_addf(&path, "%s/", opts->state_dir);
419 prefix_len = path.len;
422 strbuf_setlen(&path, prefix_len);
423 strbuf_addstr(&path, filename);
424 return path.buf;
427 /* Initialize the rebase options from the state directory. */
428 static int read_basic_state(struct rebase_options *opts)
430 struct strbuf head_name = STRBUF_INIT;
431 struct strbuf buf = STRBUF_INIT;
432 struct object_id oid;
434 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
435 READ_ONELINER_WARN_MISSING) ||
436 !read_oneliner(&buf, state_dir_path("onto", opts),
437 READ_ONELINER_WARN_MISSING))
438 return -1;
439 opts->head_name = starts_with(head_name.buf, "refs/") ?
440 xstrdup(head_name.buf) : NULL;
441 strbuf_release(&head_name);
442 if (get_oid_hex(buf.buf, &oid) ||
443 !(opts->onto = lookup_commit_object(the_repository, &oid)))
444 return error(_("invalid onto: '%s'"), buf.buf);
447 * We always write to orig-head, but interactive rebase used to write to
448 * head. Fall back to reading from head to cover for the case that the
449 * user upgraded git with an ongoing interactive rebase.
451 strbuf_reset(&buf);
452 if (file_exists(state_dir_path("orig-head", opts))) {
453 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
454 READ_ONELINER_WARN_MISSING))
455 return -1;
456 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
457 READ_ONELINER_WARN_MISSING))
458 return -1;
459 if (get_oid_hex(buf.buf, &oid) ||
460 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
461 return error(_("invalid orig-head: '%s'"), buf.buf);
463 if (file_exists(state_dir_path("quiet", opts)))
464 opts->flags &= ~REBASE_NO_QUIET;
465 else
466 opts->flags |= REBASE_NO_QUIET;
468 if (file_exists(state_dir_path("verbose", opts)))
469 opts->flags |= REBASE_VERBOSE;
471 if (file_exists(state_dir_path("signoff", opts))) {
472 opts->signoff = 1;
473 opts->flags |= REBASE_FORCE;
476 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
477 strbuf_reset(&buf);
478 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
479 READ_ONELINER_WARN_MISSING))
480 return -1;
481 if (!strcmp(buf.buf, "--rerere-autoupdate"))
482 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
483 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
484 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
485 else
486 warning(_("ignoring invalid allow_rerere_autoupdate: "
487 "'%s'"), buf.buf);
490 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
491 strbuf_reset(&buf);
492 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
493 READ_ONELINER_WARN_MISSING))
494 return -1;
495 free(opts->gpg_sign_opt);
496 opts->gpg_sign_opt = xstrdup(buf.buf);
499 strbuf_release(&buf);
501 return 0;
504 static int rebase_write_basic_state(struct rebase_options *opts)
506 write_file(state_dir_path("head-name", opts), "%s",
507 opts->head_name ? opts->head_name : "detached HEAD");
508 write_file(state_dir_path("onto", opts), "%s",
509 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
510 write_file(state_dir_path("orig-head", opts), "%s",
511 oid_to_hex(&opts->orig_head->object.oid));
512 if (!(opts->flags & REBASE_NO_QUIET))
513 write_file(state_dir_path("quiet", opts), "%s", "");
514 if (opts->flags & REBASE_VERBOSE)
515 write_file(state_dir_path("verbose", opts), "%s", "");
516 if (opts->allow_rerere_autoupdate > 0)
517 write_file(state_dir_path("allow_rerere_autoupdate", opts),
518 "-%s-rerere-autoupdate",
519 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
520 "" : "-no");
521 if (opts->gpg_sign_opt)
522 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
523 opts->gpg_sign_opt);
524 if (opts->signoff)
525 write_file(state_dir_path("signoff", opts), "--signoff");
527 return 0;
530 static int finish_rebase(struct rebase_options *opts)
532 struct strbuf dir = STRBUF_INIT;
533 int ret = 0;
535 refs_delete_ref(get_main_ref_store(the_repository), NULL,
536 "REBASE_HEAD", NULL, REF_NO_DEREF);
537 refs_delete_ref(get_main_ref_store(the_repository), NULL,
538 "AUTO_MERGE", NULL, REF_NO_DEREF);
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 int run_am(struct rebase_options *opts)
592 struct child_process am = CHILD_PROCESS_INIT;
593 struct child_process format_patch = CHILD_PROCESS_INIT;
594 int status;
595 char *rebased_patches;
597 am.git_cmd = 1;
598 strvec_push(&am.args, "am");
599 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
600 opts->reflog_action);
601 if (opts->action == ACTION_CONTINUE) {
602 strvec_push(&am.args, "--resolved");
603 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
604 if (opts->gpg_sign_opt)
605 strvec_push(&am.args, opts->gpg_sign_opt);
606 status = run_command(&am);
607 if (status)
608 return status;
610 return move_to_original_branch(opts);
612 if (opts->action == ACTION_SKIP) {
613 strvec_push(&am.args, "--skip");
614 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
615 status = run_command(&am);
616 if (status)
617 return status;
619 return move_to_original_branch(opts);
621 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
622 strvec_push(&am.args, "--show-current-patch");
623 return run_command(&am);
626 rebased_patches = xstrdup(git_path("rebased-patches"));
627 format_patch.out = open(rebased_patches,
628 O_WRONLY | O_CREAT | O_TRUNC, 0666);
629 if (format_patch.out < 0) {
630 status = error_errno(_("could not open '%s' for writing"),
631 rebased_patches);
632 free(rebased_patches);
633 child_process_clear(&am);
634 return status;
637 format_patch.git_cmd = 1;
638 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
639 "--full-index", "--cherry-pick", "--right-only",
640 "--default-prefix", "--no-renames",
641 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
642 "--no-base", NULL);
643 if (opts->git_format_patch_opt.len)
644 strvec_split(&format_patch.args,
645 opts->git_format_patch_opt.buf);
646 strvec_pushf(&format_patch.args, "%s...%s",
647 oid_to_hex(opts->root ?
648 /* this is now equivalent to !opts->upstream */
649 &opts->onto->object.oid :
650 &opts->upstream->object.oid),
651 oid_to_hex(&opts->orig_head->object.oid));
652 if (opts->restrict_revision)
653 strvec_pushf(&format_patch.args, "^%s",
654 oid_to_hex(&opts->restrict_revision->object.oid));
656 status = run_command(&format_patch);
657 if (status) {
658 struct reset_head_opts ropts = { 0 };
659 unlink(rebased_patches);
660 free(rebased_patches);
661 child_process_clear(&am);
663 ropts.oid = &opts->orig_head->object.oid;
664 ropts.branch = opts->head_name;
665 ropts.default_reflog_action = opts->reflog_action;
666 reset_head(the_repository, &ropts);
667 error(_("\ngit encountered an error while preparing the "
668 "patches to replay\n"
669 "these revisions:\n"
670 "\n %s\n\n"
671 "As a result, git cannot rebase them."),
672 opts->revisions);
674 return status;
677 am.in = open(rebased_patches, O_RDONLY);
678 if (am.in < 0) {
679 status = error_errno(_("could not open '%s' for reading"),
680 rebased_patches);
681 free(rebased_patches);
682 child_process_clear(&am);
683 return status;
686 strvec_pushv(&am.args, opts->git_am_opts.v);
687 strvec_push(&am.args, "--rebasing");
688 strvec_pushf(&am.args, "--resolvemsg=%s", rebase_resolvemsg);
689 strvec_push(&am.args, "--patch-format=mboxrd");
690 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
691 strvec_push(&am.args, "--rerere-autoupdate");
692 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
693 strvec_push(&am.args, "--no-rerere-autoupdate");
694 if (opts->gpg_sign_opt)
695 strvec_push(&am.args, opts->gpg_sign_opt);
696 status = run_command(&am);
697 unlink(rebased_patches);
698 free(rebased_patches);
700 if (!status) {
701 return move_to_original_branch(opts);
704 if (is_directory(opts->state_dir))
705 rebase_write_basic_state(opts);
707 return status;
710 static int run_specific_rebase(struct rebase_options *opts)
712 int status;
714 if (opts->type == REBASE_MERGE) {
715 /* Run sequencer-based rebase */
716 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT))
717 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
718 if (opts->gpg_sign_opt) {
719 /* remove the leading "-S" */
720 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
721 free(opts->gpg_sign_opt);
722 opts->gpg_sign_opt = tmp;
725 status = run_sequencer_rebase(opts);
726 } else if (opts->type == REBASE_APPLY)
727 status = run_am(opts);
728 else
729 BUG("Unhandled rebase type %d", opts->type);
731 if (opts->dont_finish_rebase)
732 ; /* do nothing */
733 else if (opts->type == REBASE_MERGE)
734 ; /* merge backend cleans up after itself */
735 else if (status == 0) {
736 if (!file_exists(state_dir_path("stopped-sha", opts)))
737 finish_rebase(opts);
738 } else if (status == 2) {
739 struct strbuf dir = STRBUF_INIT;
741 apply_autostash(state_dir_path("autostash", opts));
742 strbuf_addstr(&dir, opts->state_dir);
743 remove_dir_recursively(&dir, 0);
744 strbuf_release(&dir);
745 die("Nothing to do");
748 return status ? -1 : 0;
751 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
753 if (!strcmp("no-rebase-cousins", value))
754 options->rebase_cousins = 0;
755 else if (!strcmp("rebase-cousins", value))
756 options->rebase_cousins = 1;
757 else
758 die(_("Unknown rebase-merges mode: %s"), value);
761 static int rebase_config(const char *var, const char *value,
762 const struct config_context *ctx, void *data)
764 struct rebase_options *opts = data;
766 if (!strcmp(var, "rebase.stat")) {
767 if (git_config_bool(var, value))
768 opts->flags |= REBASE_DIFFSTAT;
769 else
770 opts->flags &= ~REBASE_DIFFSTAT;
771 return 0;
774 if (!strcmp(var, "rebase.autosquash")) {
775 opts->config_autosquash = git_config_bool(var, value);
776 return 0;
779 if (!strcmp(var, "commit.gpgsign")) {
780 free(opts->gpg_sign_opt);
781 opts->gpg_sign_opt = git_config_bool(var, value) ?
782 xstrdup("-S") : NULL;
783 return 0;
786 if (!strcmp(var, "rebase.autostash")) {
787 opts->autostash = git_config_bool(var, value);
788 return 0;
791 if (!strcmp(var, "rebase.rebasemerges")) {
792 opts->config_rebase_merges = git_parse_maybe_bool(value);
793 if (opts->config_rebase_merges < 0) {
794 opts->config_rebase_merges = 1;
795 parse_rebase_merges_value(opts, value);
796 } else {
797 opts->rebase_cousins = 0;
799 return 0;
802 if (!strcmp(var, "rebase.updaterefs")) {
803 opts->config_update_refs = git_config_bool(var, value);
804 return 0;
807 if (!strcmp(var, "rebase.reschedulefailedexec")) {
808 opts->reschedule_failed_exec = git_config_bool(var, value);
809 return 0;
812 if (!strcmp(var, "rebase.forkpoint")) {
813 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
814 return 0;
817 if (!strcmp(var, "rebase.backend")) {
818 FREE_AND_NULL(opts->default_backend);
819 return git_config_string(&opts->default_backend, var, value);
822 return git_default_config(var, value, ctx, data);
825 static int checkout_up_to_date(struct rebase_options *options)
827 struct strbuf buf = STRBUF_INIT;
828 struct reset_head_opts ropts = { 0 };
829 int ret = 0;
831 strbuf_addf(&buf, "%s: checkout %s",
832 options->reflog_action, options->switch_to);
833 ropts.oid = &options->orig_head->object.oid;
834 ropts.branch = options->head_name;
835 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
836 if (!ropts.branch)
837 ropts.flags |= RESET_HEAD_DETACH;
838 ropts.head_msg = buf.buf;
839 if (reset_head(the_repository, &ropts) < 0)
840 ret = error(_("could not switch to %s"), options->switch_to);
841 strbuf_release(&buf);
843 return ret;
847 * Determines whether the commits in from..to are linear, i.e. contain
848 * no merge commits. This function *expects* `from` to be an ancestor of
849 * `to`.
851 static int is_linear_history(struct commit *from, struct commit *to)
853 while (to && to != from) {
854 repo_parse_commit(the_repository, to);
855 if (!to->parents)
856 return 1;
857 if (to->parents->next)
858 return 0;
859 to = to->parents->item;
861 return 1;
864 static int can_fast_forward(struct commit *onto, struct commit *upstream,
865 struct commit *restrict_revision,
866 struct commit *head, struct object_id *branch_base)
868 struct commit_list *merge_bases = NULL;
869 int res = 0;
871 if (is_null_oid(branch_base))
872 goto done; /* fill_branch_base() found multiple merge bases */
874 if (!oideq(branch_base, &onto->object.oid))
875 goto done;
877 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
878 goto done;
880 if (!upstream)
881 goto done;
883 if (repo_get_merge_bases(the_repository, upstream, head, &merge_bases) < 0)
884 exit(128);
885 if (!merge_bases || merge_bases->next)
886 goto done;
888 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
889 goto done;
891 res = 1;
893 done:
894 free_commit_list(merge_bases);
895 return res && is_linear_history(onto, head);
898 static void fill_branch_base(struct rebase_options *options,
899 struct object_id *branch_base)
901 struct commit_list *merge_bases = NULL;
903 if (repo_get_merge_bases(the_repository, options->onto,
904 options->orig_head, &merge_bases) < 0)
905 exit(128);
906 if (!merge_bases || merge_bases->next)
907 oidcpy(branch_base, null_oid());
908 else
909 oidcpy(branch_base, &merge_bases->item->object.oid);
911 free_commit_list(merge_bases);
914 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
916 struct rebase_options *opts = opt->value;
918 BUG_ON_OPT_NEG(unset);
919 BUG_ON_OPT_ARG(arg);
921 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
922 die(_("apply options and merge options cannot be used together"));
924 opts->type = REBASE_APPLY;
926 return 0;
929 /* -i followed by -m is still -i */
930 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
932 struct rebase_options *opts = opt->value;
934 BUG_ON_OPT_NEG(unset);
935 BUG_ON_OPT_ARG(arg);
937 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
938 die(_("apply options and merge options cannot be used together"));
940 opts->type = REBASE_MERGE;
942 return 0;
945 /* -i followed by -r is still explicitly interactive, but -r alone is not */
946 static int parse_opt_interactive(const struct option *opt, const char *arg,
947 int unset)
949 struct rebase_options *opts = opt->value;
951 BUG_ON_OPT_NEG(unset);
952 BUG_ON_OPT_ARG(arg);
954 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
955 die(_("apply options and merge options cannot be used together"));
957 opts->type = REBASE_MERGE;
958 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
960 return 0;
963 static enum empty_type parse_empty_value(const char *value)
965 if (!strcasecmp(value, "drop"))
966 return EMPTY_DROP;
967 else if (!strcasecmp(value, "keep"))
968 return EMPTY_KEEP;
969 else if (!strcasecmp(value, "stop"))
970 return EMPTY_STOP;
971 else if (!strcasecmp(value, "ask")) {
972 warning(_("--empty=ask is deprecated; use '--empty=stop' instead."));
973 return EMPTY_STOP;
976 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"stop\"."), value);
979 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
980 int unset)
982 struct rebase_options *opts = opt->value;
984 BUG_ON_OPT_ARG(arg);
986 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
987 opts->keep_empty = !unset;
988 return 0;
991 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
993 struct rebase_options *options = opt->value;
994 enum empty_type value = parse_empty_value(arg);
996 BUG_ON_OPT_NEG(unset);
998 options->empty = value;
999 return 0;
1002 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
1004 struct rebase_options *options = opt->value;
1006 options->rebase_merges = !unset;
1007 options->rebase_cousins = 0;
1009 if (arg) {
1010 if (!*arg) {
1011 warning(_("--rebase-merges with an empty string "
1012 "argument is deprecated and will stop "
1013 "working in a future version of Git. Use "
1014 "--rebase-merges without an argument "
1015 "instead, which does the same thing."));
1016 return 0;
1018 parse_rebase_merges_value(options, arg);
1021 return 0;
1024 static void NORETURN error_on_missing_default_upstream(void)
1026 struct branch *current_branch = branch_get(NULL);
1028 printf(_("%s\n"
1029 "Please specify which branch you want to rebase against.\n"
1030 "See git-rebase(1) for details.\n"
1031 "\n"
1032 " git rebase '<branch>'\n"
1033 "\n"),
1034 current_branch ? _("There is no tracking information for "
1035 "the current branch.") :
1036 _("You are not currently on a branch."));
1038 if (current_branch) {
1039 const char *remote = current_branch->remote_name;
1041 if (!remote)
1042 remote = _("<remote>");
1044 printf(_("If you wish to set tracking information for this "
1045 "branch you can do so with:\n"
1046 "\n"
1047 " git branch --set-upstream-to=%s/<branch> %s\n"
1048 "\n"),
1049 remote, current_branch->name);
1051 exit(1);
1054 static int check_exec_cmd(const char *cmd)
1056 if (strchr(cmd, '\n'))
1057 return error(_("exec commands cannot contain newlines"));
1059 /* Does the command consist purely of whitespace? */
1060 if (!cmd[strspn(cmd, " \t\r\f\v")])
1061 return error(_("empty exec command"));
1063 return 0;
1066 int cmd_rebase(int argc, const char **argv, const char *prefix)
1068 struct rebase_options options = REBASE_OPTIONS_INIT;
1069 const char *branch_name;
1070 const char *strategy_opt = NULL;
1071 int ret, flags, total_argc, in_progress = 0;
1072 int keep_base = 0;
1073 int ok_to_skip_pre_rebase = 0;
1074 struct strbuf msg = STRBUF_INIT;
1075 struct strbuf revisions = STRBUF_INIT;
1076 struct strbuf buf = STRBUF_INIT;
1077 struct object_id branch_base;
1078 int ignore_whitespace = 0;
1079 const char *gpg_sign = NULL;
1080 struct object_id squash_onto;
1081 char *squash_onto_name = NULL;
1082 char *keep_base_onto_name = NULL;
1083 int reschedule_failed_exec = -1;
1084 int allow_preemptive_ff = 1;
1085 int preserve_merges_selected = 0;
1086 struct reset_head_opts ropts = { 0 };
1087 struct option builtin_rebase_options[] = {
1088 OPT_STRING(0, "onto", &options.onto_name,
1089 N_("revision"),
1090 N_("rebase onto given branch instead of upstream")),
1091 OPT_BOOL(0, "keep-base", &keep_base,
1092 N_("use the merge-base of upstream and branch as the current base")),
1093 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1094 N_("allow pre-rebase hook to run")),
1095 OPT_NEGBIT('q', "quiet", &options.flags,
1096 N_("be quiet. implies --no-stat"),
1097 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1098 OPT_BIT('v', "verbose", &options.flags,
1099 N_("display a diffstat of what changed upstream"),
1100 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1101 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1102 N_("do not show diffstat of what changed upstream"),
1103 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1104 OPT_BOOL(0, "signoff", &options.signoff,
1105 N_("add a Signed-off-by trailer to each commit")),
1106 OPT_BOOL(0, "committer-date-is-author-date",
1107 &options.committer_date_is_author_date,
1108 N_("make committer date match author date")),
1109 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1110 N_("ignore author date and use current date")),
1111 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1112 N_("synonym of --reset-author-date")),
1113 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1114 N_("passed to 'git apply'"), 0),
1115 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1116 N_("ignore changes in whitespace")),
1117 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1118 N_("action"), N_("passed to 'git apply'"), 0),
1119 OPT_BIT('f', "force-rebase", &options.flags,
1120 N_("cherry-pick all commits, even if unchanged"),
1121 REBASE_FORCE),
1122 OPT_BIT(0, "no-ff", &options.flags,
1123 N_("cherry-pick all commits, even if unchanged"),
1124 REBASE_FORCE),
1125 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1126 ACTION_CONTINUE),
1127 OPT_CMDMODE(0, "skip", &options.action,
1128 N_("skip current patch and continue"), ACTION_SKIP),
1129 OPT_CMDMODE(0, "abort", &options.action,
1130 N_("abort and check out the original branch"),
1131 ACTION_ABORT),
1132 OPT_CMDMODE(0, "quit", &options.action,
1133 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1134 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1135 "during an interactive rebase"), ACTION_EDIT_TODO),
1136 OPT_CMDMODE(0, "show-current-patch", &options.action,
1137 N_("show the patch file being applied or merged"),
1138 ACTION_SHOW_CURRENT_PATCH),
1139 OPT_CALLBACK_F(0, "apply", &options, NULL,
1140 N_("use apply strategies to rebase"),
1141 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1142 parse_opt_am),
1143 OPT_CALLBACK_F('m', "merge", &options, NULL,
1144 N_("use merging strategies to rebase"),
1145 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1146 parse_opt_merge),
1147 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1148 N_("let the user edit the list of commits to rebase"),
1149 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1150 parse_opt_interactive),
1151 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1152 N_("(REMOVED) was: try to recreate merges "
1153 "instead of ignoring them"),
1154 1, PARSE_OPT_HIDDEN),
1155 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1156 OPT_CALLBACK_F(0, "empty", &options, "(drop|keep|stop)",
1157 N_("how to handle commits that become empty"),
1158 PARSE_OPT_NONEG, parse_opt_empty),
1159 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1160 N_("keep commits which start empty"),
1161 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1162 parse_opt_keep_empty),
1163 OPT_BOOL(0, "autosquash", &options.autosquash,
1164 N_("move commits that begin with "
1165 "squash!/fixup! under -i")),
1166 OPT_BOOL(0, "update-refs", &options.update_refs,
1167 N_("update branches that point to commits "
1168 "that are being rebased")),
1169 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1170 N_("GPG-sign commits"),
1171 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1172 OPT_AUTOSTASH(&options.autostash),
1173 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1174 N_("add exec lines after each commit of the "
1175 "editable list")),
1176 OPT_BOOL_F(0, "allow-empty-message",
1177 &options.allow_empty_message,
1178 N_("allow rebasing commits with empty messages"),
1179 PARSE_OPT_HIDDEN),
1180 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1181 N_("try to rebase merges instead of skipping them"),
1182 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1183 OPT_BOOL(0, "fork-point", &options.fork_point,
1184 N_("use 'merge-base --fork-point' to refine upstream")),
1185 OPT_STRING('s', "strategy", &strategy_opt,
1186 N_("strategy"), N_("use the given merge strategy")),
1187 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1188 N_("option"),
1189 N_("pass the argument through to the merge "
1190 "strategy")),
1191 OPT_BOOL(0, "root", &options.root,
1192 N_("rebase all reachable commits up to the root(s)")),
1193 OPT_BOOL(0, "reschedule-failed-exec",
1194 &reschedule_failed_exec,
1195 N_("automatically re-schedule any `exec` that fails")),
1196 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1197 N_("apply all changes, even those already present upstream")),
1198 OPT_END(),
1200 int i;
1202 if (argc == 2 && !strcmp(argv[1], "-h"))
1203 usage_with_options(builtin_rebase_usage,
1204 builtin_rebase_options);
1206 prepare_repo_settings(the_repository);
1207 the_repository->settings.command_requires_full_index = 0;
1209 git_config(rebase_config, &options);
1210 /* options.gpg_sign_opt will be either "-S" or NULL */
1211 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1212 FREE_AND_NULL(options.gpg_sign_opt);
1214 strbuf_reset(&buf);
1215 strbuf_addf(&buf, "%s/applying", apply_dir());
1216 if(file_exists(buf.buf))
1217 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1219 if (is_directory(apply_dir())) {
1220 options.type = REBASE_APPLY;
1221 options.state_dir = apply_dir();
1222 } else if (is_directory(merge_dir())) {
1223 strbuf_reset(&buf);
1224 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1225 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1226 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1227 "Use `git rebase --abort` to terminate current rebase.\n"
1228 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1229 } else {
1230 strbuf_reset(&buf);
1231 strbuf_addf(&buf, "%s/interactive", merge_dir());
1232 options.type = REBASE_MERGE;
1233 if (file_exists(buf.buf))
1234 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1236 options.state_dir = merge_dir();
1239 if (options.type != REBASE_UNSPECIFIED)
1240 in_progress = 1;
1242 total_argc = argc;
1243 argc = parse_options(argc, argv, prefix,
1244 builtin_rebase_options,
1245 builtin_rebase_usage, 0);
1247 if (preserve_merges_selected)
1248 die(_("--preserve-merges was replaced by --rebase-merges\n"
1249 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1250 "which is no longer supported; use 'merges' instead"));
1252 if (options.action != ACTION_NONE && total_argc != 2) {
1253 usage_with_options(builtin_rebase_usage,
1254 builtin_rebase_options);
1257 if (argc > 2)
1258 usage_with_options(builtin_rebase_usage,
1259 builtin_rebase_options);
1261 if (keep_base) {
1262 if (options.onto_name)
1263 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1264 if (options.root)
1265 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1267 * --keep-base defaults to --no-fork-point to keep the
1268 * base the same.
1270 if (options.fork_point < 0)
1271 options.fork_point = 0;
1273 if (options.root && options.fork_point > 0)
1274 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1276 if (options.action != ACTION_NONE && !in_progress)
1277 die(_("no rebase in progress"));
1279 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1280 die(_("The --edit-todo action can only be used during "
1281 "interactive rebase."));
1283 if (trace2_is_enabled()) {
1284 if (is_merge(&options))
1285 trace2_cmd_mode("interactive");
1286 else if (options.exec.nr)
1287 trace2_cmd_mode("interactive-exec");
1288 else
1289 trace2_cmd_mode(action_names[options.action]);
1292 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1293 options.reflog_action =
1294 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1296 switch (options.action) {
1297 case ACTION_CONTINUE: {
1298 struct object_id head;
1299 struct lock_file lock_file = LOCK_INIT;
1300 int fd;
1302 /* Sanity check */
1303 if (repo_get_oid(the_repository, "HEAD", &head))
1304 die(_("Cannot read HEAD"));
1306 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1307 if (repo_read_index(the_repository) < 0)
1308 die(_("could not read index"));
1309 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1310 NULL);
1311 if (0 <= fd)
1312 repo_update_index_if_able(the_repository, &lock_file);
1313 rollback_lock_file(&lock_file);
1315 if (has_unstaged_changes(the_repository, 1)) {
1316 puts(_("You must edit all merge conflicts and then\n"
1317 "mark them as resolved using git add"));
1318 exit(1);
1320 if (read_basic_state(&options))
1321 exit(1);
1322 goto run_rebase;
1324 case ACTION_SKIP: {
1325 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1327 rerere_clear(the_repository, &merge_rr);
1328 string_list_clear(&merge_rr, 1);
1329 ropts.flags = RESET_HEAD_HARD;
1330 if (reset_head(the_repository, &ropts) < 0)
1331 die(_("could not discard worktree changes"));
1332 remove_branch_state(the_repository, 0);
1333 if (read_basic_state(&options))
1334 exit(1);
1335 goto run_rebase;
1337 case ACTION_ABORT: {
1338 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1339 struct strbuf head_msg = STRBUF_INIT;
1341 rerere_clear(the_repository, &merge_rr);
1342 string_list_clear(&merge_rr, 1);
1344 if (read_basic_state(&options))
1345 exit(1);
1347 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1348 options.reflog_action,
1349 options.head_name ? options.head_name
1350 : oid_to_hex(&options.orig_head->object.oid));
1351 ropts.oid = &options.orig_head->object.oid;
1352 ropts.head_msg = head_msg.buf;
1353 ropts.branch = options.head_name;
1354 ropts.flags = RESET_HEAD_HARD;
1355 if (reset_head(the_repository, &ropts) < 0)
1356 die(_("could not move back to %s"),
1357 oid_to_hex(&options.orig_head->object.oid));
1358 strbuf_release(&head_msg);
1359 remove_branch_state(the_repository, 0);
1360 ret = finish_rebase(&options);
1361 goto cleanup;
1363 case ACTION_QUIT: {
1364 save_autostash(state_dir_path("autostash", &options));
1365 if (options.type == REBASE_MERGE) {
1366 struct replay_opts replay = REPLAY_OPTS_INIT;
1368 replay.action = REPLAY_INTERACTIVE_REBASE;
1369 ret = sequencer_remove_state(&replay);
1370 replay_opts_release(&replay);
1371 } else {
1372 strbuf_reset(&buf);
1373 strbuf_addstr(&buf, options.state_dir);
1374 ret = remove_dir_recursively(&buf, 0);
1375 if (ret)
1376 error(_("could not remove '%s'"),
1377 options.state_dir);
1379 goto cleanup;
1381 case ACTION_EDIT_TODO:
1382 options.dont_finish_rebase = 1;
1383 goto run_rebase;
1384 case ACTION_SHOW_CURRENT_PATCH:
1385 options.dont_finish_rebase = 1;
1386 goto run_rebase;
1387 case ACTION_NONE:
1388 break;
1389 default:
1390 BUG("action: %d", options.action);
1393 /* Make sure no rebase is in progress */
1394 if (in_progress) {
1395 const char *last_slash = strrchr(options.state_dir, '/');
1396 const char *state_dir_base =
1397 last_slash ? last_slash + 1 : options.state_dir;
1398 const char *cmd_live_rebase =
1399 "git rebase (--continue | --abort | --skip)";
1400 strbuf_reset(&buf);
1401 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1402 die(_("It seems that there is already a %s directory, and\n"
1403 "I wonder if you are in the middle of another rebase. "
1404 "If that is the\n"
1405 "case, please try\n\t%s\n"
1406 "If that is not the case, please\n\t%s\n"
1407 "and run me again. I am stopping in case you still "
1408 "have something\n"
1409 "valuable there.\n"),
1410 state_dir_base, cmd_live_rebase, buf.buf);
1413 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1414 (options.action != ACTION_NONE) ||
1415 (options.exec.nr > 0) ||
1416 options.autosquash == 1) {
1417 allow_preemptive_ff = 0;
1419 if (options.committer_date_is_author_date || options.ignore_date)
1420 options.flags |= REBASE_FORCE;
1422 for (i = 0; i < options.git_am_opts.nr; i++) {
1423 const char *option = options.git_am_opts.v[i], *p;
1424 if (!strcmp(option, "--whitespace=fix") ||
1425 !strcmp(option, "--whitespace=strip"))
1426 allow_preemptive_ff = 0;
1427 else if (skip_prefix(option, "-C", &p)) {
1428 while (*p)
1429 if (!isdigit(*(p++)))
1430 die(_("switch `C' expects a "
1431 "numerical value"));
1432 } else if (skip_prefix(option, "--whitespace=", &p)) {
1433 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1434 strcmp(p, "error") && strcmp(p, "error-all"))
1435 die("Invalid whitespace option: '%s'", p);
1439 for (i = 0; i < options.exec.nr; i++)
1440 if (check_exec_cmd(options.exec.items[i].string))
1441 exit(1);
1443 if (!(options.flags & REBASE_NO_QUIET))
1444 strvec_push(&options.git_am_opts, "-q");
1446 if (options.empty != EMPTY_UNSPECIFIED)
1447 imply_merge(&options, "--empty");
1449 if (options.reapply_cherry_picks < 0)
1451 * We default to --no-reapply-cherry-picks unless
1452 * --keep-base is given; when --keep-base is given, we want
1453 * to default to --reapply-cherry-picks.
1455 options.reapply_cherry_picks = keep_base;
1456 else if (!keep_base)
1458 * The apply backend always searches for and drops cherry
1459 * picks. This is often not wanted with --keep-base, so
1460 * --keep-base allows --reapply-cherry-picks to be
1461 * simulated by altering the upstream such that
1462 * cherry-picks cannot be detected and thus all commits are
1463 * reapplied. Thus, --[no-]reapply-cherry-picks is
1464 * supported when --keep-base is specified, but not when
1465 * --keep-base is left out.
1467 imply_merge(&options, options.reapply_cherry_picks ?
1468 "--reapply-cherry-picks" :
1469 "--no-reapply-cherry-picks");
1471 if (gpg_sign)
1472 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1474 if (options.exec.nr)
1475 imply_merge(&options, "--exec");
1477 if (options.type == REBASE_APPLY) {
1478 if (ignore_whitespace)
1479 strvec_push(&options.git_am_opts,
1480 "--ignore-whitespace");
1481 if (options.committer_date_is_author_date)
1482 strvec_push(&options.git_am_opts,
1483 "--committer-date-is-author-date");
1484 if (options.ignore_date)
1485 strvec_push(&options.git_am_opts, "--ignore-date");
1486 } else {
1487 /* REBASE_MERGE */
1488 if (ignore_whitespace) {
1489 string_list_append(&options.strategy_opts,
1490 "ignore-space-change");
1494 if (strategy_opt)
1495 options.strategy = xstrdup(strategy_opt);
1496 else if (options.strategy_opts.nr && !options.strategy)
1497 options.strategy = xstrdup("ort");
1498 if (options.strategy)
1499 imply_merge(&options, "--strategy");
1501 if (options.root && !options.onto_name)
1502 imply_merge(&options, "--root without --onto");
1504 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1505 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1507 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1508 /* all am options except -q are compatible only with --apply */
1509 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1510 if (strcmp(options.git_am_opts.v[i], "-q"))
1511 break;
1513 if (i >= 0 || options.type == REBASE_APPLY) {
1514 if (is_merge(&options))
1515 die(_("apply options and merge options "
1516 "cannot be used together"));
1517 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1518 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1519 else if (options.update_refs == -1 && options.config_update_refs == 1)
1520 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1521 else
1522 options.type = REBASE_APPLY;
1526 if (options.update_refs == 1)
1527 imply_merge(&options, "--update-refs");
1528 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1529 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1531 if (options.rebase_merges == 1)
1532 imply_merge(&options, "--rebase-merges");
1533 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1534 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1536 if (options.autosquash == 1) {
1537 imply_merge(&options, "--autosquash");
1538 } else if (options.autosquash == -1) {
1539 options.autosquash =
1540 options.config_autosquash &&
1541 (options.flags & REBASE_INTERACTIVE_EXPLICIT);
1544 if (options.type == REBASE_UNSPECIFIED) {
1545 if (!strcmp(options.default_backend, "merge"))
1546 options.type = REBASE_MERGE;
1547 else if (!strcmp(options.default_backend, "apply"))
1548 options.type = REBASE_APPLY;
1549 else
1550 die(_("Unknown rebase backend: %s"),
1551 options.default_backend);
1554 if (options.type == REBASE_MERGE &&
1555 !options.strategy &&
1556 getenv("GIT_TEST_MERGE_ALGORITHM"))
1557 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1559 switch (options.type) {
1560 case REBASE_MERGE:
1561 options.state_dir = merge_dir();
1562 break;
1563 case REBASE_APPLY:
1564 options.state_dir = apply_dir();
1565 break;
1566 default:
1567 BUG("options.type was just set above; should be unreachable.");
1570 if (options.empty == EMPTY_UNSPECIFIED) {
1571 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1572 options.empty = EMPTY_STOP;
1573 else if (options.exec.nr > 0)
1574 options.empty = EMPTY_KEEP;
1575 else
1576 options.empty = EMPTY_DROP;
1578 if (reschedule_failed_exec > 0 && !is_merge(&options))
1579 die(_("--reschedule-failed-exec requires "
1580 "--exec or --interactive"));
1581 if (reschedule_failed_exec >= 0)
1582 options.reschedule_failed_exec = reschedule_failed_exec;
1584 if (options.signoff) {
1585 strvec_push(&options.git_am_opts, "--signoff");
1586 options.flags |= REBASE_FORCE;
1589 if (!options.root) {
1590 if (argc < 1) {
1591 struct branch *branch;
1593 branch = branch_get(NULL);
1594 options.upstream_name = branch_get_upstream(branch,
1595 NULL);
1596 if (!options.upstream_name)
1597 error_on_missing_default_upstream();
1598 if (options.fork_point < 0)
1599 options.fork_point = 1;
1600 } else {
1601 options.upstream_name = argv[0];
1602 argc--;
1603 argv++;
1604 if (!strcmp(options.upstream_name, "-"))
1605 options.upstream_name = "@{-1}";
1607 options.upstream =
1608 lookup_commit_reference_by_name(options.upstream_name);
1609 if (!options.upstream)
1610 die(_("invalid upstream '%s'"), options.upstream_name);
1611 options.upstream_arg = options.upstream_name;
1612 } else {
1613 if (!options.onto_name) {
1614 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1615 &squash_onto, NULL, NULL) < 0)
1616 die(_("Could not create new root commit"));
1617 options.squash_onto = &squash_onto;
1618 options.onto_name = squash_onto_name =
1619 xstrdup(oid_to_hex(&squash_onto));
1620 } else
1621 options.root_with_onto = 1;
1623 options.upstream_name = NULL;
1624 options.upstream = NULL;
1625 if (argc > 1)
1626 usage_with_options(builtin_rebase_usage,
1627 builtin_rebase_options);
1628 options.upstream_arg = "--root";
1632 * If the branch to rebase is given, that is the branch we will rebase
1633 * branch_name -- branch/commit being rebased, or
1634 * HEAD (already detached)
1635 * orig_head -- commit object name of tip of the branch before rebasing
1636 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1638 if (argc == 1) {
1639 /* Is it "rebase other branchname" or "rebase other commit"? */
1640 struct object_id branch_oid;
1641 branch_name = argv[0];
1642 options.switch_to = argv[0];
1644 /* Is it a local branch? */
1645 strbuf_reset(&buf);
1646 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1647 if (!refs_read_ref(get_main_ref_store(the_repository), buf.buf, &branch_oid)) {
1648 die_if_checked_out(buf.buf, 1);
1649 options.head_name = xstrdup(buf.buf);
1650 options.orig_head =
1651 lookup_commit_object(the_repository,
1652 &branch_oid);
1653 /* If not is it a valid ref (branch or commit)? */
1654 } else {
1655 options.orig_head =
1656 lookup_commit_reference_by_name(branch_name);
1657 options.head_name = NULL;
1659 if (!options.orig_head)
1660 die(_("no such branch/commit '%s'"), branch_name);
1661 } else if (argc == 0) {
1662 /* Do not need to switch branches, we are already on it. */
1663 options.head_name =
1664 xstrdup_or_null(refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL,
1665 &flags));
1666 if (!options.head_name)
1667 die(_("No such ref: %s"), "HEAD");
1668 if (flags & REF_ISSYMREF) {
1669 if (!skip_prefix(options.head_name,
1670 "refs/heads/", &branch_name))
1671 branch_name = options.head_name;
1673 } else {
1674 FREE_AND_NULL(options.head_name);
1675 branch_name = "HEAD";
1677 options.orig_head = lookup_commit_reference_by_name("HEAD");
1678 if (!options.orig_head)
1679 die(_("Could not resolve HEAD to a commit"));
1680 } else
1681 BUG("unexpected number of arguments left to parse");
1683 /* Make sure the branch to rebase onto is valid. */
1684 if (keep_base) {
1685 strbuf_reset(&buf);
1686 strbuf_addstr(&buf, options.upstream_name);
1687 strbuf_addstr(&buf, "...");
1688 strbuf_addstr(&buf, branch_name);
1689 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1690 } else if (!options.onto_name)
1691 options.onto_name = options.upstream_name;
1692 if (strstr(options.onto_name, "...")) {
1693 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1694 if (keep_base)
1695 die(_("'%s': need exactly one merge base with branch"),
1696 options.upstream_name);
1697 else
1698 die(_("'%s': need exactly one merge base"),
1699 options.onto_name);
1701 options.onto = lookup_commit_or_die(&branch_base,
1702 options.onto_name);
1703 } else {
1704 options.onto =
1705 lookup_commit_reference_by_name(options.onto_name);
1706 if (!options.onto)
1707 die(_("Does not point to a valid commit '%s'"),
1708 options.onto_name);
1709 fill_branch_base(&options, &branch_base);
1712 if (keep_base && options.reapply_cherry_picks)
1713 options.upstream = options.onto;
1715 if (options.fork_point > 0)
1716 options.restrict_revision =
1717 get_fork_point(options.upstream_name, options.orig_head);
1719 if (repo_read_index(the_repository) < 0)
1720 die(_("could not read index"));
1722 if (options.autostash)
1723 create_autostash(the_repository,
1724 state_dir_path("autostash", &options));
1727 if (require_clean_work_tree(the_repository, "rebase",
1728 _("Please commit or stash them."), 1, 1)) {
1729 ret = -1;
1730 goto cleanup;
1734 * Now we are rebasing commits upstream..orig_head (or with --root,
1735 * everything leading up to orig_head) on top of onto.
1739 * Check if we are already based on onto with linear history,
1740 * in which case we could fast-forward without replacing the commits
1741 * with new commits recreated by replaying their changes.
1743 if (allow_preemptive_ff &&
1744 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1745 options.orig_head, &branch_base)) {
1746 int flag;
1748 if (!(options.flags & REBASE_FORCE)) {
1749 /* Lazily switch to the target branch if needed... */
1750 if (options.switch_to) {
1751 ret = checkout_up_to_date(&options);
1752 if (ret)
1753 goto cleanup;
1756 if (!(options.flags & REBASE_NO_QUIET))
1757 ; /* be quiet */
1758 else if (!strcmp(branch_name, "HEAD") &&
1759 refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL, &flag))
1760 puts(_("HEAD is up to date."));
1761 else
1762 printf(_("Current branch %s is up to date.\n"),
1763 branch_name);
1764 ret = finish_rebase(&options);
1765 goto cleanup;
1766 } else if (!(options.flags & REBASE_NO_QUIET))
1767 ; /* be quiet */
1768 else if (!strcmp(branch_name, "HEAD") &&
1769 refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", 0, NULL, &flag))
1770 puts(_("HEAD is up to date, rebase forced."));
1771 else
1772 printf(_("Current branch %s is up to date, rebase "
1773 "forced.\n"), branch_name);
1776 /* If a hook exists, give it a chance to interrupt*/
1777 if (!ok_to_skip_pre_rebase &&
1778 run_hooks_l(the_repository, "pre-rebase", options.upstream_arg,
1779 argc ? argv[0] : NULL, NULL))
1780 die(_("The pre-rebase hook refused to rebase."));
1782 if (options.flags & REBASE_DIFFSTAT) {
1783 struct diff_options opts;
1785 if (options.flags & REBASE_VERBOSE) {
1786 if (is_null_oid(&branch_base))
1787 printf(_("Changes to %s:\n"),
1788 oid_to_hex(&options.onto->object.oid));
1789 else
1790 printf(_("Changes from %s to %s:\n"),
1791 oid_to_hex(&branch_base),
1792 oid_to_hex(&options.onto->object.oid));
1795 /* We want color (if set), but no pager */
1796 repo_diff_setup(the_repository, &opts);
1797 init_diffstat_widths(&opts);
1798 opts.output_format |=
1799 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1800 opts.detect_rename = DIFF_DETECT_RENAME;
1801 diff_setup_done(&opts);
1802 diff_tree_oid(is_null_oid(&branch_base) ?
1803 the_hash_algo->empty_tree : &branch_base,
1804 &options.onto->object.oid, "", &opts);
1805 diffcore_std(&opts);
1806 diff_flush(&opts);
1809 if (is_merge(&options))
1810 goto run_rebase;
1812 /* Detach HEAD and reset the tree */
1813 if (options.flags & REBASE_NO_QUIET)
1814 printf(_("First, rewinding head to replay your work on top of "
1815 "it...\n"));
1817 strbuf_addf(&msg, "%s (start): checkout %s",
1818 options.reflog_action, options.onto_name);
1819 ropts.oid = &options.onto->object.oid;
1820 ropts.orig_head = &options.orig_head->object.oid,
1821 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1822 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1823 ropts.head_msg = msg.buf;
1824 ropts.default_reflog_action = options.reflog_action;
1825 if (reset_head(the_repository, &ropts))
1826 die(_("Could not detach HEAD"));
1827 strbuf_release(&msg);
1830 * If the onto is a proper descendant of the tip of the branch, then
1831 * we just fast-forwarded.
1833 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1834 printf(_("Fast-forwarded %s to %s.\n"),
1835 branch_name, options.onto_name);
1836 move_to_original_branch(&options);
1837 ret = finish_rebase(&options);
1838 goto cleanup;
1841 strbuf_addf(&revisions, "%s..%s",
1842 options.root ? oid_to_hex(&options.onto->object.oid) :
1843 (options.restrict_revision ?
1844 oid_to_hex(&options.restrict_revision->object.oid) :
1845 oid_to_hex(&options.upstream->object.oid)),
1846 oid_to_hex(&options.orig_head->object.oid));
1848 options.revisions = revisions.buf;
1850 run_rebase:
1851 ret = run_specific_rebase(&options);
1853 cleanup:
1854 strbuf_release(&buf);
1855 strbuf_release(&revisions);
1856 rebase_options_release(&options);
1857 free(squash_onto_name);
1858 free(keep_base_onto_name);
1859 return !!ret;