rebase --apply: respect GIT_REFLOG_ACTION
[git/debian.git] / builtin / rebase.c
blobea246c6bb3ab52652095abc263bb4f7196936d8c
1 /*
2 * "git rebase" builtin command
4 * Copyright (c) 2018 Pratik Karki
5 */
7 #define USE_THE_INDEX_COMPATIBILITY_MACROS
8 #include "builtin.h"
9 #include "run-command.h"
10 #include "exec-cmd.h"
11 #include "strvec.h"
12 #include "dir.h"
13 #include "packfile.h"
14 #include "refs.h"
15 #include "quote.h"
16 #include "config.h"
17 #include "cache-tree.h"
18 #include "unpack-trees.h"
19 #include "lockfile.h"
20 #include "parse-options.h"
21 #include "commit.h"
22 #include "diff.h"
23 #include "wt-status.h"
24 #include "revision.h"
25 #include "commit-reach.h"
26 #include "rerere.h"
27 #include "branch.h"
28 #include "sequencer.h"
29 #include "rebase-interactive.h"
30 #include "reset.h"
31 #include "hook.h"
33 #define DEFAULT_REFLOG_ACTION "rebase"
35 static char const * const builtin_rebase_usage[] = {
36 N_("git rebase [-i] [options] [--exec <cmd>] "
37 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
38 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
39 "--root [<branch>]"),
40 "git rebase --continue | --abort | --skip | --edit-todo",
41 NULL
44 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
45 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
46 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
47 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
49 enum rebase_type {
50 REBASE_UNSPECIFIED = -1,
51 REBASE_APPLY,
52 REBASE_MERGE
55 enum empty_type {
56 EMPTY_UNSPECIFIED = -1,
57 EMPTY_DROP,
58 EMPTY_KEEP,
59 EMPTY_ASK
62 struct rebase_options {
63 enum rebase_type type;
64 enum empty_type empty;
65 const char *default_backend;
66 const char *state_dir;
67 struct commit *upstream;
68 const char *upstream_name;
69 const char *upstream_arg;
70 char *head_name;
71 struct commit *orig_head;
72 struct commit *onto;
73 const char *onto_name;
74 const char *revisions;
75 const char *switch_to;
76 int root, root_with_onto;
77 struct object_id *squash_onto;
78 struct commit *restrict_revision;
79 int dont_finish_rebase;
80 enum {
81 REBASE_NO_QUIET = 1<<0,
82 REBASE_VERBOSE = 1<<1,
83 REBASE_DIFFSTAT = 1<<2,
84 REBASE_FORCE = 1<<3,
85 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
86 } flags;
87 struct strvec git_am_opts;
88 const char *action;
89 int signoff;
90 int allow_rerere_autoupdate;
91 int keep_empty;
92 int autosquash;
93 char *gpg_sign_opt;
94 int autostash;
95 int committer_date_is_author_date;
96 int ignore_date;
97 char *cmd;
98 int allow_empty_message;
99 int rebase_merges, rebase_cousins;
100 char *strategy, *strategy_opts;
101 struct strbuf git_format_patch_opt;
102 int reschedule_failed_exec;
103 int reapply_cherry_picks;
104 int fork_point;
107 #define REBASE_OPTIONS_INIT { \
108 .type = REBASE_UNSPECIFIED, \
109 .empty = EMPTY_UNSPECIFIED, \
110 .keep_empty = 1, \
111 .default_backend = "merge", \
112 .flags = REBASE_NO_QUIET, \
113 .git_am_opts = STRVEC_INIT, \
114 .git_format_patch_opt = STRBUF_INIT, \
115 .fork_point = -1, \
118 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
120 struct replay_opts replay = REPLAY_OPTS_INIT;
122 replay.action = REPLAY_INTERACTIVE_REBASE;
123 replay.strategy = NULL;
124 sequencer_init_config(&replay);
126 replay.signoff = opts->signoff;
127 replay.allow_ff = !(opts->flags & REBASE_FORCE);
128 if (opts->allow_rerere_autoupdate)
129 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
130 replay.allow_empty = 1;
131 replay.allow_empty_message = opts->allow_empty_message;
132 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
133 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
134 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
135 replay.verbose = opts->flags & REBASE_VERBOSE;
136 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
137 replay.committer_date_is_author_date =
138 opts->committer_date_is_author_date;
139 replay.ignore_date = opts->ignore_date;
140 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
141 if (opts->strategy)
142 replay.strategy = xstrdup_or_null(opts->strategy);
143 else if (!replay.strategy && replay.default_strategy) {
144 replay.strategy = replay.default_strategy;
145 replay.default_strategy = NULL;
148 if (opts->strategy_opts)
149 parse_strategy_opts(&replay, opts->strategy_opts);
151 if (opts->squash_onto) {
152 oidcpy(&replay.squash_onto, opts->squash_onto);
153 replay.have_squash_onto = 1;
156 return replay;
159 enum action {
160 ACTION_NONE = 0,
161 ACTION_CONTINUE,
162 ACTION_SKIP,
163 ACTION_ABORT,
164 ACTION_QUIT,
165 ACTION_EDIT_TODO,
166 ACTION_SHOW_CURRENT_PATCH
169 static const char *action_names[] = { "undefined",
170 "continue",
171 "skip",
172 "abort",
173 "quit",
174 "edit_todo",
175 "show_current_patch" };
177 static int edit_todo_file(unsigned flags)
179 const char *todo_file = rebase_path_todo();
180 struct todo_list todo_list = TODO_LIST_INIT,
181 new_todo = TODO_LIST_INIT;
182 int res = 0;
184 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
185 return error_errno(_("could not read '%s'."), todo_file);
187 strbuf_stripspace(&todo_list.buf, 1);
188 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
189 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
190 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
191 res = error_errno(_("could not write '%s'"), todo_file);
193 todo_list_release(&todo_list);
194 todo_list_release(&new_todo);
196 return res;
199 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
200 struct object_id *orig_head, char **revisions,
201 char **shortrevisions)
203 struct commit *base_rev = upstream ? upstream : onto;
204 const char *shorthead;
206 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
207 oid_to_hex(orig_head));
209 shorthead = find_unique_abbrev(orig_head, DEFAULT_ABBREV);
211 if (upstream) {
212 const char *shortrev;
214 shortrev = find_unique_abbrev(&base_rev->object.oid,
215 DEFAULT_ABBREV);
217 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
218 } else
219 *shortrevisions = xstrdup(shorthead);
221 return 0;
224 static int init_basic_state(struct replay_opts *opts, const char *head_name,
225 struct commit *onto,
226 const struct object_id *orig_head)
228 FILE *interactive;
230 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
231 return error_errno(_("could not create temporary %s"), merge_dir());
233 delete_reflog("REBASE_HEAD");
235 interactive = fopen(path_interactive(), "w");
236 if (!interactive)
237 return error_errno(_("could not mark as interactive"));
238 fclose(interactive);
240 return write_basic_state(opts, head_name, onto, orig_head);
243 static void split_exec_commands(const char *cmd, struct string_list *commands)
245 if (cmd && *cmd) {
246 string_list_split(commands, cmd, '\n', -1);
248 /* rebase.c adds a new line to cmd after every command,
249 * so here the last command is always empty */
250 string_list_remove_empty_items(commands, 0);
254 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
256 int ret;
257 char *revisions = NULL, *shortrevisions = NULL;
258 struct strvec make_script_args = STRVEC_INIT;
259 struct todo_list todo_list = TODO_LIST_INIT;
260 struct replay_opts replay = get_replay_opts(opts);
261 struct string_list commands = STRING_LIST_INIT_DUP;
263 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head->object.oid,
264 &revisions, &shortrevisions))
265 return -1;
267 if (init_basic_state(&replay,
268 opts->head_name ? opts->head_name : "detached HEAD",
269 opts->onto, &opts->orig_head->object.oid)) {
270 free(revisions);
271 free(shortrevisions);
273 return -1;
276 if (!opts->upstream && opts->squash_onto)
277 write_file(path_squash_onto(), "%s\n",
278 oid_to_hex(opts->squash_onto));
280 strvec_pushl(&make_script_args, "", revisions, NULL);
281 if (opts->restrict_revision)
282 strvec_pushf(&make_script_args, "^%s",
283 oid_to_hex(&opts->restrict_revision->object.oid));
285 ret = sequencer_make_script(the_repository, &todo_list.buf,
286 make_script_args.nr, make_script_args.v,
287 flags);
289 if (ret)
290 error(_("could not generate todo list"));
291 else {
292 discard_cache();
293 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
294 &todo_list))
295 BUG("unusable todo list");
297 split_exec_commands(opts->cmd, &commands);
298 ret = complete_action(the_repository, &replay, flags,
299 shortrevisions, opts->onto_name, opts->onto,
300 &opts->orig_head->object.oid, &commands,
301 opts->autosquash, &todo_list);
304 string_list_clear(&commands, 0);
305 free(revisions);
306 free(shortrevisions);
307 todo_list_release(&todo_list);
308 strvec_clear(&make_script_args);
310 return ret;
313 static int run_sequencer_rebase(struct rebase_options *opts,
314 enum action command)
316 unsigned flags = 0;
317 int abbreviate_commands = 0, ret = 0;
319 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
321 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
322 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
323 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
324 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
325 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
326 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
327 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
329 switch (command) {
330 case ACTION_NONE: {
331 if (!opts->onto && !opts->upstream)
332 die(_("a base commit must be provided with --upstream or --onto"));
334 ret = do_interactive_rebase(opts, flags);
335 break;
337 case ACTION_SKIP: {
338 struct string_list merge_rr = STRING_LIST_INIT_DUP;
340 rerere_clear(the_repository, &merge_rr);
342 /* fallthrough */
343 case ACTION_CONTINUE: {
344 struct replay_opts replay_opts = get_replay_opts(opts);
346 ret = sequencer_continue(the_repository, &replay_opts);
347 break;
349 case ACTION_EDIT_TODO:
350 ret = edit_todo_file(flags);
351 break;
352 case ACTION_SHOW_CURRENT_PATCH: {
353 struct child_process cmd = CHILD_PROCESS_INIT;
355 cmd.git_cmd = 1;
356 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
357 ret = run_command(&cmd);
359 break;
361 default:
362 BUG("invalid command '%d'", command);
365 return ret;
368 static void imply_merge(struct rebase_options *opts, const char *option);
369 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
370 int unset)
372 struct rebase_options *opts = opt->value;
374 BUG_ON_OPT_ARG(arg);
376 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
377 opts->keep_empty = !unset;
378 opts->type = REBASE_MERGE;
379 return 0;
382 static int is_merge(struct rebase_options *opts)
384 return opts->type == REBASE_MERGE;
387 static void imply_merge(struct rebase_options *opts, const char *option)
389 switch (opts->type) {
390 case REBASE_APPLY:
391 die(_("%s requires the merge backend"), option);
392 break;
393 case REBASE_MERGE:
394 break;
395 default:
396 opts->type = REBASE_MERGE; /* implied */
397 break;
401 /* Returns the filename prefixed by the state_dir */
402 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
404 static struct strbuf path = STRBUF_INIT;
405 static size_t prefix_len;
407 if (!prefix_len) {
408 strbuf_addf(&path, "%s/", opts->state_dir);
409 prefix_len = path.len;
412 strbuf_setlen(&path, prefix_len);
413 strbuf_addstr(&path, filename);
414 return path.buf;
417 /* Initialize the rebase options from the state directory. */
418 static int read_basic_state(struct rebase_options *opts)
420 struct strbuf head_name = STRBUF_INIT;
421 struct strbuf buf = STRBUF_INIT;
422 struct object_id oid;
424 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
425 READ_ONELINER_WARN_MISSING) ||
426 !read_oneliner(&buf, state_dir_path("onto", opts),
427 READ_ONELINER_WARN_MISSING))
428 return -1;
429 opts->head_name = starts_with(head_name.buf, "refs/") ?
430 xstrdup(head_name.buf) : NULL;
431 strbuf_release(&head_name);
432 if (get_oid_hex(buf.buf, &oid) ||
433 !(opts->onto = lookup_commit_object(the_repository, &oid)))
434 return error(_("invalid onto: '%s'"), buf.buf);
437 * We always write to orig-head, but interactive rebase used to write to
438 * head. Fall back to reading from head to cover for the case that the
439 * user upgraded git with an ongoing interactive rebase.
441 strbuf_reset(&buf);
442 if (file_exists(state_dir_path("orig-head", opts))) {
443 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
444 READ_ONELINER_WARN_MISSING))
445 return -1;
446 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
447 READ_ONELINER_WARN_MISSING))
448 return -1;
449 if (get_oid_hex(buf.buf, &oid) ||
450 !(opts->orig_head = lookup_commit_object(the_repository, &oid)))
451 return error(_("invalid orig-head: '%s'"), buf.buf);
453 if (file_exists(state_dir_path("quiet", opts)))
454 opts->flags &= ~REBASE_NO_QUIET;
455 else
456 opts->flags |= REBASE_NO_QUIET;
458 if (file_exists(state_dir_path("verbose", opts)))
459 opts->flags |= REBASE_VERBOSE;
461 if (file_exists(state_dir_path("signoff", opts))) {
462 opts->signoff = 1;
463 opts->flags |= REBASE_FORCE;
466 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
467 strbuf_reset(&buf);
468 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
469 READ_ONELINER_WARN_MISSING))
470 return -1;
471 if (!strcmp(buf.buf, "--rerere-autoupdate"))
472 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
473 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
474 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
475 else
476 warning(_("ignoring invalid allow_rerere_autoupdate: "
477 "'%s'"), buf.buf);
480 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
481 strbuf_reset(&buf);
482 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
483 READ_ONELINER_WARN_MISSING))
484 return -1;
485 free(opts->gpg_sign_opt);
486 opts->gpg_sign_opt = xstrdup(buf.buf);
489 if (file_exists(state_dir_path("strategy", opts))) {
490 strbuf_reset(&buf);
491 if (!read_oneliner(&buf, state_dir_path("strategy", opts),
492 READ_ONELINER_WARN_MISSING))
493 return -1;
494 free(opts->strategy);
495 opts->strategy = xstrdup(buf.buf);
498 if (file_exists(state_dir_path("strategy_opts", opts))) {
499 strbuf_reset(&buf);
500 if (!read_oneliner(&buf, state_dir_path("strategy_opts", opts),
501 READ_ONELINER_WARN_MISSING))
502 return -1;
503 free(opts->strategy_opts);
504 opts->strategy_opts = xstrdup(buf.buf);
507 strbuf_release(&buf);
509 return 0;
512 static int rebase_write_basic_state(struct rebase_options *opts)
514 write_file(state_dir_path("head-name", opts), "%s",
515 opts->head_name ? opts->head_name : "detached HEAD");
516 write_file(state_dir_path("onto", opts), "%s",
517 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
518 write_file(state_dir_path("orig-head", opts), "%s",
519 oid_to_hex(&opts->orig_head->object.oid));
520 if (!(opts->flags & REBASE_NO_QUIET))
521 write_file(state_dir_path("quiet", opts), "%s", "");
522 if (opts->flags & REBASE_VERBOSE)
523 write_file(state_dir_path("verbose", opts), "%s", "");
524 if (opts->strategy)
525 write_file(state_dir_path("strategy", opts), "%s",
526 opts->strategy);
527 if (opts->strategy_opts)
528 write_file(state_dir_path("strategy_opts", opts), "%s",
529 opts->strategy_opts);
530 if (opts->allow_rerere_autoupdate > 0)
531 write_file(state_dir_path("allow_rerere_autoupdate", opts),
532 "-%s-rerere-autoupdate",
533 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
534 "" : "-no");
535 if (opts->gpg_sign_opt)
536 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
537 opts->gpg_sign_opt);
538 if (opts->signoff)
539 write_file(state_dir_path("signoff", opts), "--signoff");
541 return 0;
544 static int finish_rebase(struct rebase_options *opts)
546 struct strbuf dir = STRBUF_INIT;
547 int ret = 0;
549 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
550 unlink(git_path_auto_merge(the_repository));
551 apply_autostash(state_dir_path("autostash", opts));
553 * We ignore errors in 'git maintenance run --auto', since the
554 * user should see them.
556 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
557 if (opts->type == REBASE_MERGE) {
558 struct replay_opts replay = REPLAY_OPTS_INIT;
560 replay.action = REPLAY_INTERACTIVE_REBASE;
561 ret = sequencer_remove_state(&replay);
562 } else {
563 strbuf_addstr(&dir, opts->state_dir);
564 if (remove_dir_recursively(&dir, 0))
565 ret = error(_("could not remove '%s'"),
566 opts->state_dir);
567 strbuf_release(&dir);
570 return ret;
573 static int move_to_original_branch(struct rebase_options *opts)
575 struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
576 struct reset_head_opts ropts = { 0 };
577 int ret;
579 if (!opts->head_name)
580 return 0; /* nothing to move back to */
582 if (!opts->onto)
583 BUG("move_to_original_branch without onto");
585 strbuf_addf(&branch_reflog, "%s finished: %s onto %s",
586 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
587 opts->head_name, oid_to_hex(&opts->onto->object.oid));
588 strbuf_addf(&head_reflog, "%s finished: returning to %s",
589 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), opts->head_name);
590 ropts.branch = opts->head_name;
591 ropts.flags = RESET_HEAD_REFS_ONLY;
592 ropts.branch_msg = branch_reflog.buf;
593 ropts.head_msg = head_reflog.buf;
594 ret = reset_head(the_repository, &ropts);
596 strbuf_release(&branch_reflog);
597 strbuf_release(&head_reflog);
598 return ret;
601 static const char *resolvemsg =
602 N_("Resolve all conflicts manually, mark them as resolved with\n"
603 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
604 "You can instead skip this commit: run \"git rebase --skip\".\n"
605 "To abort and get back to the state before \"git rebase\", run "
606 "\"git rebase --abort\".");
608 static int run_am(struct rebase_options *opts)
610 struct child_process am = CHILD_PROCESS_INIT;
611 struct child_process format_patch = CHILD_PROCESS_INIT;
612 struct strbuf revisions = STRBUF_INIT;
613 int status;
614 char *rebased_patches;
616 am.git_cmd = 1;
617 strvec_push(&am.args, "am");
619 if (opts->action && !strcmp("continue", opts->action)) {
620 strvec_push(&am.args, "--resolved");
621 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
622 if (opts->gpg_sign_opt)
623 strvec_push(&am.args, opts->gpg_sign_opt);
624 status = run_command(&am);
625 if (status)
626 return status;
628 return move_to_original_branch(opts);
630 if (opts->action && !strcmp("skip", opts->action)) {
631 strvec_push(&am.args, "--skip");
632 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
633 status = run_command(&am);
634 if (status)
635 return status;
637 return move_to_original_branch(opts);
639 if (opts->action && !strcmp("show-current-patch", opts->action)) {
640 strvec_push(&am.args, "--show-current-patch");
641 return run_command(&am);
644 strbuf_addf(&revisions, "%s...%s",
645 oid_to_hex(opts->root ?
646 /* this is now equivalent to !opts->upstream */
647 &opts->onto->object.oid :
648 &opts->upstream->object.oid),
649 oid_to_hex(&opts->orig_head->object.oid));
651 rebased_patches = xstrdup(git_path("rebased-patches"));
652 format_patch.out = open(rebased_patches,
653 O_WRONLY | O_CREAT | O_TRUNC, 0666);
654 if (format_patch.out < 0) {
655 status = error_errno(_("could not open '%s' for writing"),
656 rebased_patches);
657 free(rebased_patches);
658 strvec_clear(&am.args);
659 return status;
662 format_patch.git_cmd = 1;
663 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
664 "--full-index", "--cherry-pick", "--right-only",
665 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
666 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
667 "--no-base", NULL);
668 if (opts->git_format_patch_opt.len)
669 strvec_split(&format_patch.args,
670 opts->git_format_patch_opt.buf);
671 strvec_push(&format_patch.args, revisions.buf);
672 if (opts->restrict_revision)
673 strvec_pushf(&format_patch.args, "^%s",
674 oid_to_hex(&opts->restrict_revision->object.oid));
676 status = run_command(&format_patch);
677 if (status) {
678 struct reset_head_opts ropts = { 0 };
679 unlink(rebased_patches);
680 free(rebased_patches);
681 strvec_clear(&am.args);
683 ropts.oid = &opts->orig_head->object.oid;
684 ropts.branch = opts->head_name;
685 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
686 reset_head(the_repository, &ropts);
687 error(_("\ngit encountered an error while preparing the "
688 "patches to replay\n"
689 "these revisions:\n"
690 "\n %s\n\n"
691 "As a result, git cannot rebase them."),
692 opts->revisions);
694 strbuf_release(&revisions);
695 return status;
697 strbuf_release(&revisions);
699 am.in = open(rebased_patches, O_RDONLY);
700 if (am.in < 0) {
701 status = error_errno(_("could not open '%s' for reading"),
702 rebased_patches);
703 free(rebased_patches);
704 strvec_clear(&am.args);
705 return status;
708 strvec_pushv(&am.args, opts->git_am_opts.v);
709 strvec_push(&am.args, "--rebasing");
710 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
711 strvec_push(&am.args, "--patch-format=mboxrd");
712 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
713 strvec_push(&am.args, "--rerere-autoupdate");
714 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
715 strvec_push(&am.args, "--no-rerere-autoupdate");
716 if (opts->gpg_sign_opt)
717 strvec_push(&am.args, opts->gpg_sign_opt);
718 status = run_command(&am);
719 unlink(rebased_patches);
720 free(rebased_patches);
722 if (!status) {
723 return move_to_original_branch(opts);
726 if (is_directory(opts->state_dir))
727 rebase_write_basic_state(opts);
729 return status;
732 static int run_specific_rebase(struct rebase_options *opts, enum action action)
734 int status;
736 if (opts->type == REBASE_MERGE) {
737 /* Run sequencer-based rebase */
738 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
739 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
740 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
741 opts->autosquash = 0;
743 if (opts->gpg_sign_opt) {
744 /* remove the leading "-S" */
745 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
746 free(opts->gpg_sign_opt);
747 opts->gpg_sign_opt = tmp;
750 status = run_sequencer_rebase(opts, action);
751 } else if (opts->type == REBASE_APPLY)
752 status = run_am(opts);
753 else
754 BUG("Unhandled rebase type %d", opts->type);
756 if (opts->dont_finish_rebase)
757 ; /* do nothing */
758 else if (opts->type == REBASE_MERGE)
759 ; /* merge backend cleans up after itself */
760 else if (status == 0) {
761 if (!file_exists(state_dir_path("stopped-sha", opts)))
762 finish_rebase(opts);
763 } else if (status == 2) {
764 struct strbuf dir = STRBUF_INIT;
766 apply_autostash(state_dir_path("autostash", opts));
767 strbuf_addstr(&dir, opts->state_dir);
768 remove_dir_recursively(&dir, 0);
769 strbuf_release(&dir);
770 die("Nothing to do");
773 return status ? -1 : 0;
776 static int rebase_config(const char *var, const char *value, void *data)
778 struct rebase_options *opts = data;
780 if (!strcmp(var, "rebase.stat")) {
781 if (git_config_bool(var, value))
782 opts->flags |= REBASE_DIFFSTAT;
783 else
784 opts->flags &= ~REBASE_DIFFSTAT;
785 return 0;
788 if (!strcmp(var, "rebase.autosquash")) {
789 opts->autosquash = git_config_bool(var, value);
790 return 0;
793 if (!strcmp(var, "commit.gpgsign")) {
794 free(opts->gpg_sign_opt);
795 opts->gpg_sign_opt = git_config_bool(var, value) ?
796 xstrdup("-S") : NULL;
797 return 0;
800 if (!strcmp(var, "rebase.autostash")) {
801 opts->autostash = git_config_bool(var, value);
802 return 0;
805 if (!strcmp(var, "rebase.reschedulefailedexec")) {
806 opts->reschedule_failed_exec = git_config_bool(var, value);
807 return 0;
810 if (!strcmp(var, "rebase.forkpoint")) {
811 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
812 return 0;
815 if (!strcmp(var, "rebase.backend")) {
816 return git_config_string(&opts->default_backend, var, value);
819 return git_default_config(var, value, data);
822 static int checkout_up_to_date(struct rebase_options *options)
824 struct strbuf buf = STRBUF_INIT;
825 struct reset_head_opts ropts = { 0 };
826 int ret = 0;
828 strbuf_addf(&buf, "%s: checkout %s",
829 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
830 options->switch_to);
831 ropts.oid = &options->orig_head->object.oid;
832 ropts.branch = options->head_name;
833 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
834 if (!ropts.branch)
835 ropts.flags |= RESET_HEAD_DETACH;
836 ropts.head_msg = buf.buf;
837 if (reset_head(the_repository, &ropts) < 0)
838 ret = error(_("could not switch to %s"), options->switch_to);
839 strbuf_release(&buf);
841 return ret;
845 * Determines whether the commits in from..to are linear, i.e. contain
846 * no merge commits. This function *expects* `from` to be an ancestor of
847 * `to`.
849 static int is_linear_history(struct commit *from, struct commit *to)
851 while (to && to != from) {
852 parse_commit(to);
853 if (!to->parents)
854 return 1;
855 if (to->parents->next)
856 return 0;
857 to = to->parents->item;
859 return 1;
862 static int can_fast_forward(struct commit *onto, struct commit *upstream,
863 struct commit *restrict_revision,
864 struct commit *head, struct object_id *branch_base)
866 struct commit_list *merge_bases = NULL;
867 int res = 0;
869 if (is_null_oid(branch_base))
870 goto done; /* fill_branch_base() found multiple merge bases */
872 if (!oideq(branch_base, &onto->object.oid))
873 goto done;
875 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
876 goto done;
878 if (!upstream)
879 goto done;
881 merge_bases = get_merge_bases(upstream, head);
882 if (!merge_bases || merge_bases->next)
883 goto done;
885 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
886 goto done;
888 res = 1;
890 done:
891 free_commit_list(merge_bases);
892 return res && is_linear_history(onto, head);
895 static void fill_branch_base(struct rebase_options *options,
896 struct object_id *branch_base)
898 struct commit_list *merge_bases = NULL;
900 merge_bases = get_merge_bases(options->onto, options->orig_head);
901 if (!merge_bases || merge_bases->next)
902 oidcpy(branch_base, null_oid());
903 else
904 oidcpy(branch_base, &merge_bases->item->object.oid);
906 free_commit_list(merge_bases);
909 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
911 struct rebase_options *opts = opt->value;
913 BUG_ON_OPT_NEG(unset);
914 BUG_ON_OPT_ARG(arg);
916 opts->type = REBASE_APPLY;
918 return 0;
921 /* -i followed by -m is still -i */
922 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
924 struct rebase_options *opts = opt->value;
926 BUG_ON_OPT_NEG(unset);
927 BUG_ON_OPT_ARG(arg);
929 if (!is_merge(opts))
930 opts->type = REBASE_MERGE;
932 return 0;
935 /* -i followed by -r is still explicitly interactive, but -r alone is not */
936 static int parse_opt_interactive(const struct option *opt, const char *arg,
937 int unset)
939 struct rebase_options *opts = opt->value;
941 BUG_ON_OPT_NEG(unset);
942 BUG_ON_OPT_ARG(arg);
944 opts->type = REBASE_MERGE;
945 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
947 return 0;
950 static enum empty_type parse_empty_value(const char *value)
952 if (!strcasecmp(value, "drop"))
953 return EMPTY_DROP;
954 else if (!strcasecmp(value, "keep"))
955 return EMPTY_KEEP;
956 else if (!strcasecmp(value, "ask"))
957 return EMPTY_ASK;
959 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
962 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
964 struct rebase_options *options = opt->value;
965 enum empty_type value = parse_empty_value(arg);
967 BUG_ON_OPT_NEG(unset);
969 options->empty = value;
970 return 0;
973 static void NORETURN error_on_missing_default_upstream(void)
975 struct branch *current_branch = branch_get(NULL);
977 printf(_("%s\n"
978 "Please specify which branch you want to rebase against.\n"
979 "See git-rebase(1) for details.\n"
980 "\n"
981 " git rebase '<branch>'\n"
982 "\n"),
983 current_branch ? _("There is no tracking information for "
984 "the current branch.") :
985 _("You are not currently on a branch."));
987 if (current_branch) {
988 const char *remote = current_branch->remote_name;
990 if (!remote)
991 remote = _("<remote>");
993 printf(_("If you wish to set tracking information for this "
994 "branch you can do so with:\n"
995 "\n"
996 " git branch --set-upstream-to=%s/<branch> %s\n"
997 "\n"),
998 remote, current_branch->name);
1000 exit(1);
1003 static void set_reflog_action(struct rebase_options *options)
1005 const char *env;
1006 struct strbuf buf = STRBUF_INIT;
1008 if (!is_merge(options))
1009 return;
1011 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1012 if (env && strcmp("rebase", env))
1013 return; /* only override it if it is "rebase" */
1015 strbuf_addf(&buf, "rebase (%s)", options->action);
1016 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1017 strbuf_release(&buf);
1020 static int check_exec_cmd(const char *cmd)
1022 if (strchr(cmd, '\n'))
1023 return error(_("exec commands cannot contain newlines"));
1025 /* Does the command consist purely of whitespace? */
1026 if (!cmd[strspn(cmd, " \t\r\f\v")])
1027 return error(_("empty exec command"));
1029 return 0;
1032 int cmd_rebase(int argc, const char **argv, const char *prefix)
1034 struct rebase_options options = REBASE_OPTIONS_INIT;
1035 const char *branch_name;
1036 int ret, flags, total_argc, in_progress = 0;
1037 int keep_base = 0;
1038 int ok_to_skip_pre_rebase = 0;
1039 struct strbuf msg = STRBUF_INIT;
1040 struct strbuf revisions = STRBUF_INIT;
1041 struct strbuf buf = STRBUF_INIT;
1042 struct object_id branch_base;
1043 int ignore_whitespace = 0;
1044 enum action action = ACTION_NONE;
1045 const char *gpg_sign = NULL;
1046 struct string_list exec = STRING_LIST_INIT_NODUP;
1047 const char *rebase_merges = NULL;
1048 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1049 struct object_id squash_onto;
1050 char *squash_onto_name = NULL;
1051 int reschedule_failed_exec = -1;
1052 int allow_preemptive_ff = 1;
1053 int preserve_merges_selected = 0;
1054 struct reset_head_opts ropts = { 0 };
1055 struct option builtin_rebase_options[] = {
1056 OPT_STRING(0, "onto", &options.onto_name,
1057 N_("revision"),
1058 N_("rebase onto given branch instead of upstream")),
1059 OPT_BOOL(0, "keep-base", &keep_base,
1060 N_("use the merge-base of upstream and branch as the current base")),
1061 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1062 N_("allow pre-rebase hook to run")),
1063 OPT_NEGBIT('q', "quiet", &options.flags,
1064 N_("be quiet. implies --no-stat"),
1065 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1066 OPT_BIT('v', "verbose", &options.flags,
1067 N_("display a diffstat of what changed upstream"),
1068 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1069 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1070 N_("do not show diffstat of what changed upstream"),
1071 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1072 OPT_BOOL(0, "signoff", &options.signoff,
1073 N_("add a Signed-off-by trailer to each commit")),
1074 OPT_BOOL(0, "committer-date-is-author-date",
1075 &options.committer_date_is_author_date,
1076 N_("make committer date match author date")),
1077 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1078 N_("ignore author date and use current date")),
1079 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1080 N_("synonym of --reset-author-date")),
1081 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1082 N_("passed to 'git apply'"), 0),
1083 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1084 N_("ignore changes in whitespace")),
1085 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1086 N_("action"), N_("passed to 'git apply'"), 0),
1087 OPT_BIT('f', "force-rebase", &options.flags,
1088 N_("cherry-pick all commits, even if unchanged"),
1089 REBASE_FORCE),
1090 OPT_BIT(0, "no-ff", &options.flags,
1091 N_("cherry-pick all commits, even if unchanged"),
1092 REBASE_FORCE),
1093 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1094 ACTION_CONTINUE),
1095 OPT_CMDMODE(0, "skip", &action,
1096 N_("skip current patch and continue"), ACTION_SKIP),
1097 OPT_CMDMODE(0, "abort", &action,
1098 N_("abort and check out the original branch"),
1099 ACTION_ABORT),
1100 OPT_CMDMODE(0, "quit", &action,
1101 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1102 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1103 "during an interactive rebase"), ACTION_EDIT_TODO),
1104 OPT_CMDMODE(0, "show-current-patch", &action,
1105 N_("show the patch file being applied or merged"),
1106 ACTION_SHOW_CURRENT_PATCH),
1107 OPT_CALLBACK_F(0, "apply", &options, NULL,
1108 N_("use apply strategies to rebase"),
1109 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1110 parse_opt_am),
1111 OPT_CALLBACK_F('m', "merge", &options, NULL,
1112 N_("use merging strategies to rebase"),
1113 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1114 parse_opt_merge),
1115 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1116 N_("let the user edit the list of commits to rebase"),
1117 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1118 parse_opt_interactive),
1119 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1120 N_("(REMOVED) was: try to recreate merges "
1121 "instead of ignoring them"),
1122 1, PARSE_OPT_HIDDEN),
1123 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1124 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1125 N_("how to handle commits that become empty"),
1126 PARSE_OPT_NONEG, parse_opt_empty),
1127 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1128 N_("keep commits which start empty"),
1129 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1130 parse_opt_keep_empty),
1131 OPT_BOOL(0, "autosquash", &options.autosquash,
1132 N_("move commits that begin with "
1133 "squash!/fixup! under -i")),
1134 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1135 N_("GPG-sign commits"),
1136 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1137 OPT_AUTOSTASH(&options.autostash),
1138 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1139 N_("add exec lines after each commit of the "
1140 "editable list")),
1141 OPT_BOOL_F(0, "allow-empty-message",
1142 &options.allow_empty_message,
1143 N_("allow rebasing commits with empty messages"),
1144 PARSE_OPT_HIDDEN),
1145 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1146 N_("mode"),
1147 N_("try to rebase merges instead of skipping them"),
1148 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1149 OPT_BOOL(0, "fork-point", &options.fork_point,
1150 N_("use 'merge-base --fork-point' to refine upstream")),
1151 OPT_STRING('s', "strategy", &options.strategy,
1152 N_("strategy"), N_("use the given merge strategy")),
1153 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1154 N_("option"),
1155 N_("pass the argument through to the merge "
1156 "strategy")),
1157 OPT_BOOL(0, "root", &options.root,
1158 N_("rebase all reachable commits up to the root(s)")),
1159 OPT_BOOL(0, "reschedule-failed-exec",
1160 &reschedule_failed_exec,
1161 N_("automatically re-schedule any `exec` that fails")),
1162 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1163 N_("apply all changes, even those already present upstream")),
1164 OPT_END(),
1166 int i;
1168 if (argc == 2 && !strcmp(argv[1], "-h"))
1169 usage_with_options(builtin_rebase_usage,
1170 builtin_rebase_options);
1172 prepare_repo_settings(the_repository);
1173 the_repository->settings.command_requires_full_index = 0;
1175 options.reapply_cherry_picks = -1;
1176 options.allow_empty_message = 1;
1177 git_config(rebase_config, &options);
1178 /* options.gpg_sign_opt will be either "-S" or NULL */
1179 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1180 FREE_AND_NULL(options.gpg_sign_opt);
1182 strbuf_reset(&buf);
1183 strbuf_addf(&buf, "%s/applying", apply_dir());
1184 if(file_exists(buf.buf))
1185 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1187 if (is_directory(apply_dir())) {
1188 options.type = REBASE_APPLY;
1189 options.state_dir = apply_dir();
1190 } else if (is_directory(merge_dir())) {
1191 strbuf_reset(&buf);
1192 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1193 if (!(action == ACTION_ABORT) && is_directory(buf.buf)) {
1194 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1195 "Use `git rebase --abort` to terminate current rebase.\n"
1196 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1197 } else {
1198 strbuf_reset(&buf);
1199 strbuf_addf(&buf, "%s/interactive", merge_dir());
1200 options.type = REBASE_MERGE;
1201 if (file_exists(buf.buf))
1202 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1204 options.state_dir = merge_dir();
1207 if (options.type != REBASE_UNSPECIFIED)
1208 in_progress = 1;
1210 total_argc = argc;
1211 argc = parse_options(argc, argv, prefix,
1212 builtin_rebase_options,
1213 builtin_rebase_usage, 0);
1215 if (preserve_merges_selected)
1216 die(_("--preserve-merges was replaced by --rebase-merges\n"
1217 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1218 "which is no longer supported; use 'merges' instead"));
1220 if (action != ACTION_NONE && total_argc != 2) {
1221 usage_with_options(builtin_rebase_usage,
1222 builtin_rebase_options);
1225 if (argc > 2)
1226 usage_with_options(builtin_rebase_usage,
1227 builtin_rebase_options);
1229 if (keep_base) {
1230 if (options.onto_name)
1231 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1232 if (options.root)
1233 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1235 * --keep-base defaults to --no-fork-point to keep the
1236 * base the same.
1238 if (options.fork_point < 0)
1239 options.fork_point = 0;
1242 * --keep-base defaults to --reapply-cherry-picks to avoid losing
1243 * commits when using this option.
1245 if (options.reapply_cherry_picks < 0)
1246 options.reapply_cherry_picks = keep_base;
1248 if (options.root && options.fork_point > 0)
1249 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1251 if (action != ACTION_NONE && !in_progress)
1252 die(_("No rebase in progress?"));
1253 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1255 if (action == ACTION_EDIT_TODO && !is_merge(&options))
1256 die(_("The --edit-todo action can only be used during "
1257 "interactive rebase."));
1259 if (trace2_is_enabled()) {
1260 if (is_merge(&options))
1261 trace2_cmd_mode("interactive");
1262 else if (exec.nr)
1263 trace2_cmd_mode("interactive-exec");
1264 else
1265 trace2_cmd_mode(action_names[action]);
1268 switch (action) {
1269 case ACTION_CONTINUE: {
1270 struct object_id head;
1271 struct lock_file lock_file = LOCK_INIT;
1272 int fd;
1274 options.action = "continue";
1275 /* Sanity check */
1276 if (get_oid("HEAD", &head))
1277 die(_("Cannot read HEAD"));
1279 fd = hold_locked_index(&lock_file, 0);
1280 if (repo_read_index(the_repository) < 0)
1281 die(_("could not read index"));
1282 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1283 NULL);
1284 if (0 <= fd)
1285 repo_update_index_if_able(the_repository, &lock_file);
1286 rollback_lock_file(&lock_file);
1288 if (has_unstaged_changes(the_repository, 1)) {
1289 puts(_("You must edit all merge conflicts and then\n"
1290 "mark them as resolved using git add"));
1291 exit(1);
1293 if (read_basic_state(&options))
1294 exit(1);
1295 goto run_rebase;
1297 case ACTION_SKIP: {
1298 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1300 options.action = "skip";
1301 rerere_clear(the_repository, &merge_rr);
1302 string_list_clear(&merge_rr, 1);
1303 ropts.flags = RESET_HEAD_HARD;
1304 if (reset_head(the_repository, &ropts) < 0)
1305 die(_("could not discard worktree changes"));
1306 remove_branch_state(the_repository, 0);
1307 if (read_basic_state(&options))
1308 exit(1);
1309 goto run_rebase;
1311 case ACTION_ABORT: {
1312 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1313 options.action = "abort";
1314 set_reflog_action(&options);
1316 rerere_clear(the_repository, &merge_rr);
1317 string_list_clear(&merge_rr, 1);
1319 if (read_basic_state(&options))
1320 exit(1);
1321 ropts.oid = &options.orig_head->object.oid;
1322 ropts.branch = options.head_name;
1323 ropts.flags = RESET_HEAD_HARD;
1324 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1325 if (reset_head(the_repository, &ropts) < 0)
1326 die(_("could not move back to %s"),
1327 oid_to_hex(&options.orig_head->object.oid));
1328 remove_branch_state(the_repository, 0);
1329 ret = finish_rebase(&options);
1330 goto cleanup;
1332 case ACTION_QUIT: {
1333 save_autostash(state_dir_path("autostash", &options));
1334 if (options.type == REBASE_MERGE) {
1335 struct replay_opts replay = REPLAY_OPTS_INIT;
1337 replay.action = REPLAY_INTERACTIVE_REBASE;
1338 ret = sequencer_remove_state(&replay);
1339 } else {
1340 strbuf_reset(&buf);
1341 strbuf_addstr(&buf, options.state_dir);
1342 ret = remove_dir_recursively(&buf, 0);
1343 if (ret)
1344 error(_("could not remove '%s'"),
1345 options.state_dir);
1347 goto cleanup;
1349 case ACTION_EDIT_TODO:
1350 options.action = "edit-todo";
1351 options.dont_finish_rebase = 1;
1352 goto run_rebase;
1353 case ACTION_SHOW_CURRENT_PATCH:
1354 options.action = "show-current-patch";
1355 options.dont_finish_rebase = 1;
1356 goto run_rebase;
1357 case ACTION_NONE:
1358 break;
1359 default:
1360 BUG("action: %d", action);
1363 /* Make sure no rebase is in progress */
1364 if (in_progress) {
1365 const char *last_slash = strrchr(options.state_dir, '/');
1366 const char *state_dir_base =
1367 last_slash ? last_slash + 1 : options.state_dir;
1368 const char *cmd_live_rebase =
1369 "git rebase (--continue | --abort | --skip)";
1370 strbuf_reset(&buf);
1371 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1372 die(_("It seems that there is already a %s directory, and\n"
1373 "I wonder if you are in the middle of another rebase. "
1374 "If that is the\n"
1375 "case, please try\n\t%s\n"
1376 "If that is not the case, please\n\t%s\n"
1377 "and run me again. I am stopping in case you still "
1378 "have something\n"
1379 "valuable there.\n"),
1380 state_dir_base, cmd_live_rebase, buf.buf);
1383 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1384 (action != ACTION_NONE) ||
1385 (exec.nr > 0) ||
1386 options.autosquash) {
1387 allow_preemptive_ff = 0;
1389 if (options.committer_date_is_author_date || options.ignore_date)
1390 options.flags |= REBASE_FORCE;
1392 for (i = 0; i < options.git_am_opts.nr; i++) {
1393 const char *option = options.git_am_opts.v[i], *p;
1394 if (!strcmp(option, "--whitespace=fix") ||
1395 !strcmp(option, "--whitespace=strip"))
1396 allow_preemptive_ff = 0;
1397 else if (skip_prefix(option, "-C", &p)) {
1398 while (*p)
1399 if (!isdigit(*(p++)))
1400 die(_("switch `C' expects a "
1401 "numerical value"));
1402 } else if (skip_prefix(option, "--whitespace=", &p)) {
1403 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1404 strcmp(p, "error") && strcmp(p, "error-all"))
1405 die("Invalid whitespace option: '%s'", p);
1409 for (i = 0; i < exec.nr; i++)
1410 if (check_exec_cmd(exec.items[i].string))
1411 exit(1);
1413 if (!(options.flags & REBASE_NO_QUIET))
1414 strvec_push(&options.git_am_opts, "-q");
1416 if (options.empty != EMPTY_UNSPECIFIED)
1417 imply_merge(&options, "--empty");
1420 * --keep-base implements --reapply-cherry-picks by altering upstream so
1421 * it works with both backends.
1423 if (options.reapply_cherry_picks && !keep_base)
1424 imply_merge(&options, "--reapply-cherry-picks");
1426 if (gpg_sign)
1427 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1429 if (exec.nr) {
1430 int i;
1432 imply_merge(&options, "--exec");
1434 strbuf_reset(&buf);
1435 for (i = 0; i < exec.nr; i++)
1436 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1437 options.cmd = xstrdup(buf.buf);
1440 if (rebase_merges) {
1441 if (!*rebase_merges)
1442 ; /* default mode; do nothing */
1443 else if (!strcmp("rebase-cousins", rebase_merges))
1444 options.rebase_cousins = 1;
1445 else if (strcmp("no-rebase-cousins", rebase_merges))
1446 die(_("Unknown mode: %s"), rebase_merges);
1447 options.rebase_merges = 1;
1448 imply_merge(&options, "--rebase-merges");
1451 if (options.type == REBASE_APPLY) {
1452 if (ignore_whitespace)
1453 strvec_push(&options.git_am_opts,
1454 "--ignore-whitespace");
1455 if (options.committer_date_is_author_date)
1456 strvec_push(&options.git_am_opts,
1457 "--committer-date-is-author-date");
1458 if (options.ignore_date)
1459 strvec_push(&options.git_am_opts, "--ignore-date");
1460 } else {
1461 /* REBASE_MERGE */
1462 if (ignore_whitespace) {
1463 string_list_append(&strategy_options,
1464 "ignore-space-change");
1468 if (strategy_options.nr) {
1469 int i;
1471 if (!options.strategy)
1472 options.strategy = "ort";
1474 strbuf_reset(&buf);
1475 for (i = 0; i < strategy_options.nr; i++)
1476 strbuf_addf(&buf, " --%s",
1477 strategy_options.items[i].string);
1478 options.strategy_opts = xstrdup(buf.buf);
1481 if (options.strategy) {
1482 options.strategy = xstrdup(options.strategy);
1483 switch (options.type) {
1484 case REBASE_APPLY:
1485 die(_("--strategy requires --merge or --interactive"));
1486 case REBASE_MERGE:
1487 /* compatible */
1488 break;
1489 case REBASE_UNSPECIFIED:
1490 options.type = REBASE_MERGE;
1491 break;
1492 default:
1493 BUG("unhandled rebase type (%d)", options.type);
1497 if (options.type == REBASE_MERGE)
1498 imply_merge(&options, "--merge");
1500 if (options.root && !options.onto_name)
1501 imply_merge(&options, "--root without --onto");
1503 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1504 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1506 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1507 /* all am options except -q are compatible only with --apply */
1508 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1509 if (strcmp(options.git_am_opts.v[i], "-q"))
1510 break;
1512 if (i >= 0) {
1513 if (is_merge(&options))
1514 die(_("apply options and merge options "
1515 "cannot be used together"));
1516 else
1517 options.type = REBASE_APPLY;
1521 if (options.type == REBASE_UNSPECIFIED) {
1522 if (!strcmp(options.default_backend, "merge"))
1523 imply_merge(&options, "--merge");
1524 else if (!strcmp(options.default_backend, "apply"))
1525 options.type = REBASE_APPLY;
1526 else
1527 die(_("Unknown rebase backend: %s"),
1528 options.default_backend);
1531 if (options.type == REBASE_MERGE &&
1532 !options.strategy &&
1533 getenv("GIT_TEST_MERGE_ALGORITHM"))
1534 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1536 switch (options.type) {
1537 case REBASE_MERGE:
1538 options.state_dir = merge_dir();
1539 break;
1540 case REBASE_APPLY:
1541 options.state_dir = apply_dir();
1542 break;
1543 default:
1544 BUG("options.type was just set above; should be unreachable.");
1547 if (options.empty == EMPTY_UNSPECIFIED) {
1548 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1549 options.empty = EMPTY_ASK;
1550 else if (exec.nr > 0)
1551 options.empty = EMPTY_KEEP;
1552 else
1553 options.empty = EMPTY_DROP;
1555 if (reschedule_failed_exec > 0 && !is_merge(&options))
1556 die(_("--reschedule-failed-exec requires "
1557 "--exec or --interactive"));
1558 if (reschedule_failed_exec >= 0)
1559 options.reschedule_failed_exec = reschedule_failed_exec;
1561 if (options.signoff) {
1562 strvec_push(&options.git_am_opts, "--signoff");
1563 options.flags |= REBASE_FORCE;
1566 if (!options.root) {
1567 if (argc < 1) {
1568 struct branch *branch;
1570 branch = branch_get(NULL);
1571 options.upstream_name = branch_get_upstream(branch,
1572 NULL);
1573 if (!options.upstream_name)
1574 error_on_missing_default_upstream();
1575 if (options.fork_point < 0)
1576 options.fork_point = 1;
1577 } else {
1578 options.upstream_name = argv[0];
1579 argc--;
1580 argv++;
1581 if (!strcmp(options.upstream_name, "-"))
1582 options.upstream_name = "@{-1}";
1584 options.upstream =
1585 lookup_commit_reference_by_name(options.upstream_name);
1586 if (!options.upstream)
1587 die(_("invalid upstream '%s'"), options.upstream_name);
1588 options.upstream_arg = options.upstream_name;
1589 } else {
1590 if (!options.onto_name) {
1591 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1592 &squash_onto, NULL, NULL) < 0)
1593 die(_("Could not create new root commit"));
1594 options.squash_onto = &squash_onto;
1595 options.onto_name = squash_onto_name =
1596 xstrdup(oid_to_hex(&squash_onto));
1597 } else
1598 options.root_with_onto = 1;
1600 options.upstream_name = NULL;
1601 options.upstream = NULL;
1602 if (argc > 1)
1603 usage_with_options(builtin_rebase_usage,
1604 builtin_rebase_options);
1605 options.upstream_arg = "--root";
1609 * If the branch to rebase is given, that is the branch we will rebase
1610 * branch_name -- branch/commit being rebased, or
1611 * HEAD (already detached)
1612 * orig_head -- commit object name of tip of the branch before rebasing
1613 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1615 if (argc == 1) {
1616 /* Is it "rebase other branchname" or "rebase other commit"? */
1617 struct object_id branch_oid;
1618 branch_name = argv[0];
1619 options.switch_to = argv[0];
1621 /* Is it a local branch? */
1622 strbuf_reset(&buf);
1623 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1624 if (!read_ref(buf.buf, &branch_oid)) {
1625 die_if_checked_out(buf.buf, 1);
1626 options.head_name = xstrdup(buf.buf);
1627 options.orig_head =
1628 lookup_commit_object(the_repository,
1629 &branch_oid);
1630 /* If not is it a valid ref (branch or commit)? */
1631 } else {
1632 options.orig_head =
1633 lookup_commit_reference_by_name(branch_name);
1634 options.head_name = NULL;
1636 if (!options.orig_head)
1637 die(_("no such branch/commit '%s'"), branch_name);
1638 } else if (argc == 0) {
1639 /* Do not need to switch branches, we are already on it. */
1640 options.head_name =
1641 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1642 &flags));
1643 if (!options.head_name)
1644 die(_("No such ref: %s"), "HEAD");
1645 if (flags & REF_ISSYMREF) {
1646 if (!skip_prefix(options.head_name,
1647 "refs/heads/", &branch_name))
1648 branch_name = options.head_name;
1650 } else {
1651 FREE_AND_NULL(options.head_name);
1652 branch_name = "HEAD";
1654 options.orig_head = lookup_commit_reference_by_name("HEAD");
1655 if (!options.orig_head)
1656 die(_("Could not resolve HEAD to a commit"));
1657 } else
1658 BUG("unexpected number of arguments left to parse");
1660 /* Make sure the branch to rebase onto is valid. */
1661 if (keep_base) {
1662 strbuf_reset(&buf);
1663 strbuf_addstr(&buf, options.upstream_name);
1664 strbuf_addstr(&buf, "...");
1665 strbuf_addstr(&buf, branch_name);
1666 options.onto_name = xstrdup(buf.buf);
1667 } else if (!options.onto_name)
1668 options.onto_name = options.upstream_name;
1669 if (strstr(options.onto_name, "...")) {
1670 if (get_oid_mb(options.onto_name, &branch_base) < 0) {
1671 if (keep_base)
1672 die(_("'%s': need exactly one merge base with branch"),
1673 options.upstream_name);
1674 else
1675 die(_("'%s': need exactly one merge base"),
1676 options.onto_name);
1678 options.onto = lookup_commit_or_die(&branch_base,
1679 options.onto_name);
1680 } else {
1681 options.onto =
1682 lookup_commit_reference_by_name(options.onto_name);
1683 if (!options.onto)
1684 die(_("Does not point to a valid commit '%s'"),
1685 options.onto_name);
1686 fill_branch_base(&options, &branch_base);
1689 if (keep_base && options.reapply_cherry_picks)
1690 options.upstream = options.onto;
1692 if (options.fork_point > 0)
1693 options.restrict_revision =
1694 get_fork_point(options.upstream_name, options.orig_head);
1696 if (repo_read_index(the_repository) < 0)
1697 die(_("could not read index"));
1699 if (options.autostash)
1700 create_autostash(the_repository,
1701 state_dir_path("autostash", &options));
1704 if (require_clean_work_tree(the_repository, "rebase",
1705 _("Please commit or stash them."), 1, 1)) {
1706 ret = -1;
1707 goto cleanup;
1711 * Now we are rebasing commits upstream..orig_head (or with --root,
1712 * everything leading up to orig_head) on top of onto.
1716 * Check if we are already based on onto with linear history,
1717 * in which case we could fast-forward without replacing the commits
1718 * with new commits recreated by replaying their changes.
1720 if (allow_preemptive_ff &&
1721 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1722 options.orig_head, &branch_base)) {
1723 int flag;
1725 if (!(options.flags & REBASE_FORCE)) {
1726 /* Lazily switch to the target branch if needed... */
1727 if (options.switch_to) {
1728 ret = checkout_up_to_date(&options);
1729 if (ret)
1730 goto cleanup;
1733 if (!(options.flags & REBASE_NO_QUIET))
1734 ; /* be quiet */
1735 else if (!strcmp(branch_name, "HEAD") &&
1736 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1737 puts(_("HEAD is up to date."));
1738 else
1739 printf(_("Current branch %s is up to date.\n"),
1740 branch_name);
1741 ret = finish_rebase(&options);
1742 goto cleanup;
1743 } else if (!(options.flags & REBASE_NO_QUIET))
1744 ; /* be quiet */
1745 else if (!strcmp(branch_name, "HEAD") &&
1746 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1747 puts(_("HEAD is up to date, rebase forced."));
1748 else
1749 printf(_("Current branch %s is up to date, rebase "
1750 "forced.\n"), branch_name);
1753 /* If a hook exists, give it a chance to interrupt*/
1754 if (!ok_to_skip_pre_rebase &&
1755 run_hooks_l("pre-rebase", options.upstream_arg,
1756 argc ? argv[0] : NULL, NULL))
1757 die(_("The pre-rebase hook refused to rebase."));
1759 if (options.flags & REBASE_DIFFSTAT) {
1760 struct diff_options opts;
1762 if (options.flags & REBASE_VERBOSE) {
1763 if (is_null_oid(&branch_base))
1764 printf(_("Changes to %s:\n"),
1765 oid_to_hex(&options.onto->object.oid));
1766 else
1767 printf(_("Changes from %s to %s:\n"),
1768 oid_to_hex(&branch_base),
1769 oid_to_hex(&options.onto->object.oid));
1772 /* We want color (if set), but no pager */
1773 diff_setup(&opts);
1774 opts.stat_width = -1; /* use full terminal width */
1775 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1776 opts.output_format |=
1777 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1778 opts.detect_rename = DIFF_DETECT_RENAME;
1779 diff_setup_done(&opts);
1780 diff_tree_oid(is_null_oid(&branch_base) ?
1781 the_hash_algo->empty_tree : &branch_base,
1782 &options.onto->object.oid, "", &opts);
1783 diffcore_std(&opts);
1784 diff_flush(&opts);
1787 if (is_merge(&options))
1788 goto run_rebase;
1790 /* Detach HEAD and reset the tree */
1791 if (options.flags & REBASE_NO_QUIET)
1792 printf(_("First, rewinding head to replay your work on top of "
1793 "it...\n"));
1795 strbuf_addf(&msg, "%s: checkout %s",
1796 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1797 ropts.oid = &options.onto->object.oid;
1798 ropts.orig_head = &options.orig_head->object.oid,
1799 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1800 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1801 ropts.head_msg = msg.buf;
1802 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1803 if (reset_head(the_repository, &ropts))
1804 die(_("Could not detach HEAD"));
1805 strbuf_release(&msg);
1808 * If the onto is a proper descendant of the tip of the branch, then
1809 * we just fast-forwarded.
1811 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1812 printf(_("Fast-forwarded %s to %s.\n"),
1813 branch_name, options.onto_name);
1814 move_to_original_branch(&options);
1815 ret = finish_rebase(&options);
1816 goto cleanup;
1819 strbuf_addf(&revisions, "%s..%s",
1820 options.root ? oid_to_hex(&options.onto->object.oid) :
1821 (options.restrict_revision ?
1822 oid_to_hex(&options.restrict_revision->object.oid) :
1823 oid_to_hex(&options.upstream->object.oid)),
1824 oid_to_hex(&options.orig_head->object.oid));
1826 options.revisions = revisions.buf;
1828 run_rebase:
1829 ret = run_specific_rebase(&options, action);
1831 cleanup:
1832 strbuf_release(&buf);
1833 strbuf_release(&revisions);
1834 free(options.head_name);
1835 free(options.gpg_sign_opt);
1836 free(options.cmd);
1837 free(options.strategy);
1838 strbuf_release(&options.git_format_patch_opt);
1839 free(squash_onto_name);
1840 return !!ret;