pack-bitmap: improve grammar of "xor chain" error message
[git/debian.git] / builtin / rebase.c
blob56e4214b44104a445f8b68d185c0aadd3442247d
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 object_id 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;
105 int update_refs;
108 #define REBASE_OPTIONS_INIT { \
109 .type = REBASE_UNSPECIFIED, \
110 .empty = EMPTY_UNSPECIFIED, \
111 .keep_empty = 1, \
112 .default_backend = "merge", \
113 .flags = REBASE_NO_QUIET, \
114 .git_am_opts = STRVEC_INIT, \
115 .git_format_patch_opt = STRBUF_INIT, \
116 .fork_point = -1, \
119 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
121 struct replay_opts replay = REPLAY_OPTS_INIT;
123 replay.action = REPLAY_INTERACTIVE_REBASE;
124 replay.strategy = NULL;
125 sequencer_init_config(&replay);
127 replay.signoff = opts->signoff;
128 replay.allow_ff = !(opts->flags & REBASE_FORCE);
129 if (opts->allow_rerere_autoupdate)
130 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
131 replay.allow_empty = 1;
132 replay.allow_empty_message = opts->allow_empty_message;
133 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
134 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
135 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
136 replay.verbose = opts->flags & REBASE_VERBOSE;
137 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
138 replay.committer_date_is_author_date =
139 opts->committer_date_is_author_date;
140 replay.ignore_date = opts->ignore_date;
141 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
142 if (opts->strategy)
143 replay.strategy = xstrdup_or_null(opts->strategy);
144 else if (!replay.strategy && replay.default_strategy) {
145 replay.strategy = replay.default_strategy;
146 replay.default_strategy = NULL;
149 if (opts->strategy_opts)
150 parse_strategy_opts(&replay, opts->strategy_opts);
152 if (opts->squash_onto) {
153 oidcpy(&replay.squash_onto, opts->squash_onto);
154 replay.have_squash_onto = 1;
157 return replay;
160 enum action {
161 ACTION_NONE = 0,
162 ACTION_CONTINUE,
163 ACTION_SKIP,
164 ACTION_ABORT,
165 ACTION_QUIT,
166 ACTION_EDIT_TODO,
167 ACTION_SHOW_CURRENT_PATCH
170 static const char *action_names[] = { "undefined",
171 "continue",
172 "skip",
173 "abort",
174 "quit",
175 "edit_todo",
176 "show_current_patch" };
178 static int edit_todo_file(unsigned flags)
180 const char *todo_file = rebase_path_todo();
181 struct todo_list todo_list = TODO_LIST_INIT,
182 new_todo = TODO_LIST_INIT;
183 int res = 0;
185 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
186 return error_errno(_("could not read '%s'."), todo_file);
188 strbuf_stripspace(&todo_list.buf, 1);
189 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
190 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
191 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
192 res = error_errno(_("could not write '%s'"), todo_file);
194 todo_list_release(&todo_list);
195 todo_list_release(&new_todo);
197 return res;
200 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
201 struct object_id *orig_head, char **revisions,
202 char **shortrevisions)
204 struct commit *base_rev = upstream ? upstream : onto;
205 const char *shorthead;
207 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
208 oid_to_hex(orig_head));
210 shorthead = find_unique_abbrev(orig_head, DEFAULT_ABBREV);
212 if (upstream) {
213 const char *shortrev;
215 shortrev = find_unique_abbrev(&base_rev->object.oid,
216 DEFAULT_ABBREV);
218 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
219 } else
220 *shortrevisions = xstrdup(shorthead);
222 return 0;
225 static int init_basic_state(struct replay_opts *opts, const char *head_name,
226 struct commit *onto,
227 const struct object_id *orig_head)
229 FILE *interactive;
231 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
232 return error_errno(_("could not create temporary %s"), merge_dir());
234 delete_reflog("REBASE_HEAD");
236 interactive = fopen(path_interactive(), "w");
237 if (!interactive)
238 return error_errno(_("could not mark as interactive"));
239 fclose(interactive);
241 return write_basic_state(opts, head_name, onto, orig_head);
244 static void split_exec_commands(const char *cmd, struct string_list *commands)
246 if (cmd && *cmd) {
247 string_list_split(commands, cmd, '\n', -1);
249 /* rebase.c adds a new line to cmd after every command,
250 * so here the last command is always empty */
251 string_list_remove_empty_items(commands, 0);
255 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
257 int ret;
258 char *revisions = NULL, *shortrevisions = NULL;
259 struct strvec make_script_args = STRVEC_INIT;
260 struct todo_list todo_list = TODO_LIST_INIT;
261 struct replay_opts replay = get_replay_opts(opts);
262 struct string_list commands = STRING_LIST_INIT_DUP;
264 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head,
265 &revisions, &shortrevisions))
266 return -1;
268 if (init_basic_state(&replay,
269 opts->head_name ? opts->head_name : "detached HEAD",
270 opts->onto, &opts->orig_head)) {
271 free(revisions);
272 free(shortrevisions);
274 return -1;
277 if (!opts->upstream && opts->squash_onto)
278 write_file(path_squash_onto(), "%s\n",
279 oid_to_hex(opts->squash_onto));
281 strvec_pushl(&make_script_args, "", revisions, NULL);
282 if (opts->restrict_revision)
283 strvec_pushf(&make_script_args, "^%s",
284 oid_to_hex(&opts->restrict_revision->object.oid));
286 ret = sequencer_make_script(the_repository, &todo_list.buf,
287 make_script_args.nr, make_script_args.v,
288 flags);
290 if (ret)
291 error(_("could not generate todo list"));
292 else {
293 discard_cache();
294 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
295 &todo_list))
296 BUG("unusable todo list");
298 split_exec_commands(opts->cmd, &commands);
299 ret = complete_action(the_repository, &replay, flags,
300 shortrevisions, opts->onto_name, opts->onto,
301 &opts->orig_head, &commands, opts->autosquash,
302 opts->update_refs,
303 &todo_list);
306 string_list_clear(&commands, 0);
307 free(revisions);
308 free(shortrevisions);
309 todo_list_release(&todo_list);
310 strvec_clear(&make_script_args);
312 return ret;
315 static int run_sequencer_rebase(struct rebase_options *opts,
316 enum action command)
318 unsigned flags = 0;
319 int abbreviate_commands = 0, ret = 0;
321 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
323 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
324 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
325 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
326 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
327 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
328 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
329 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
331 switch (command) {
332 case ACTION_NONE: {
333 if (!opts->onto && !opts->upstream)
334 die(_("a base commit must be provided with --upstream or --onto"));
336 ret = do_interactive_rebase(opts, flags);
337 break;
339 case ACTION_SKIP: {
340 struct string_list merge_rr = STRING_LIST_INIT_DUP;
342 rerere_clear(the_repository, &merge_rr);
344 /* fallthrough */
345 case ACTION_CONTINUE: {
346 struct replay_opts replay_opts = get_replay_opts(opts);
348 ret = sequencer_continue(the_repository, &replay_opts);
349 break;
351 case ACTION_EDIT_TODO:
352 ret = edit_todo_file(flags);
353 break;
354 case ACTION_SHOW_CURRENT_PATCH: {
355 struct child_process cmd = CHILD_PROCESS_INIT;
357 cmd.git_cmd = 1;
358 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
359 ret = run_command(&cmd);
361 break;
363 default:
364 BUG("invalid command '%d'", command);
367 return ret;
370 static void imply_merge(struct rebase_options *opts, const char *option);
371 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
372 int unset)
374 struct rebase_options *opts = opt->value;
376 BUG_ON_OPT_ARG(arg);
378 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
379 opts->keep_empty = !unset;
380 opts->type = REBASE_MERGE;
381 return 0;
384 static int is_merge(struct rebase_options *opts)
386 return opts->type == REBASE_MERGE;
389 static void imply_merge(struct rebase_options *opts, const char *option)
391 switch (opts->type) {
392 case REBASE_APPLY:
393 die(_("%s requires the merge backend"), option);
394 break;
395 case REBASE_MERGE:
396 break;
397 default:
398 opts->type = REBASE_MERGE; /* implied */
399 break;
403 /* Returns the filename prefixed by the state_dir */
404 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
406 static struct strbuf path = STRBUF_INIT;
407 static size_t prefix_len;
409 if (!prefix_len) {
410 strbuf_addf(&path, "%s/", opts->state_dir);
411 prefix_len = path.len;
414 strbuf_setlen(&path, prefix_len);
415 strbuf_addstr(&path, filename);
416 return path.buf;
419 /* Initialize the rebase options from the state directory. */
420 static int read_basic_state(struct rebase_options *opts)
422 struct strbuf head_name = STRBUF_INIT;
423 struct strbuf buf = STRBUF_INIT;
424 struct object_id oid;
426 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
427 READ_ONELINER_WARN_MISSING) ||
428 !read_oneliner(&buf, state_dir_path("onto", opts),
429 READ_ONELINER_WARN_MISSING))
430 return -1;
431 opts->head_name = starts_with(head_name.buf, "refs/") ?
432 xstrdup(head_name.buf) : NULL;
433 strbuf_release(&head_name);
434 if (get_oid(buf.buf, &oid))
435 return error(_("could not get 'onto': '%s'"), buf.buf);
436 opts->onto = lookup_commit_or_die(&oid, buf.buf);
439 * We always write to orig-head, but interactive rebase used to write to
440 * head. Fall back to reading from head to cover for the case that the
441 * user upgraded git with an ongoing interactive rebase.
443 strbuf_reset(&buf);
444 if (file_exists(state_dir_path("orig-head", opts))) {
445 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
446 READ_ONELINER_WARN_MISSING))
447 return -1;
448 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
449 READ_ONELINER_WARN_MISSING))
450 return -1;
451 if (get_oid(buf.buf, &opts->orig_head))
452 return error(_("invalid orig-head: '%s'"), buf.buf);
454 if (file_exists(state_dir_path("quiet", opts)))
455 opts->flags &= ~REBASE_NO_QUIET;
456 else
457 opts->flags |= REBASE_NO_QUIET;
459 if (file_exists(state_dir_path("verbose", opts)))
460 opts->flags |= REBASE_VERBOSE;
462 if (file_exists(state_dir_path("signoff", opts))) {
463 opts->signoff = 1;
464 opts->flags |= REBASE_FORCE;
467 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
468 strbuf_reset(&buf);
469 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
470 READ_ONELINER_WARN_MISSING))
471 return -1;
472 if (!strcmp(buf.buf, "--rerere-autoupdate"))
473 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
474 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
475 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
476 else
477 warning(_("ignoring invalid allow_rerere_autoupdate: "
478 "'%s'"), buf.buf);
481 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
482 strbuf_reset(&buf);
483 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
484 READ_ONELINER_WARN_MISSING))
485 return -1;
486 free(opts->gpg_sign_opt);
487 opts->gpg_sign_opt = xstrdup(buf.buf);
490 if (file_exists(state_dir_path("strategy", opts))) {
491 strbuf_reset(&buf);
492 if (!read_oneliner(&buf, state_dir_path("strategy", opts),
493 READ_ONELINER_WARN_MISSING))
494 return -1;
495 free(opts->strategy);
496 opts->strategy = xstrdup(buf.buf);
499 if (file_exists(state_dir_path("strategy_opts", opts))) {
500 strbuf_reset(&buf);
501 if (!read_oneliner(&buf, state_dir_path("strategy_opts", opts),
502 READ_ONELINER_WARN_MISSING))
503 return -1;
504 free(opts->strategy_opts);
505 opts->strategy_opts = xstrdup(buf.buf);
508 strbuf_release(&buf);
510 return 0;
513 static int rebase_write_basic_state(struct rebase_options *opts)
515 write_file(state_dir_path("head-name", opts), "%s",
516 opts->head_name ? opts->head_name : "detached HEAD");
517 write_file(state_dir_path("onto", opts), "%s",
518 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
519 write_file(state_dir_path("orig-head", opts), "%s",
520 oid_to_hex(&opts->orig_head));
521 if (!(opts->flags & REBASE_NO_QUIET))
522 write_file(state_dir_path("quiet", opts), "%s", "");
523 if (opts->flags & REBASE_VERBOSE)
524 write_file(state_dir_path("verbose", opts), "%s", "");
525 if (opts->strategy)
526 write_file(state_dir_path("strategy", opts), "%s",
527 opts->strategy);
528 if (opts->strategy_opts)
529 write_file(state_dir_path("strategy_opts", opts), "%s",
530 opts->strategy_opts);
531 if (opts->allow_rerere_autoupdate > 0)
532 write_file(state_dir_path("allow_rerere_autoupdate", opts),
533 "-%s-rerere-autoupdate",
534 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
535 "" : "-no");
536 if (opts->gpg_sign_opt)
537 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
538 opts->gpg_sign_opt);
539 if (opts->signoff)
540 write_file(state_dir_path("signoff", opts), "--signoff");
542 return 0;
545 static int finish_rebase(struct rebase_options *opts)
547 struct strbuf dir = STRBUF_INIT;
548 int ret = 0;
550 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
551 unlink(git_path_auto_merge(the_repository));
552 apply_autostash(state_dir_path("autostash", opts));
554 * We ignore errors in 'git maintenance run --auto', since the
555 * user should see them.
557 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
558 if (opts->type == REBASE_MERGE) {
559 struct replay_opts replay = REPLAY_OPTS_INIT;
561 replay.action = REPLAY_INTERACTIVE_REBASE;
562 ret = sequencer_remove_state(&replay);
563 } else {
564 strbuf_addstr(&dir, opts->state_dir);
565 if (remove_dir_recursively(&dir, 0))
566 ret = error(_("could not remove '%s'"),
567 opts->state_dir);
568 strbuf_release(&dir);
571 return ret;
574 static int move_to_original_branch(struct rebase_options *opts)
576 struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
577 struct reset_head_opts ropts = { 0 };
578 int ret;
580 if (!opts->head_name)
581 return 0; /* nothing to move back to */
583 if (!opts->onto)
584 BUG("move_to_original_branch without onto");
586 strbuf_addf(&branch_reflog, "rebase finished: %s onto %s",
587 opts->head_name, oid_to_hex(&opts->onto->object.oid));
588 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
589 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));
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;
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.updaterefs")) {
806 opts->update_refs = git_config_bool(var, value);
807 return 0;
810 if (!strcmp(var, "rebase.reschedulefailedexec")) {
811 opts->reschedule_failed_exec = git_config_bool(var, value);
812 return 0;
815 if (!strcmp(var, "rebase.forkpoint")) {
816 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
817 return 0;
820 if (!strcmp(var, "rebase.backend")) {
821 return git_config_string(&opts->default_backend, var, value);
824 return git_default_config(var, value, data);
827 static int checkout_up_to_date(struct rebase_options *options)
829 struct strbuf buf = STRBUF_INIT;
830 struct reset_head_opts ropts = { 0 };
831 int ret = 0;
833 strbuf_addf(&buf, "%s: checkout %s",
834 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
835 options->switch_to);
836 ropts.oid = &options->orig_head;
837 ropts.branch = options->head_name;
838 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
839 if (!ropts.branch)
840 ropts.flags |= RESET_HEAD_DETACH;
841 ropts.head_msg = buf.buf;
842 if (reset_head(the_repository, &ropts) < 0)
843 ret = error(_("could not switch to %s"), options->switch_to);
844 strbuf_release(&buf);
846 return ret;
850 * Determines whether the commits in from..to are linear, i.e. contain
851 * no merge commits. This function *expects* `from` to be an ancestor of
852 * `to`.
854 static int is_linear_history(struct commit *from, struct commit *to)
856 while (to && to != from) {
857 parse_commit(to);
858 if (!to->parents)
859 return 1;
860 if (to->parents->next)
861 return 0;
862 to = to->parents->item;
864 return 1;
867 static int can_fast_forward(struct commit *onto, struct commit *upstream,
868 struct commit *restrict_revision,
869 struct object_id *head_oid, struct object_id *merge_base)
871 struct commit *head = lookup_commit(the_repository, head_oid);
872 struct commit_list *merge_bases = NULL;
873 int res = 0;
875 if (!head)
876 goto done;
878 merge_bases = get_merge_bases(onto, head);
879 if (!merge_bases || merge_bases->next) {
880 oidcpy(merge_base, null_oid());
881 goto done;
884 oidcpy(merge_base, &merge_bases->item->object.oid);
885 if (!oideq(merge_base, &onto->object.oid))
886 goto done;
888 if (restrict_revision && !oideq(&restrict_revision->object.oid, merge_base))
889 goto done;
891 if (!upstream)
892 goto done;
894 free_commit_list(merge_bases);
895 merge_bases = get_merge_bases(upstream, head);
896 if (!merge_bases || merge_bases->next)
897 goto done;
899 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
900 goto done;
902 res = 1;
904 done:
905 free_commit_list(merge_bases);
906 return res && is_linear_history(onto, head);
909 static 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 merge_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 OPT_BOOL(0, "update-refs", &options.update_refs,
1135 N_("update branches that point to commits "
1136 "that are being rebased")),
1137 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1138 N_("GPG-sign commits"),
1139 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1140 OPT_AUTOSTASH(&options.autostash),
1141 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1142 N_("add exec lines after each commit of the "
1143 "editable list")),
1144 OPT_BOOL_F(0, "allow-empty-message",
1145 &options.allow_empty_message,
1146 N_("allow rebasing commits with empty messages"),
1147 PARSE_OPT_HIDDEN),
1148 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1149 N_("mode"),
1150 N_("try to rebase merges instead of skipping them"),
1151 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1152 OPT_BOOL(0, "fork-point", &options.fork_point,
1153 N_("use 'merge-base --fork-point' to refine upstream")),
1154 OPT_STRING('s', "strategy", &options.strategy,
1155 N_("strategy"), N_("use the given merge strategy")),
1156 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1157 N_("option"),
1158 N_("pass the argument through to the merge "
1159 "strategy")),
1160 OPT_BOOL(0, "root", &options.root,
1161 N_("rebase all reachable commits up to the root(s)")),
1162 OPT_BOOL(0, "reschedule-failed-exec",
1163 &reschedule_failed_exec,
1164 N_("automatically re-schedule any `exec` that fails")),
1165 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1166 N_("apply all changes, even those already present upstream")),
1167 OPT_END(),
1169 int i;
1171 if (argc == 2 && !strcmp(argv[1], "-h"))
1172 usage_with_options(builtin_rebase_usage,
1173 builtin_rebase_options);
1175 prepare_repo_settings(the_repository);
1176 the_repository->settings.command_requires_full_index = 0;
1178 options.allow_empty_message = 1;
1179 git_config(rebase_config, &options);
1180 /* options.gpg_sign_opt will be either "-S" or NULL */
1181 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1182 FREE_AND_NULL(options.gpg_sign_opt);
1184 strbuf_reset(&buf);
1185 strbuf_addf(&buf, "%s/applying", apply_dir());
1186 if(file_exists(buf.buf))
1187 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1189 if (is_directory(apply_dir())) {
1190 options.type = REBASE_APPLY;
1191 options.state_dir = apply_dir();
1192 } else if (is_directory(merge_dir())) {
1193 strbuf_reset(&buf);
1194 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1195 if (!(action == ACTION_ABORT) && is_directory(buf.buf)) {
1196 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1197 "Use `git rebase --abort` to terminate current rebase.\n"
1198 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1199 } else {
1200 strbuf_reset(&buf);
1201 strbuf_addf(&buf, "%s/interactive", merge_dir());
1202 options.type = REBASE_MERGE;
1203 if (file_exists(buf.buf))
1204 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1206 options.state_dir = merge_dir();
1209 if (options.type != REBASE_UNSPECIFIED)
1210 in_progress = 1;
1212 total_argc = argc;
1213 argc = parse_options(argc, argv, prefix,
1214 builtin_rebase_options,
1215 builtin_rebase_usage, 0);
1217 if (preserve_merges_selected)
1218 die(_("--preserve-merges was replaced by --rebase-merges\n"
1219 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1220 "which is no longer supported; use 'merges' instead"));
1222 if (action != ACTION_NONE && total_argc != 2) {
1223 usage_with_options(builtin_rebase_usage,
1224 builtin_rebase_options);
1227 if (argc > 2)
1228 usage_with_options(builtin_rebase_usage,
1229 builtin_rebase_options);
1231 if (keep_base) {
1232 if (options.onto_name)
1233 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1234 if (options.root)
1235 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1238 if (options.root && options.fork_point > 0)
1239 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1241 if (action != ACTION_NONE && !in_progress)
1242 die(_("No rebase in progress?"));
1243 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1245 if (action == ACTION_EDIT_TODO && !is_merge(&options))
1246 die(_("The --edit-todo action can only be used during "
1247 "interactive rebase."));
1249 if (trace2_is_enabled()) {
1250 if (is_merge(&options))
1251 trace2_cmd_mode("interactive");
1252 else if (exec.nr)
1253 trace2_cmd_mode("interactive-exec");
1254 else
1255 trace2_cmd_mode(action_names[action]);
1258 switch (action) {
1259 case ACTION_CONTINUE: {
1260 struct object_id head;
1261 struct lock_file lock_file = LOCK_INIT;
1262 int fd;
1264 options.action = "continue";
1265 set_reflog_action(&options);
1267 /* Sanity check */
1268 if (get_oid("HEAD", &head))
1269 die(_("Cannot read HEAD"));
1271 fd = hold_locked_index(&lock_file, 0);
1272 if (repo_read_index(the_repository) < 0)
1273 die(_("could not read index"));
1274 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1275 NULL);
1276 if (0 <= fd)
1277 repo_update_index_if_able(the_repository, &lock_file);
1278 rollback_lock_file(&lock_file);
1280 if (has_unstaged_changes(the_repository, 1)) {
1281 puts(_("You must edit all merge conflicts and then\n"
1282 "mark them as resolved using git add"));
1283 exit(1);
1285 if (read_basic_state(&options))
1286 exit(1);
1287 goto run_rebase;
1289 case ACTION_SKIP: {
1290 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1292 options.action = "skip";
1293 set_reflog_action(&options);
1295 rerere_clear(the_repository, &merge_rr);
1296 string_list_clear(&merge_rr, 1);
1297 ropts.flags = RESET_HEAD_HARD;
1298 if (reset_head(the_repository, &ropts) < 0)
1299 die(_("could not discard worktree changes"));
1300 remove_branch_state(the_repository, 0);
1301 if (read_basic_state(&options))
1302 exit(1);
1303 goto run_rebase;
1305 case ACTION_ABORT: {
1306 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1307 options.action = "abort";
1308 set_reflog_action(&options);
1310 rerere_clear(the_repository, &merge_rr);
1311 string_list_clear(&merge_rr, 1);
1313 if (read_basic_state(&options))
1314 exit(1);
1315 ropts.oid = &options.orig_head;
1316 ropts.branch = options.head_name;
1317 ropts.flags = RESET_HEAD_HARD;
1318 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1319 if (reset_head(the_repository, &ropts) < 0)
1320 die(_("could not move back to %s"),
1321 oid_to_hex(&options.orig_head));
1322 remove_branch_state(the_repository, 0);
1323 ret = finish_rebase(&options);
1324 goto cleanup;
1326 case ACTION_QUIT: {
1327 save_autostash(state_dir_path("autostash", &options));
1328 if (options.type == REBASE_MERGE) {
1329 struct replay_opts replay = REPLAY_OPTS_INIT;
1331 replay.action = REPLAY_INTERACTIVE_REBASE;
1332 ret = sequencer_remove_state(&replay);
1333 } else {
1334 strbuf_reset(&buf);
1335 strbuf_addstr(&buf, options.state_dir);
1336 ret = remove_dir_recursively(&buf, 0);
1337 if (ret)
1338 error(_("could not remove '%s'"),
1339 options.state_dir);
1341 goto cleanup;
1343 case ACTION_EDIT_TODO:
1344 options.action = "edit-todo";
1345 options.dont_finish_rebase = 1;
1346 goto run_rebase;
1347 case ACTION_SHOW_CURRENT_PATCH:
1348 options.action = "show-current-patch";
1349 options.dont_finish_rebase = 1;
1350 goto run_rebase;
1351 case ACTION_NONE:
1352 break;
1353 default:
1354 BUG("action: %d", action);
1357 /* Make sure no rebase is in progress */
1358 if (in_progress) {
1359 const char *last_slash = strrchr(options.state_dir, '/');
1360 const char *state_dir_base =
1361 last_slash ? last_slash + 1 : options.state_dir;
1362 const char *cmd_live_rebase =
1363 "git rebase (--continue | --abort | --skip)";
1364 strbuf_reset(&buf);
1365 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1366 die(_("It seems that there is already a %s directory, and\n"
1367 "I wonder if you are in the middle of another rebase. "
1368 "If that is the\n"
1369 "case, please try\n\t%s\n"
1370 "If that is not the case, please\n\t%s\n"
1371 "and run me again. I am stopping in case you still "
1372 "have something\n"
1373 "valuable there.\n"),
1374 state_dir_base, cmd_live_rebase, buf.buf);
1377 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1378 (action != ACTION_NONE) ||
1379 (exec.nr > 0) ||
1380 options.autosquash) {
1381 allow_preemptive_ff = 0;
1383 if (options.committer_date_is_author_date || options.ignore_date)
1384 options.flags |= REBASE_FORCE;
1386 for (i = 0; i < options.git_am_opts.nr; i++) {
1387 const char *option = options.git_am_opts.v[i], *p;
1388 if (!strcmp(option, "--whitespace=fix") ||
1389 !strcmp(option, "--whitespace=strip"))
1390 allow_preemptive_ff = 0;
1391 else if (skip_prefix(option, "-C", &p)) {
1392 while (*p)
1393 if (!isdigit(*(p++)))
1394 die(_("switch `C' expects a "
1395 "numerical value"));
1396 } else if (skip_prefix(option, "--whitespace=", &p)) {
1397 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1398 strcmp(p, "error") && strcmp(p, "error-all"))
1399 die("Invalid whitespace option: '%s'", p);
1403 for (i = 0; i < exec.nr; i++)
1404 if (check_exec_cmd(exec.items[i].string))
1405 exit(1);
1407 if (!(options.flags & REBASE_NO_QUIET))
1408 strvec_push(&options.git_am_opts, "-q");
1410 if (options.empty != EMPTY_UNSPECIFIED)
1411 imply_merge(&options, "--empty");
1413 if (options.reapply_cherry_picks)
1414 imply_merge(&options, "--reapply-cherry-picks");
1416 if (gpg_sign)
1417 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1419 if (exec.nr) {
1420 int i;
1422 imply_merge(&options, "--exec");
1424 strbuf_reset(&buf);
1425 for (i = 0; i < exec.nr; i++)
1426 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1427 options.cmd = xstrdup(buf.buf);
1430 if (rebase_merges) {
1431 if (!*rebase_merges)
1432 ; /* default mode; do nothing */
1433 else if (!strcmp("rebase-cousins", rebase_merges))
1434 options.rebase_cousins = 1;
1435 else if (strcmp("no-rebase-cousins", rebase_merges))
1436 die(_("Unknown mode: %s"), rebase_merges);
1437 options.rebase_merges = 1;
1438 imply_merge(&options, "--rebase-merges");
1441 if (options.type == REBASE_APPLY) {
1442 if (ignore_whitespace)
1443 strvec_push(&options.git_am_opts,
1444 "--ignore-whitespace");
1445 if (options.committer_date_is_author_date)
1446 strvec_push(&options.git_am_opts,
1447 "--committer-date-is-author-date");
1448 if (options.ignore_date)
1449 strvec_push(&options.git_am_opts, "--ignore-date");
1450 } else {
1451 /* REBASE_MERGE */
1452 if (ignore_whitespace) {
1453 string_list_append(&strategy_options,
1454 "ignore-space-change");
1458 if (strategy_options.nr) {
1459 int i;
1461 if (!options.strategy)
1462 options.strategy = "ort";
1464 strbuf_reset(&buf);
1465 for (i = 0; i < strategy_options.nr; i++)
1466 strbuf_addf(&buf, " --%s",
1467 strategy_options.items[i].string);
1468 options.strategy_opts = xstrdup(buf.buf);
1471 if (options.strategy) {
1472 options.strategy = xstrdup(options.strategy);
1473 switch (options.type) {
1474 case REBASE_APPLY:
1475 die(_("--strategy requires --merge or --interactive"));
1476 case REBASE_MERGE:
1477 /* compatible */
1478 break;
1479 case REBASE_UNSPECIFIED:
1480 options.type = REBASE_MERGE;
1481 break;
1482 default:
1483 BUG("unhandled rebase type (%d)", options.type);
1487 if (options.type == REBASE_MERGE)
1488 imply_merge(&options, "--merge");
1490 if (options.root && !options.onto_name)
1491 imply_merge(&options, "--root without --onto");
1493 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1494 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1496 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1497 /* all am options except -q are compatible only with --apply */
1498 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1499 if (strcmp(options.git_am_opts.v[i], "-q"))
1500 break;
1502 if (i >= 0) {
1503 if (is_merge(&options))
1504 die(_("apply options and merge options "
1505 "cannot be used together"));
1506 else
1507 options.type = REBASE_APPLY;
1511 if (options.type == REBASE_UNSPECIFIED) {
1512 if (!strcmp(options.default_backend, "merge"))
1513 imply_merge(&options, "--merge");
1514 else if (!strcmp(options.default_backend, "apply"))
1515 options.type = REBASE_APPLY;
1516 else
1517 die(_("Unknown rebase backend: %s"),
1518 options.default_backend);
1521 if (options.type == REBASE_MERGE &&
1522 !options.strategy &&
1523 getenv("GIT_TEST_MERGE_ALGORITHM"))
1524 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1526 switch (options.type) {
1527 case REBASE_MERGE:
1528 options.state_dir = merge_dir();
1529 break;
1530 case REBASE_APPLY:
1531 options.state_dir = apply_dir();
1532 break;
1533 default:
1534 BUG("options.type was just set above; should be unreachable.");
1537 if (options.empty == EMPTY_UNSPECIFIED) {
1538 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1539 options.empty = EMPTY_ASK;
1540 else if (exec.nr > 0)
1541 options.empty = EMPTY_KEEP;
1542 else
1543 options.empty = EMPTY_DROP;
1545 if (reschedule_failed_exec > 0 && !is_merge(&options))
1546 die(_("--reschedule-failed-exec requires "
1547 "--exec or --interactive"));
1548 if (reschedule_failed_exec >= 0)
1549 options.reschedule_failed_exec = reschedule_failed_exec;
1551 if (options.signoff) {
1552 strvec_push(&options.git_am_opts, "--signoff");
1553 options.flags |= REBASE_FORCE;
1556 if (!options.root) {
1557 if (argc < 1) {
1558 struct branch *branch;
1560 branch = branch_get(NULL);
1561 options.upstream_name = branch_get_upstream(branch,
1562 NULL);
1563 if (!options.upstream_name)
1564 error_on_missing_default_upstream();
1565 if (options.fork_point < 0)
1566 options.fork_point = 1;
1567 } else {
1568 options.upstream_name = argv[0];
1569 argc--;
1570 argv++;
1571 if (!strcmp(options.upstream_name, "-"))
1572 options.upstream_name = "@{-1}";
1574 options.upstream =
1575 lookup_commit_reference_by_name(options.upstream_name);
1576 if (!options.upstream)
1577 die(_("invalid upstream '%s'"), options.upstream_name);
1578 options.upstream_arg = options.upstream_name;
1579 } else {
1580 if (!options.onto_name) {
1581 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1582 &squash_onto, NULL, NULL) < 0)
1583 die(_("Could not create new root commit"));
1584 options.squash_onto = &squash_onto;
1585 options.onto_name = squash_onto_name =
1586 xstrdup(oid_to_hex(&squash_onto));
1587 } else
1588 options.root_with_onto = 1;
1590 options.upstream_name = NULL;
1591 options.upstream = NULL;
1592 if (argc > 1)
1593 usage_with_options(builtin_rebase_usage,
1594 builtin_rebase_options);
1595 options.upstream_arg = "--root";
1599 * If the branch to rebase is given, that is the branch we will rebase
1600 * branch_name -- branch/commit being rebased, or
1601 * HEAD (already detached)
1602 * orig_head -- commit object name of tip of the branch before rebasing
1603 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1605 if (argc == 1) {
1606 /* Is it "rebase other branchname" or "rebase other commit"? */
1607 branch_name = argv[0];
1608 options.switch_to = argv[0];
1610 /* Is it a local branch? */
1611 strbuf_reset(&buf);
1612 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1613 if (!read_ref(buf.buf, &options.orig_head)) {
1614 die_if_checked_out(buf.buf, 1);
1615 options.head_name = xstrdup(buf.buf);
1616 /* If not is it a valid ref (branch or commit)? */
1617 } else {
1618 struct commit *commit =
1619 lookup_commit_reference_by_name(branch_name);
1620 if (!commit)
1621 die(_("no such branch/commit '%s'"),
1622 branch_name);
1623 oidcpy(&options.orig_head, &commit->object.oid);
1624 options.head_name = NULL;
1626 } else if (argc == 0) {
1627 /* Do not need to switch branches, we are already on it. */
1628 options.head_name =
1629 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1630 &flags));
1631 if (!options.head_name)
1632 die(_("No such ref: %s"), "HEAD");
1633 if (flags & REF_ISSYMREF) {
1634 if (!skip_prefix(options.head_name,
1635 "refs/heads/", &branch_name))
1636 branch_name = options.head_name;
1638 } else {
1639 FREE_AND_NULL(options.head_name);
1640 branch_name = "HEAD";
1642 if (get_oid("HEAD", &options.orig_head))
1643 die(_("Could not resolve HEAD to a revision"));
1644 } else
1645 BUG("unexpected number of arguments left to parse");
1647 /* Make sure the branch to rebase onto is valid. */
1648 if (keep_base) {
1649 strbuf_reset(&buf);
1650 strbuf_addstr(&buf, options.upstream_name);
1651 strbuf_addstr(&buf, "...");
1652 strbuf_addstr(&buf, branch_name);
1653 options.onto_name = xstrdup(buf.buf);
1654 } else if (!options.onto_name)
1655 options.onto_name = options.upstream_name;
1656 if (strstr(options.onto_name, "...")) {
1657 if (get_oid_mb(options.onto_name, &merge_base) < 0) {
1658 if (keep_base)
1659 die(_("'%s': need exactly one merge base with branch"),
1660 options.upstream_name);
1661 else
1662 die(_("'%s': need exactly one merge base"),
1663 options.onto_name);
1665 options.onto = lookup_commit_or_die(&merge_base,
1666 options.onto_name);
1667 } else {
1668 options.onto =
1669 lookup_commit_reference_by_name(options.onto_name);
1670 if (!options.onto)
1671 die(_("Does not point to a valid commit '%s'"),
1672 options.onto_name);
1675 if (options.fork_point > 0) {
1676 struct commit *head =
1677 lookup_commit_reference(the_repository,
1678 &options.orig_head);
1679 options.restrict_revision =
1680 get_fork_point(options.upstream_name, head);
1683 if (repo_read_index(the_repository) < 0)
1684 die(_("could not read index"));
1686 if (options.autostash)
1687 create_autostash(the_repository,
1688 state_dir_path("autostash", &options));
1691 if (require_clean_work_tree(the_repository, "rebase",
1692 _("Please commit or stash them."), 1, 1)) {
1693 ret = -1;
1694 goto cleanup;
1698 * Now we are rebasing commits upstream..orig_head (or with --root,
1699 * everything leading up to orig_head) on top of onto.
1703 * Check if we are already based on onto with linear history,
1704 * in which case we could fast-forward without replacing the commits
1705 * with new commits recreated by replaying their changes.
1707 * Note that can_fast_forward() initializes merge_base, so we have to
1708 * call it before checking allow_preemptive_ff.
1710 if (can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1711 &options.orig_head, &merge_base) &&
1712 allow_preemptive_ff) {
1713 int flag;
1715 if (!(options.flags & REBASE_FORCE)) {
1716 /* Lazily switch to the target branch if needed... */
1717 if (options.switch_to) {
1718 ret = checkout_up_to_date(&options);
1719 if (ret)
1720 goto cleanup;
1723 if (!(options.flags & REBASE_NO_QUIET))
1724 ; /* be quiet */
1725 else if (!strcmp(branch_name, "HEAD") &&
1726 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1727 puts(_("HEAD is up to date."));
1728 else
1729 printf(_("Current branch %s is up to date.\n"),
1730 branch_name);
1731 ret = finish_rebase(&options);
1732 goto cleanup;
1733 } else 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, rebase forced."));
1738 else
1739 printf(_("Current branch %s is up to date, rebase "
1740 "forced.\n"), branch_name);
1743 /* If a hook exists, give it a chance to interrupt*/
1744 if (!ok_to_skip_pre_rebase &&
1745 run_hooks_l("pre-rebase", options.upstream_arg,
1746 argc ? argv[0] : NULL, NULL))
1747 die(_("The pre-rebase hook refused to rebase."));
1749 if (options.flags & REBASE_DIFFSTAT) {
1750 struct diff_options opts;
1752 if (options.flags & REBASE_VERBOSE) {
1753 if (is_null_oid(&merge_base))
1754 printf(_("Changes to %s:\n"),
1755 oid_to_hex(&options.onto->object.oid));
1756 else
1757 printf(_("Changes from %s to %s:\n"),
1758 oid_to_hex(&merge_base),
1759 oid_to_hex(&options.onto->object.oid));
1762 /* We want color (if set), but no pager */
1763 diff_setup(&opts);
1764 opts.stat_width = -1; /* use full terminal width */
1765 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1766 opts.output_format |=
1767 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1768 opts.detect_rename = DIFF_DETECT_RENAME;
1769 diff_setup_done(&opts);
1770 diff_tree_oid(is_null_oid(&merge_base) ?
1771 the_hash_algo->empty_tree : &merge_base,
1772 &options.onto->object.oid, "", &opts);
1773 diffcore_std(&opts);
1774 diff_flush(&opts);
1777 if (is_merge(&options))
1778 goto run_rebase;
1780 /* Detach HEAD and reset the tree */
1781 if (options.flags & REBASE_NO_QUIET)
1782 printf(_("First, rewinding head to replay your work on top of "
1783 "it...\n"));
1785 strbuf_addf(&msg, "%s: checkout %s",
1786 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1787 ropts.oid = &options.onto->object.oid;
1788 ropts.orig_head = &options.orig_head,
1789 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1790 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1791 ropts.head_msg = msg.buf;
1792 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1793 if (reset_head(the_repository, &ropts))
1794 die(_("Could not detach HEAD"));
1795 strbuf_release(&msg);
1798 * If the onto is a proper descendant of the tip of the branch, then
1799 * we just fast-forwarded.
1801 strbuf_reset(&msg);
1802 if (oideq(&merge_base, &options.orig_head)) {
1803 printf(_("Fast-forwarded %s to %s.\n"),
1804 branch_name, options.onto_name);
1805 strbuf_addf(&msg, "rebase finished: %s onto %s",
1806 options.head_name ? options.head_name : "detached HEAD",
1807 oid_to_hex(&options.onto->object.oid));
1808 memset(&ropts, 0, sizeof(ropts));
1809 ropts.branch = options.head_name;
1810 ropts.flags = RESET_HEAD_REFS_ONLY;
1811 ropts.head_msg = msg.buf;
1812 reset_head(the_repository, &ropts);
1813 strbuf_release(&msg);
1814 ret = finish_rebase(&options);
1815 goto cleanup;
1818 strbuf_addf(&revisions, "%s..%s",
1819 options.root ? oid_to_hex(&options.onto->object.oid) :
1820 (options.restrict_revision ?
1821 oid_to_hex(&options.restrict_revision->object.oid) :
1822 oid_to_hex(&options.upstream->object.oid)),
1823 oid_to_hex(&options.orig_head));
1825 options.revisions = revisions.buf;
1827 run_rebase:
1828 ret = run_specific_rebase(&options, action);
1830 cleanup:
1831 strbuf_release(&buf);
1832 strbuf_release(&revisions);
1833 free(options.head_name);
1834 free(options.gpg_sign_opt);
1835 free(options.cmd);
1836 free(options.strategy);
1837 strbuf_release(&options.git_format_patch_opt);
1838 free(squash_onto_name);
1839 return !!ret;