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