reset_head(): take struct rebase_head_opts
[git/gitster.git] / builtin / rebase.c
blobecc368dd4f458ad486a367ae1dd832a4b6bd8b74
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"
32 #define DEFAULT_REFLOG_ACTION "rebase"
34 static char const * const builtin_rebase_usage[] = {
35 N_("git rebase [-i] [options] [--exec <cmd>] "
36 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
37 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
38 "--root [<branch>]"),
39 N_("git rebase --continue | --abort | --skip | --edit-todo"),
40 NULL
43 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
44 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
45 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
46 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
48 enum rebase_type {
49 REBASE_UNSPECIFIED = -1,
50 REBASE_APPLY,
51 REBASE_MERGE
54 enum empty_type {
55 EMPTY_UNSPECIFIED = -1,
56 EMPTY_DROP,
57 EMPTY_KEEP,
58 EMPTY_ASK
61 struct rebase_options {
62 enum rebase_type type;
63 enum empty_type empty;
64 const char *default_backend;
65 const char *state_dir;
66 struct commit *upstream;
67 const char *upstream_name;
68 const char *upstream_arg;
69 char *head_name;
70 struct object_id orig_head;
71 struct commit *onto;
72 const char *onto_name;
73 const char *revisions;
74 const char *switch_to;
75 int root, root_with_onto;
76 struct object_id *squash_onto;
77 struct commit *restrict_revision;
78 int dont_finish_rebase;
79 enum {
80 REBASE_NO_QUIET = 1<<0,
81 REBASE_VERBOSE = 1<<1,
82 REBASE_DIFFSTAT = 1<<2,
83 REBASE_FORCE = 1<<3,
84 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
85 } flags;
86 struct strvec git_am_opts;
87 const char *action;
88 int signoff;
89 int allow_rerere_autoupdate;
90 int keep_empty;
91 int autosquash;
92 char *gpg_sign_opt;
93 int autostash;
94 int committer_date_is_author_date;
95 int ignore_date;
96 char *cmd;
97 int allow_empty_message;
98 int rebase_merges, rebase_cousins;
99 char *strategy, *strategy_opts;
100 struct strbuf git_format_patch_opt;
101 int reschedule_failed_exec;
102 int reapply_cherry_picks;
103 int fork_point;
106 #define REBASE_OPTIONS_INIT { \
107 .type = REBASE_UNSPECIFIED, \
108 .empty = EMPTY_UNSPECIFIED, \
109 .keep_empty = 1, \
110 .default_backend = "merge", \
111 .flags = REBASE_NO_QUIET, \
112 .git_am_opts = STRVEC_INIT, \
113 .git_format_patch_opt = STRBUF_INIT, \
114 .fork_point = -1, \
117 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
119 struct replay_opts replay = REPLAY_OPTS_INIT;
121 replay.action = REPLAY_INTERACTIVE_REBASE;
122 replay.strategy = NULL;
123 sequencer_init_config(&replay);
125 replay.signoff = opts->signoff;
126 replay.allow_ff = !(opts->flags & REBASE_FORCE);
127 if (opts->allow_rerere_autoupdate)
128 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
129 replay.allow_empty = 1;
130 replay.allow_empty_message = opts->allow_empty_message;
131 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
132 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
133 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
134 replay.verbose = opts->flags & REBASE_VERBOSE;
135 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
136 replay.committer_date_is_author_date =
137 opts->committer_date_is_author_date;
138 replay.ignore_date = opts->ignore_date;
139 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
140 if (opts->strategy)
141 replay.strategy = xstrdup_or_null(opts->strategy);
142 else if (!replay.strategy && replay.default_strategy) {
143 replay.strategy = replay.default_strategy;
144 replay.default_strategy = NULL;
147 if (opts->strategy_opts)
148 parse_strategy_opts(&replay, opts->strategy_opts);
150 if (opts->squash_onto) {
151 oidcpy(&replay.squash_onto, opts->squash_onto);
152 replay.have_squash_onto = 1;
155 return replay;
158 enum action {
159 ACTION_NONE = 0,
160 ACTION_CONTINUE,
161 ACTION_SKIP,
162 ACTION_ABORT,
163 ACTION_QUIT,
164 ACTION_EDIT_TODO,
165 ACTION_SHOW_CURRENT_PATCH
168 static const char *action_names[] = { "undefined",
169 "continue",
170 "skip",
171 "abort",
172 "quit",
173 "edit_todo",
174 "show_current_patch" };
176 static int edit_todo_file(unsigned flags)
178 const char *todo_file = rebase_path_todo();
179 struct todo_list todo_list = TODO_LIST_INIT,
180 new_todo = TODO_LIST_INIT;
181 int res = 0;
183 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
184 return error_errno(_("could not read '%s'."), todo_file);
186 strbuf_stripspace(&todo_list.buf, 1);
187 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
188 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
189 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
190 res = error_errno(_("could not write '%s'"), todo_file);
192 todo_list_release(&todo_list);
193 todo_list_release(&new_todo);
195 return res;
198 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
199 struct object_id *orig_head, char **revisions,
200 char **shortrevisions)
202 struct commit *base_rev = upstream ? upstream : onto;
203 const char *shorthead;
205 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
206 oid_to_hex(orig_head));
208 shorthead = find_unique_abbrev(orig_head, DEFAULT_ABBREV);
210 if (upstream) {
211 const char *shortrev;
213 shortrev = find_unique_abbrev(&base_rev->object.oid,
214 DEFAULT_ABBREV);
216 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
217 } else
218 *shortrevisions = xstrdup(shorthead);
220 return 0;
223 static int init_basic_state(struct replay_opts *opts, const char *head_name,
224 struct commit *onto,
225 const struct object_id *orig_head)
227 FILE *interactive;
229 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
230 return error_errno(_("could not create temporary %s"), merge_dir());
232 delete_reflog("REBASE_HEAD");
234 interactive = fopen(path_interactive(), "w");
235 if (!interactive)
236 return error_errno(_("could not mark as interactive"));
237 fclose(interactive);
239 return write_basic_state(opts, head_name, onto, orig_head);
242 static void split_exec_commands(const char *cmd, struct string_list *commands)
244 if (cmd && *cmd) {
245 string_list_split(commands, cmd, '\n', -1);
247 /* rebase.c adds a new line to cmd after every command,
248 * so here the last command is always empty */
249 string_list_remove_empty_items(commands, 0);
253 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
255 int ret;
256 char *revisions = NULL, *shortrevisions = NULL;
257 struct strvec make_script_args = STRVEC_INIT;
258 struct todo_list todo_list = TODO_LIST_INIT;
259 struct replay_opts replay = get_replay_opts(opts);
260 struct string_list commands = STRING_LIST_INIT_DUP;
262 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head,
263 &revisions, &shortrevisions))
264 return -1;
266 if (init_basic_state(&replay,
267 opts->head_name ? opts->head_name : "detached HEAD",
268 opts->onto, &opts->orig_head)) {
269 free(revisions);
270 free(shortrevisions);
272 return -1;
275 if (!opts->upstream && opts->squash_onto)
276 write_file(path_squash_onto(), "%s\n",
277 oid_to_hex(opts->squash_onto));
279 strvec_pushl(&make_script_args, "", revisions, NULL);
280 if (opts->restrict_revision)
281 strvec_pushf(&make_script_args, "^%s",
282 oid_to_hex(&opts->restrict_revision->object.oid));
284 ret = sequencer_make_script(the_repository, &todo_list.buf,
285 make_script_args.nr, make_script_args.v,
286 flags);
288 if (ret)
289 error(_("could not generate todo list"));
290 else {
291 discard_cache();
292 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
293 &todo_list))
294 BUG("unusable todo list");
296 split_exec_commands(opts->cmd, &commands);
297 ret = complete_action(the_repository, &replay, flags,
298 shortrevisions, opts->onto_name, opts->onto,
299 &opts->orig_head, &commands, opts->autosquash,
300 &todo_list);
303 string_list_clear(&commands, 0);
304 free(revisions);
305 free(shortrevisions);
306 todo_list_release(&todo_list);
307 strvec_clear(&make_script_args);
309 return ret;
312 static int run_sequencer_rebase(struct rebase_options *opts,
313 enum action command)
315 unsigned flags = 0;
316 int abbreviate_commands = 0, ret = 0;
318 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
320 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
321 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
322 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
323 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
324 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
325 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
326 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
328 switch (command) {
329 case ACTION_NONE: {
330 if (!opts->onto && !opts->upstream)
331 die(_("a base commit must be provided with --upstream or --onto"));
333 ret = do_interactive_rebase(opts, flags);
334 break;
336 case ACTION_SKIP: {
337 struct string_list merge_rr = STRING_LIST_INIT_DUP;
339 rerere_clear(the_repository, &merge_rr);
341 /* fallthrough */
342 case ACTION_CONTINUE: {
343 struct replay_opts replay_opts = get_replay_opts(opts);
345 ret = sequencer_continue(the_repository, &replay_opts);
346 break;
348 case ACTION_EDIT_TODO:
349 ret = edit_todo_file(flags);
350 break;
351 case ACTION_SHOW_CURRENT_PATCH: {
352 struct child_process cmd = CHILD_PROCESS_INIT;
354 cmd.git_cmd = 1;
355 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
356 ret = run_command(&cmd);
358 break;
360 default:
361 BUG("invalid command '%d'", command);
364 return ret;
367 static void imply_merge(struct rebase_options *opts, const char *option);
368 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
369 int unset)
371 struct rebase_options *opts = opt->value;
373 BUG_ON_OPT_ARG(arg);
375 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
376 opts->keep_empty = !unset;
377 opts->type = REBASE_MERGE;
378 return 0;
381 static int is_merge(struct rebase_options *opts)
383 return opts->type == REBASE_MERGE;
386 static void imply_merge(struct rebase_options *opts, const char *option)
388 switch (opts->type) {
389 case REBASE_APPLY:
390 die(_("%s requires the merge backend"), option);
391 break;
392 case REBASE_MERGE:
393 break;
394 default:
395 opts->type = REBASE_MERGE; /* implied */
396 break;
400 /* Returns the filename prefixed by the state_dir */
401 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
403 static struct strbuf path = STRBUF_INIT;
404 static size_t prefix_len;
406 if (!prefix_len) {
407 strbuf_addf(&path, "%s/", opts->state_dir);
408 prefix_len = path.len;
411 strbuf_setlen(&path, prefix_len);
412 strbuf_addstr(&path, filename);
413 return path.buf;
416 /* Initialize the rebase options from the state directory. */
417 static int read_basic_state(struct rebase_options *opts)
419 struct strbuf head_name = STRBUF_INIT;
420 struct strbuf buf = STRBUF_INIT;
421 struct object_id oid;
423 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
424 READ_ONELINER_WARN_MISSING) ||
425 !read_oneliner(&buf, state_dir_path("onto", opts),
426 READ_ONELINER_WARN_MISSING))
427 return -1;
428 opts->head_name = starts_with(head_name.buf, "refs/") ?
429 xstrdup(head_name.buf) : NULL;
430 strbuf_release(&head_name);
431 if (get_oid(buf.buf, &oid))
432 return error(_("could not get 'onto': '%s'"), buf.buf);
433 opts->onto = lookup_commit_or_die(&oid, buf.buf);
436 * We always write to orig-head, but interactive rebase used to write to
437 * head. Fall back to reading from head to cover for the case that the
438 * user upgraded git with an ongoing interactive rebase.
440 strbuf_reset(&buf);
441 if (file_exists(state_dir_path("orig-head", opts))) {
442 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
443 READ_ONELINER_WARN_MISSING))
444 return -1;
445 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
446 READ_ONELINER_WARN_MISSING))
447 return -1;
448 if (get_oid(buf.buf, &opts->orig_head))
449 return error(_("invalid orig-head: '%s'"), buf.buf);
451 if (file_exists(state_dir_path("quiet", opts)))
452 opts->flags &= ~REBASE_NO_QUIET;
453 else
454 opts->flags |= REBASE_NO_QUIET;
456 if (file_exists(state_dir_path("verbose", opts)))
457 opts->flags |= REBASE_VERBOSE;
459 if (file_exists(state_dir_path("signoff", opts))) {
460 opts->signoff = 1;
461 opts->flags |= REBASE_FORCE;
464 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
465 strbuf_reset(&buf);
466 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
467 READ_ONELINER_WARN_MISSING))
468 return -1;
469 if (!strcmp(buf.buf, "--rerere-autoupdate"))
470 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
471 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
472 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
473 else
474 warning(_("ignoring invalid allow_rerere_autoupdate: "
475 "'%s'"), buf.buf);
478 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
479 strbuf_reset(&buf);
480 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
481 READ_ONELINER_WARN_MISSING))
482 return -1;
483 free(opts->gpg_sign_opt);
484 opts->gpg_sign_opt = xstrdup(buf.buf);
487 if (file_exists(state_dir_path("strategy", opts))) {
488 strbuf_reset(&buf);
489 if (!read_oneliner(&buf, state_dir_path("strategy", opts),
490 READ_ONELINER_WARN_MISSING))
491 return -1;
492 free(opts->strategy);
493 opts->strategy = xstrdup(buf.buf);
496 if (file_exists(state_dir_path("strategy_opts", opts))) {
497 strbuf_reset(&buf);
498 if (!read_oneliner(&buf, state_dir_path("strategy_opts", opts),
499 READ_ONELINER_WARN_MISSING))
500 return -1;
501 free(opts->strategy_opts);
502 opts->strategy_opts = xstrdup(buf.buf);
505 strbuf_release(&buf);
507 return 0;
510 static int rebase_write_basic_state(struct rebase_options *opts)
512 write_file(state_dir_path("head-name", opts), "%s",
513 opts->head_name ? opts->head_name : "detached HEAD");
514 write_file(state_dir_path("onto", opts), "%s",
515 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
516 write_file(state_dir_path("orig-head", opts), "%s",
517 oid_to_hex(&opts->orig_head));
518 if (!(opts->flags & REBASE_NO_QUIET))
519 write_file(state_dir_path("quiet", opts), "%s", "");
520 if (opts->flags & REBASE_VERBOSE)
521 write_file(state_dir_path("verbose", opts), "%s", "");
522 if (opts->strategy)
523 write_file(state_dir_path("strategy", opts), "%s",
524 opts->strategy);
525 if (opts->strategy_opts)
526 write_file(state_dir_path("strategy_opts", opts), "%s",
527 opts->strategy_opts);
528 if (opts->allow_rerere_autoupdate > 0)
529 write_file(state_dir_path("allow_rerere_autoupdate", opts),
530 "-%s-rerere-autoupdate",
531 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
532 "" : "-no");
533 if (opts->gpg_sign_opt)
534 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
535 opts->gpg_sign_opt);
536 if (opts->signoff)
537 write_file(state_dir_path("signoff", opts), "--signoff");
539 return 0;
542 static int finish_rebase(struct rebase_options *opts)
544 struct strbuf dir = STRBUF_INIT;
545 int ret = 0;
547 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
548 unlink(git_path_auto_merge(the_repository));
549 apply_autostash(state_dir_path("autostash", opts));
551 * We ignore errors in 'git maintenance run --auto', since the
552 * user should see them.
554 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
555 if (opts->type == REBASE_MERGE) {
556 struct replay_opts replay = REPLAY_OPTS_INIT;
558 replay.action = REPLAY_INTERACTIVE_REBASE;
559 ret = sequencer_remove_state(&replay);
560 } else {
561 strbuf_addstr(&dir, opts->state_dir);
562 if (remove_dir_recursively(&dir, 0))
563 ret = error(_("could not remove '%s'"),
564 opts->state_dir);
565 strbuf_release(&dir);
568 return ret;
571 static int move_to_original_branch(struct rebase_options *opts)
573 struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
574 struct reset_head_opts ropts = { 0 };
575 int ret;
577 if (!opts->head_name)
578 return 0; /* nothing to move back to */
580 if (!opts->onto)
581 BUG("move_to_original_branch without onto");
583 strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
584 opts->head_name, oid_to_hex(&opts->onto->object.oid));
585 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
586 opts->head_name);
587 ropts.branch = opts->head_name;
588 ropts.flags = RESET_HEAD_REFS_ONLY;
589 ropts.orig_head_msg = orig_head_reflog.buf;
590 ropts.head_msg = head_reflog.buf;
591 ret = reset_head(the_repository, &ropts);
593 strbuf_release(&orig_head_reflog);
594 strbuf_release(&head_reflog);
595 return ret;
598 static const char *resolvemsg =
599 N_("Resolve all conflicts manually, mark them as resolved with\n"
600 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
601 "You can instead skip this commit: run \"git rebase --skip\".\n"
602 "To abort and get back to the state before \"git rebase\", run "
603 "\"git rebase --abort\".");
605 static int run_am(struct rebase_options *opts)
607 struct child_process am = CHILD_PROCESS_INIT;
608 struct child_process format_patch = CHILD_PROCESS_INIT;
609 struct strbuf revisions = STRBUF_INIT;
610 int status;
611 char *rebased_patches;
613 am.git_cmd = 1;
614 strvec_push(&am.args, "am");
616 if (opts->action && !strcmp("continue", opts->action)) {
617 strvec_push(&am.args, "--resolved");
618 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
619 if (opts->gpg_sign_opt)
620 strvec_push(&am.args, opts->gpg_sign_opt);
621 status = run_command(&am);
622 if (status)
623 return status;
625 return move_to_original_branch(opts);
627 if (opts->action && !strcmp("skip", opts->action)) {
628 strvec_push(&am.args, "--skip");
629 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
630 status = run_command(&am);
631 if (status)
632 return status;
634 return move_to_original_branch(opts);
636 if (opts->action && !strcmp("show-current-patch", opts->action)) {
637 strvec_push(&am.args, "--show-current-patch");
638 return run_command(&am);
641 strbuf_addf(&revisions, "%s...%s",
642 oid_to_hex(opts->root ?
643 /* this is now equivalent to !opts->upstream */
644 &opts->onto->object.oid :
645 &opts->upstream->object.oid),
646 oid_to_hex(&opts->orig_head));
648 rebased_patches = xstrdup(git_path("rebased-patches"));
649 format_patch.out = open(rebased_patches,
650 O_WRONLY | O_CREAT | O_TRUNC, 0666);
651 if (format_patch.out < 0) {
652 status = error_errno(_("could not open '%s' for writing"),
653 rebased_patches);
654 free(rebased_patches);
655 strvec_clear(&am.args);
656 return status;
659 format_patch.git_cmd = 1;
660 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
661 "--full-index", "--cherry-pick", "--right-only",
662 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
663 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
664 "--no-base", NULL);
665 if (opts->git_format_patch_opt.len)
666 strvec_split(&format_patch.args,
667 opts->git_format_patch_opt.buf);
668 strvec_push(&format_patch.args, revisions.buf);
669 if (opts->restrict_revision)
670 strvec_pushf(&format_patch.args, "^%s",
671 oid_to_hex(&opts->restrict_revision->object.oid));
673 status = run_command(&format_patch);
674 if (status) {
675 struct reset_head_opts ropts = { 0 };
676 unlink(rebased_patches);
677 free(rebased_patches);
678 strvec_clear(&am.args);
680 ropts.oid = &opts->orig_head;
681 ropts.branch = opts->head_name;
682 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
683 reset_head(the_repository, &ropts);
684 error(_("\ngit encountered an error while preparing the "
685 "patches to replay\n"
686 "these revisions:\n"
687 "\n %s\n\n"
688 "As a result, git cannot rebase them."),
689 opts->revisions);
691 strbuf_release(&revisions);
692 return status;
694 strbuf_release(&revisions);
696 am.in = open(rebased_patches, O_RDONLY);
697 if (am.in < 0) {
698 status = error_errno(_("could not open '%s' for reading"),
699 rebased_patches);
700 free(rebased_patches);
701 strvec_clear(&am.args);
702 return status;
705 strvec_pushv(&am.args, opts->git_am_opts.v);
706 strvec_push(&am.args, "--rebasing");
707 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
708 strvec_push(&am.args, "--patch-format=mboxrd");
709 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
710 strvec_push(&am.args, "--rerere-autoupdate");
711 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
712 strvec_push(&am.args, "--no-rerere-autoupdate");
713 if (opts->gpg_sign_opt)
714 strvec_push(&am.args, opts->gpg_sign_opt);
715 status = run_command(&am);
716 unlink(rebased_patches);
717 free(rebased_patches);
719 if (!status) {
720 return move_to_original_branch(opts);
723 if (is_directory(opts->state_dir))
724 rebase_write_basic_state(opts);
726 return status;
729 static int run_specific_rebase(struct rebase_options *opts, enum action action)
731 int status;
733 if (opts->type == REBASE_MERGE) {
734 /* Run sequencer-based rebase */
735 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
736 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
737 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
738 opts->autosquash = 0;
740 if (opts->gpg_sign_opt) {
741 /* remove the leading "-S" */
742 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
743 free(opts->gpg_sign_opt);
744 opts->gpg_sign_opt = tmp;
747 status = run_sequencer_rebase(opts, action);
748 } else if (opts->type == REBASE_APPLY)
749 status = run_am(opts);
750 else
751 BUG("Unhandled rebase type %d", opts->type);
753 if (opts->dont_finish_rebase)
754 ; /* do nothing */
755 else if (opts->type == REBASE_MERGE)
756 ; /* merge backend cleans up after itself */
757 else if (status == 0) {
758 if (!file_exists(state_dir_path("stopped-sha", opts)))
759 finish_rebase(opts);
760 } else if (status == 2) {
761 struct strbuf dir = STRBUF_INIT;
763 apply_autostash(state_dir_path("autostash", opts));
764 strbuf_addstr(&dir, opts->state_dir);
765 remove_dir_recursively(&dir, 0);
766 strbuf_release(&dir);
767 die("Nothing to do");
770 return status ? -1 : 0;
773 static int rebase_config(const char *var, const char *value, void *data)
775 struct rebase_options *opts = data;
777 if (!strcmp(var, "rebase.stat")) {
778 if (git_config_bool(var, value))
779 opts->flags |= REBASE_DIFFSTAT;
780 else
781 opts->flags &= ~REBASE_DIFFSTAT;
782 return 0;
785 if (!strcmp(var, "rebase.autosquash")) {
786 opts->autosquash = git_config_bool(var, value);
787 return 0;
790 if (!strcmp(var, "commit.gpgsign")) {
791 free(opts->gpg_sign_opt);
792 opts->gpg_sign_opt = git_config_bool(var, value) ?
793 xstrdup("-S") : NULL;
794 return 0;
797 if (!strcmp(var, "rebase.autostash")) {
798 opts->autostash = git_config_bool(var, value);
799 return 0;
802 if (!strcmp(var, "rebase.reschedulefailedexec")) {
803 opts->reschedule_failed_exec = git_config_bool(var, value);
804 return 0;
807 if (!strcmp(var, "rebase.forkpoint")) {
808 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
809 return 0;
812 if (!strcmp(var, "rebase.backend")) {
813 return git_config_string(&opts->default_backend, var, value);
816 return git_default_config(var, value, data);
819 static int checkout_up_to_date(struct rebase_options *options)
821 struct strbuf buf = STRBUF_INIT;
822 struct reset_head_opts ropts = { 0 };
823 int ret = 0;
825 strbuf_addf(&buf, "%s: checkout %s",
826 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
827 options->switch_to);
828 ropts.oid = &options->orig_head;
829 ropts.branch = options->head_name;
830 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
831 ropts.head_msg = buf.buf;
832 if (reset_head(the_repository, &ropts) < 0)
833 ret = error(_("could not switch to %s"), options->switch_to);
834 strbuf_release(&buf);
836 return ret;
840 * Determines whether the commits in from..to are linear, i.e. contain
841 * no merge commits. This function *expects* `from` to be an ancestor of
842 * `to`.
844 static int is_linear_history(struct commit *from, struct commit *to)
846 while (to && to != from) {
847 parse_commit(to);
848 if (!to->parents)
849 return 1;
850 if (to->parents->next)
851 return 0;
852 to = to->parents->item;
854 return 1;
857 static int can_fast_forward(struct commit *onto, struct commit *upstream,
858 struct commit *restrict_revision,
859 struct object_id *head_oid, struct object_id *merge_base)
861 struct commit *head = lookup_commit(the_repository, head_oid);
862 struct commit_list *merge_bases = NULL;
863 int res = 0;
865 if (!head)
866 goto done;
868 merge_bases = get_merge_bases(onto, head);
869 if (!merge_bases || merge_bases->next) {
870 oidcpy(merge_base, null_oid());
871 goto done;
874 oidcpy(merge_base, &merge_bases->item->object.oid);
875 if (!oideq(merge_base, &onto->object.oid))
876 goto done;
878 if (restrict_revision && !oideq(&restrict_revision->object.oid, merge_base))
879 goto done;
881 if (!upstream)
882 goto done;
884 free_commit_list(merge_bases);
885 merge_bases = get_merge_bases(upstream, head);
886 if (!merge_bases || merge_bases->next)
887 goto done;
889 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
890 goto done;
892 res = 1;
894 done:
895 free_commit_list(merge_bases);
896 return res && is_linear_history(onto, head);
899 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
901 struct rebase_options *opts = opt->value;
903 BUG_ON_OPT_NEG(unset);
904 BUG_ON_OPT_ARG(arg);
906 opts->type = REBASE_APPLY;
908 return 0;
911 /* -i followed by -m is still -i */
912 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
914 struct rebase_options *opts = opt->value;
916 BUG_ON_OPT_NEG(unset);
917 BUG_ON_OPT_ARG(arg);
919 if (!is_merge(opts))
920 opts->type = REBASE_MERGE;
922 return 0;
925 /* -i followed by -r is still explicitly interactive, but -r alone is not */
926 static int parse_opt_interactive(const struct option *opt, const char *arg,
927 int unset)
929 struct rebase_options *opts = opt->value;
931 BUG_ON_OPT_NEG(unset);
932 BUG_ON_OPT_ARG(arg);
934 opts->type = REBASE_MERGE;
935 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
937 return 0;
940 static enum empty_type parse_empty_value(const char *value)
942 if (!strcasecmp(value, "drop"))
943 return EMPTY_DROP;
944 else if (!strcasecmp(value, "keep"))
945 return EMPTY_KEEP;
946 else if (!strcasecmp(value, "ask"))
947 return EMPTY_ASK;
949 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
952 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
954 struct rebase_options *options = opt->value;
955 enum empty_type value = parse_empty_value(arg);
957 BUG_ON_OPT_NEG(unset);
959 options->empty = value;
960 return 0;
963 static void NORETURN error_on_missing_default_upstream(void)
965 struct branch *current_branch = branch_get(NULL);
967 printf(_("%s\n"
968 "Please specify which branch you want to rebase against.\n"
969 "See git-rebase(1) for details.\n"
970 "\n"
971 " git rebase '<branch>'\n"
972 "\n"),
973 current_branch ? _("There is no tracking information for "
974 "the current branch.") :
975 _("You are not currently on a branch."));
977 if (current_branch) {
978 const char *remote = current_branch->remote_name;
980 if (!remote)
981 remote = _("<remote>");
983 printf(_("If you wish to set tracking information for this "
984 "branch you can do so with:\n"
985 "\n"
986 " git branch --set-upstream-to=%s/<branch> %s\n"
987 "\n"),
988 remote, current_branch->name);
990 exit(1);
993 static void set_reflog_action(struct rebase_options *options)
995 const char *env;
996 struct strbuf buf = STRBUF_INIT;
998 if (!is_merge(options))
999 return;
1001 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1002 if (env && strcmp("rebase", env))
1003 return; /* only override it if it is "rebase" */
1005 strbuf_addf(&buf, "rebase (%s)", options->action);
1006 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1007 strbuf_release(&buf);
1010 static int check_exec_cmd(const char *cmd)
1012 if (strchr(cmd, '\n'))
1013 return error(_("exec commands cannot contain newlines"));
1015 /* Does the command consist purely of whitespace? */
1016 if (!cmd[strspn(cmd, " \t\r\f\v")])
1017 return error(_("empty exec command"));
1019 return 0;
1022 int cmd_rebase(int argc, const char **argv, const char *prefix)
1024 struct rebase_options options = REBASE_OPTIONS_INIT;
1025 const char *branch_name;
1026 int ret, flags, total_argc, in_progress = 0;
1027 int keep_base = 0;
1028 int ok_to_skip_pre_rebase = 0;
1029 struct strbuf msg = STRBUF_INIT;
1030 struct strbuf revisions = STRBUF_INIT;
1031 struct strbuf buf = STRBUF_INIT;
1032 struct object_id merge_base;
1033 int ignore_whitespace = 0;
1034 enum action action = ACTION_NONE;
1035 const char *gpg_sign = NULL;
1036 struct string_list exec = STRING_LIST_INIT_NODUP;
1037 const char *rebase_merges = NULL;
1038 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1039 struct object_id squash_onto;
1040 char *squash_onto_name = NULL;
1041 int reschedule_failed_exec = -1;
1042 int allow_preemptive_ff = 1;
1043 int preserve_merges_selected = 0;
1044 struct reset_head_opts ropts = { 0 };
1045 struct option builtin_rebase_options[] = {
1046 OPT_STRING(0, "onto", &options.onto_name,
1047 N_("revision"),
1048 N_("rebase onto given branch instead of upstream")),
1049 OPT_BOOL(0, "keep-base", &keep_base,
1050 N_("use the merge-base of upstream and branch as the current base")),
1051 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1052 N_("allow pre-rebase hook to run")),
1053 OPT_NEGBIT('q', "quiet", &options.flags,
1054 N_("be quiet. implies --no-stat"),
1055 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1056 OPT_BIT('v', "verbose", &options.flags,
1057 N_("display a diffstat of what changed upstream"),
1058 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1059 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1060 N_("do not show diffstat of what changed upstream"),
1061 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1062 OPT_BOOL(0, "signoff", &options.signoff,
1063 N_("add a Signed-off-by trailer to each commit")),
1064 OPT_BOOL(0, "committer-date-is-author-date",
1065 &options.committer_date_is_author_date,
1066 N_("make committer date match author date")),
1067 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1068 N_("ignore author date and use current date")),
1069 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1070 N_("synonym of --reset-author-date")),
1071 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1072 N_("passed to 'git apply'"), 0),
1073 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1074 N_("ignore changes in whitespace")),
1075 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1076 N_("action"), N_("passed to 'git apply'"), 0),
1077 OPT_BIT('f', "force-rebase", &options.flags,
1078 N_("cherry-pick all commits, even if unchanged"),
1079 REBASE_FORCE),
1080 OPT_BIT(0, "no-ff", &options.flags,
1081 N_("cherry-pick all commits, even if unchanged"),
1082 REBASE_FORCE),
1083 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1084 ACTION_CONTINUE),
1085 OPT_CMDMODE(0, "skip", &action,
1086 N_("skip current patch and continue"), ACTION_SKIP),
1087 OPT_CMDMODE(0, "abort", &action,
1088 N_("abort and check out the original branch"),
1089 ACTION_ABORT),
1090 OPT_CMDMODE(0, "quit", &action,
1091 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1092 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1093 "during an interactive rebase"), ACTION_EDIT_TODO),
1094 OPT_CMDMODE(0, "show-current-patch", &action,
1095 N_("show the patch file being applied or merged"),
1096 ACTION_SHOW_CURRENT_PATCH),
1097 OPT_CALLBACK_F(0, "apply", &options, NULL,
1098 N_("use apply strategies to rebase"),
1099 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1100 parse_opt_am),
1101 OPT_CALLBACK_F('m', "merge", &options, NULL,
1102 N_("use merging strategies to rebase"),
1103 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1104 parse_opt_merge),
1105 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1106 N_("let the user edit the list of commits to rebase"),
1107 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1108 parse_opt_interactive),
1109 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1110 N_("(DEPRECATED) try to recreate merges instead of "
1111 "ignoring them"),
1112 1, PARSE_OPT_HIDDEN),
1113 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1114 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1115 N_("how to handle commits that become empty"),
1116 PARSE_OPT_NONEG, parse_opt_empty),
1117 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1118 N_("keep commits which start empty"),
1119 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1120 parse_opt_keep_empty),
1121 OPT_BOOL(0, "autosquash", &options.autosquash,
1122 N_("move commits that begin with "
1123 "squash!/fixup! under -i")),
1124 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1125 N_("GPG-sign commits"),
1126 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1127 OPT_AUTOSTASH(&options.autostash),
1128 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1129 N_("add exec lines after each commit of the "
1130 "editable list")),
1131 OPT_BOOL_F(0, "allow-empty-message",
1132 &options.allow_empty_message,
1133 N_("allow rebasing commits with empty messages"),
1134 PARSE_OPT_HIDDEN),
1135 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1136 N_("mode"),
1137 N_("try to rebase merges instead of skipping them"),
1138 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1139 OPT_BOOL(0, "fork-point", &options.fork_point,
1140 N_("use 'merge-base --fork-point' to refine upstream")),
1141 OPT_STRING('s', "strategy", &options.strategy,
1142 N_("strategy"), N_("use the given merge strategy")),
1143 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1144 N_("option"),
1145 N_("pass the argument through to the merge "
1146 "strategy")),
1147 OPT_BOOL(0, "root", &options.root,
1148 N_("rebase all reachable commits up to the root(s)")),
1149 OPT_BOOL(0, "reschedule-failed-exec",
1150 &reschedule_failed_exec,
1151 N_("automatically re-schedule any `exec` that fails")),
1152 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1153 N_("apply all changes, even those already present upstream")),
1154 OPT_END(),
1156 int i;
1158 if (argc == 2 && !strcmp(argv[1], "-h"))
1159 usage_with_options(builtin_rebase_usage,
1160 builtin_rebase_options);
1162 prepare_repo_settings(the_repository);
1163 the_repository->settings.command_requires_full_index = 0;
1165 options.allow_empty_message = 1;
1166 git_config(rebase_config, &options);
1167 /* options.gpg_sign_opt will be either "-S" or NULL */
1168 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1169 FREE_AND_NULL(options.gpg_sign_opt);
1171 strbuf_reset(&buf);
1172 strbuf_addf(&buf, "%s/applying", apply_dir());
1173 if(file_exists(buf.buf))
1174 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1176 if (is_directory(apply_dir())) {
1177 options.type = REBASE_APPLY;
1178 options.state_dir = apply_dir();
1179 } else if (is_directory(merge_dir())) {
1180 strbuf_reset(&buf);
1181 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1182 if (is_directory(buf.buf)) {
1183 die("`rebase -p` is no longer supported");
1184 } else {
1185 strbuf_reset(&buf);
1186 strbuf_addf(&buf, "%s/interactive", merge_dir());
1187 if(file_exists(buf.buf)) {
1188 options.type = REBASE_MERGE;
1189 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1190 } else
1191 options.type = REBASE_MERGE;
1193 options.state_dir = merge_dir();
1196 if (options.type != REBASE_UNSPECIFIED)
1197 in_progress = 1;
1199 total_argc = argc;
1200 argc = parse_options(argc, argv, prefix,
1201 builtin_rebase_options,
1202 builtin_rebase_usage, 0);
1204 if (preserve_merges_selected)
1205 die(_("--preserve-merges was replaced by --rebase-merges"));
1207 if (action != ACTION_NONE && total_argc != 2) {
1208 usage_with_options(builtin_rebase_usage,
1209 builtin_rebase_options);
1212 if (argc > 2)
1213 usage_with_options(builtin_rebase_usage,
1214 builtin_rebase_options);
1216 if (keep_base) {
1217 if (options.onto_name)
1218 die(_("cannot combine '--keep-base' with '--onto'"));
1219 if (options.root)
1220 die(_("cannot combine '--keep-base' with '--root'"));
1223 if (options.root && options.fork_point > 0)
1224 die(_("cannot combine '--root' with '--fork-point'"));
1226 if (action != ACTION_NONE && !in_progress)
1227 die(_("No rebase in progress?"));
1228 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1230 if (action == ACTION_EDIT_TODO && !is_merge(&options))
1231 die(_("The --edit-todo action can only be used during "
1232 "interactive rebase."));
1234 if (trace2_is_enabled()) {
1235 if (is_merge(&options))
1236 trace2_cmd_mode("interactive");
1237 else if (exec.nr)
1238 trace2_cmd_mode("interactive-exec");
1239 else
1240 trace2_cmd_mode(action_names[action]);
1243 switch (action) {
1244 case ACTION_CONTINUE: {
1245 struct object_id head;
1246 struct lock_file lock_file = LOCK_INIT;
1247 int fd;
1249 options.action = "continue";
1250 set_reflog_action(&options);
1252 /* Sanity check */
1253 if (get_oid("HEAD", &head))
1254 die(_("Cannot read HEAD"));
1256 fd = hold_locked_index(&lock_file, 0);
1257 if (repo_read_index(the_repository) < 0)
1258 die(_("could not read index"));
1259 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1260 NULL);
1261 if (0 <= fd)
1262 repo_update_index_if_able(the_repository, &lock_file);
1263 rollback_lock_file(&lock_file);
1265 if (has_unstaged_changes(the_repository, 1)) {
1266 puts(_("You must edit all merge conflicts and then\n"
1267 "mark them as resolved using git add"));
1268 exit(1);
1270 if (read_basic_state(&options))
1271 exit(1);
1272 goto run_rebase;
1274 case ACTION_SKIP: {
1275 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1277 options.action = "skip";
1278 set_reflog_action(&options);
1280 rerere_clear(the_repository, &merge_rr);
1281 string_list_clear(&merge_rr, 1);
1282 ropts.flags = RESET_HEAD_HARD;
1283 if (reset_head(the_repository, &ropts) < 0)
1284 die(_("could not discard worktree changes"));
1285 remove_branch_state(the_repository, 0);
1286 if (read_basic_state(&options))
1287 exit(1);
1288 goto run_rebase;
1290 case ACTION_ABORT: {
1291 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1292 options.action = "abort";
1293 set_reflog_action(&options);
1295 rerere_clear(the_repository, &merge_rr);
1296 string_list_clear(&merge_rr, 1);
1298 if (read_basic_state(&options))
1299 exit(1);
1300 ropts.oid = &options.orig_head;
1301 ropts.branch = options.head_name;
1302 ropts.flags = RESET_HEAD_HARD;
1303 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1304 if (reset_head(the_repository, &ropts) < 0)
1305 die(_("could not move back to %s"),
1306 oid_to_hex(&options.orig_head));
1307 remove_branch_state(the_repository, 0);
1308 ret = finish_rebase(&options);
1309 goto cleanup;
1311 case ACTION_QUIT: {
1312 save_autostash(state_dir_path("autostash", &options));
1313 if (options.type == REBASE_MERGE) {
1314 struct replay_opts replay = REPLAY_OPTS_INIT;
1316 replay.action = REPLAY_INTERACTIVE_REBASE;
1317 ret = sequencer_remove_state(&replay);
1318 } else {
1319 strbuf_reset(&buf);
1320 strbuf_addstr(&buf, options.state_dir);
1321 ret = remove_dir_recursively(&buf, 0);
1322 if (ret)
1323 error(_("could not remove '%s'"),
1324 options.state_dir);
1326 goto cleanup;
1328 case ACTION_EDIT_TODO:
1329 options.action = "edit-todo";
1330 options.dont_finish_rebase = 1;
1331 goto run_rebase;
1332 case ACTION_SHOW_CURRENT_PATCH:
1333 options.action = "show-current-patch";
1334 options.dont_finish_rebase = 1;
1335 goto run_rebase;
1336 case ACTION_NONE:
1337 break;
1338 default:
1339 BUG("action: %d", action);
1342 /* Make sure no rebase is in progress */
1343 if (in_progress) {
1344 const char *last_slash = strrchr(options.state_dir, '/');
1345 const char *state_dir_base =
1346 last_slash ? last_slash + 1 : options.state_dir;
1347 const char *cmd_live_rebase =
1348 "git rebase (--continue | --abort | --skip)";
1349 strbuf_reset(&buf);
1350 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1351 die(_("It seems that there is already a %s directory, and\n"
1352 "I wonder if you are in the middle of another rebase. "
1353 "If that is the\n"
1354 "case, please try\n\t%s\n"
1355 "If that is not the case, please\n\t%s\n"
1356 "and run me again. I am stopping in case you still "
1357 "have something\n"
1358 "valuable there.\n"),
1359 state_dir_base, cmd_live_rebase, buf.buf);
1362 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1363 (action != ACTION_NONE) ||
1364 (exec.nr > 0) ||
1365 options.autosquash) {
1366 allow_preemptive_ff = 0;
1368 if (options.committer_date_is_author_date || options.ignore_date)
1369 options.flags |= REBASE_FORCE;
1371 for (i = 0; i < options.git_am_opts.nr; i++) {
1372 const char *option = options.git_am_opts.v[i], *p;
1373 if (!strcmp(option, "--whitespace=fix") ||
1374 !strcmp(option, "--whitespace=strip"))
1375 allow_preemptive_ff = 0;
1376 else if (skip_prefix(option, "-C", &p)) {
1377 while (*p)
1378 if (!isdigit(*(p++)))
1379 die(_("switch `C' expects a "
1380 "numerical value"));
1381 } else if (skip_prefix(option, "--whitespace=", &p)) {
1382 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1383 strcmp(p, "error") && strcmp(p, "error-all"))
1384 die("Invalid whitespace option: '%s'", p);
1388 for (i = 0; i < exec.nr; i++)
1389 if (check_exec_cmd(exec.items[i].string))
1390 exit(1);
1392 if (!(options.flags & REBASE_NO_QUIET))
1393 strvec_push(&options.git_am_opts, "-q");
1395 if (options.empty != EMPTY_UNSPECIFIED)
1396 imply_merge(&options, "--empty");
1398 if (options.reapply_cherry_picks)
1399 imply_merge(&options, "--reapply-cherry-picks");
1401 if (gpg_sign)
1402 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1404 if (exec.nr) {
1405 int i;
1407 imply_merge(&options, "--exec");
1409 strbuf_reset(&buf);
1410 for (i = 0; i < exec.nr; i++)
1411 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1412 options.cmd = xstrdup(buf.buf);
1415 if (rebase_merges) {
1416 if (!*rebase_merges)
1417 ; /* default mode; do nothing */
1418 else if (!strcmp("rebase-cousins", rebase_merges))
1419 options.rebase_cousins = 1;
1420 else if (strcmp("no-rebase-cousins", rebase_merges))
1421 die(_("Unknown mode: %s"), rebase_merges);
1422 options.rebase_merges = 1;
1423 imply_merge(&options, "--rebase-merges");
1426 if (options.type == REBASE_APPLY) {
1427 if (ignore_whitespace)
1428 strvec_push(&options.git_am_opts,
1429 "--ignore-whitespace");
1430 if (options.committer_date_is_author_date)
1431 strvec_push(&options.git_am_opts,
1432 "--committer-date-is-author-date");
1433 if (options.ignore_date)
1434 strvec_push(&options.git_am_opts, "--ignore-date");
1435 } else {
1436 /* REBASE_MERGE */
1437 if (ignore_whitespace) {
1438 string_list_append(&strategy_options,
1439 "ignore-space-change");
1443 if (strategy_options.nr) {
1444 int i;
1446 if (!options.strategy)
1447 options.strategy = "ort";
1449 strbuf_reset(&buf);
1450 for (i = 0; i < strategy_options.nr; i++)
1451 strbuf_addf(&buf, " --%s",
1452 strategy_options.items[i].string);
1453 options.strategy_opts = xstrdup(buf.buf);
1456 if (options.strategy) {
1457 options.strategy = xstrdup(options.strategy);
1458 switch (options.type) {
1459 case REBASE_APPLY:
1460 die(_("--strategy requires --merge or --interactive"));
1461 case REBASE_MERGE:
1462 /* compatible */
1463 break;
1464 case REBASE_UNSPECIFIED:
1465 options.type = REBASE_MERGE;
1466 break;
1467 default:
1468 BUG("unhandled rebase type (%d)", options.type);
1472 if (options.type == REBASE_MERGE)
1473 imply_merge(&options, "--merge");
1475 if (options.root && !options.onto_name)
1476 imply_merge(&options, "--root without --onto");
1478 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1479 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1481 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1482 /* all am options except -q are compatible only with --apply */
1483 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1484 if (strcmp(options.git_am_opts.v[i], "-q"))
1485 break;
1487 if (i >= 0) {
1488 if (is_merge(&options))
1489 die(_("cannot combine apply options with "
1490 "merge options"));
1491 else
1492 options.type = REBASE_APPLY;
1496 if (options.type == REBASE_UNSPECIFIED) {
1497 if (!strcmp(options.default_backend, "merge"))
1498 imply_merge(&options, "--merge");
1499 else if (!strcmp(options.default_backend, "apply"))
1500 options.type = REBASE_APPLY;
1501 else
1502 die(_("Unknown rebase backend: %s"),
1503 options.default_backend);
1506 if (options.type == REBASE_MERGE &&
1507 !options.strategy &&
1508 getenv("GIT_TEST_MERGE_ALGORITHM"))
1509 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1511 switch (options.type) {
1512 case REBASE_MERGE:
1513 options.state_dir = merge_dir();
1514 break;
1515 case REBASE_APPLY:
1516 options.state_dir = apply_dir();
1517 break;
1518 default:
1519 BUG("options.type was just set above; should be unreachable.");
1522 if (options.empty == EMPTY_UNSPECIFIED) {
1523 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1524 options.empty = EMPTY_ASK;
1525 else if (exec.nr > 0)
1526 options.empty = EMPTY_KEEP;
1527 else
1528 options.empty = EMPTY_DROP;
1530 if (reschedule_failed_exec > 0 && !is_merge(&options))
1531 die(_("--reschedule-failed-exec requires "
1532 "--exec or --interactive"));
1533 if (reschedule_failed_exec >= 0)
1534 options.reschedule_failed_exec = reschedule_failed_exec;
1536 if (options.signoff) {
1537 strvec_push(&options.git_am_opts, "--signoff");
1538 options.flags |= REBASE_FORCE;
1541 if (!options.root) {
1542 if (argc < 1) {
1543 struct branch *branch;
1545 branch = branch_get(NULL);
1546 options.upstream_name = branch_get_upstream(branch,
1547 NULL);
1548 if (!options.upstream_name)
1549 error_on_missing_default_upstream();
1550 if (options.fork_point < 0)
1551 options.fork_point = 1;
1552 } else {
1553 options.upstream_name = argv[0];
1554 argc--;
1555 argv++;
1556 if (!strcmp(options.upstream_name, "-"))
1557 options.upstream_name = "@{-1}";
1559 options.upstream =
1560 lookup_commit_reference_by_name(options.upstream_name);
1561 if (!options.upstream)
1562 die(_("invalid upstream '%s'"), options.upstream_name);
1563 options.upstream_arg = options.upstream_name;
1564 } else {
1565 if (!options.onto_name) {
1566 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1567 &squash_onto, NULL, NULL) < 0)
1568 die(_("Could not create new root commit"));
1569 options.squash_onto = &squash_onto;
1570 options.onto_name = squash_onto_name =
1571 xstrdup(oid_to_hex(&squash_onto));
1572 } else
1573 options.root_with_onto = 1;
1575 options.upstream_name = NULL;
1576 options.upstream = NULL;
1577 if (argc > 1)
1578 usage_with_options(builtin_rebase_usage,
1579 builtin_rebase_options);
1580 options.upstream_arg = "--root";
1583 /* Make sure the branch to rebase onto is valid. */
1584 if (keep_base) {
1585 strbuf_reset(&buf);
1586 strbuf_addstr(&buf, options.upstream_name);
1587 strbuf_addstr(&buf, "...");
1588 options.onto_name = xstrdup(buf.buf);
1589 } else if (!options.onto_name)
1590 options.onto_name = options.upstream_name;
1591 if (strstr(options.onto_name, "...")) {
1592 if (get_oid_mb(options.onto_name, &merge_base) < 0) {
1593 if (keep_base)
1594 die(_("'%s': need exactly one merge base with branch"),
1595 options.upstream_name);
1596 else
1597 die(_("'%s': need exactly one merge base"),
1598 options.onto_name);
1600 options.onto = lookup_commit_or_die(&merge_base,
1601 options.onto_name);
1602 } else {
1603 options.onto =
1604 lookup_commit_reference_by_name(options.onto_name);
1605 if (!options.onto)
1606 die(_("Does not point to a valid commit '%s'"),
1607 options.onto_name);
1611 * If the branch to rebase is given, that is the branch we will rebase
1612 * branch_name -- branch/commit being rebased, or
1613 * HEAD (already detached)
1614 * orig_head -- commit object name of tip of the branch before rebasing
1615 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1617 if (argc == 1) {
1618 /* Is it "rebase other branchname" or "rebase other commit"? */
1619 branch_name = argv[0];
1620 options.switch_to = argv[0];
1622 /* Is it a local branch? */
1623 strbuf_reset(&buf);
1624 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1625 if (!read_ref(buf.buf, &options.orig_head)) {
1626 die_if_checked_out(buf.buf, 1);
1627 options.head_name = xstrdup(buf.buf);
1628 /* If not is it a valid ref (branch or commit)? */
1629 } else {
1630 struct commit *commit =
1631 lookup_commit_reference_by_name(branch_name);
1632 if (!commit)
1633 die(_("no such branch/commit '%s'"),
1634 branch_name);
1635 oidcpy(&options.orig_head, &commit->object.oid);
1636 options.head_name = NULL;
1638 } else if (argc == 0) {
1639 /* Do not need to switch branches, we are already on it. */
1640 options.head_name =
1641 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1642 &flags));
1643 if (!options.head_name)
1644 die(_("No such ref: %s"), "HEAD");
1645 if (flags & REF_ISSYMREF) {
1646 if (!skip_prefix(options.head_name,
1647 "refs/heads/", &branch_name))
1648 branch_name = options.head_name;
1650 } else {
1651 FREE_AND_NULL(options.head_name);
1652 branch_name = "HEAD";
1654 if (get_oid("HEAD", &options.orig_head))
1655 die(_("Could not resolve HEAD to a revision"));
1656 } else
1657 BUG("unexpected number of arguments left to parse");
1659 if (options.fork_point > 0) {
1660 struct commit *head =
1661 lookup_commit_reference(the_repository,
1662 &options.orig_head);
1663 options.restrict_revision =
1664 get_fork_point(options.upstream_name, head);
1667 if (repo_read_index(the_repository) < 0)
1668 die(_("could not read index"));
1670 if (options.autostash)
1671 create_autostash(the_repository,
1672 state_dir_path("autostash", &options));
1675 if (require_clean_work_tree(the_repository, "rebase",
1676 _("Please commit or stash them."), 1, 1)) {
1677 ret = -1;
1678 goto cleanup;
1682 * Now we are rebasing commits upstream..orig_head (or with --root,
1683 * everything leading up to orig_head) on top of onto.
1687 * Check if we are already based on onto with linear history,
1688 * in which case we could fast-forward without replacing the commits
1689 * with new commits recreated by replaying their changes.
1691 * Note that can_fast_forward() initializes merge_base, so we have to
1692 * call it before checking allow_preemptive_ff.
1694 if (can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1695 &options.orig_head, &merge_base) &&
1696 allow_preemptive_ff) {
1697 int flag;
1699 if (!(options.flags & REBASE_FORCE)) {
1700 /* Lazily switch to the target branch if needed... */
1701 if (options.switch_to) {
1702 ret = checkout_up_to_date(&options);
1703 if (ret)
1704 goto cleanup;
1707 if (!(options.flags & REBASE_NO_QUIET))
1708 ; /* be quiet */
1709 else if (!strcmp(branch_name, "HEAD") &&
1710 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1711 puts(_("HEAD is up to date."));
1712 else
1713 printf(_("Current branch %s is up to date.\n"),
1714 branch_name);
1715 ret = finish_rebase(&options);
1716 goto cleanup;
1717 } else if (!(options.flags & REBASE_NO_QUIET))
1718 ; /* be quiet */
1719 else if (!strcmp(branch_name, "HEAD") &&
1720 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1721 puts(_("HEAD is up to date, rebase forced."));
1722 else
1723 printf(_("Current branch %s is up to date, rebase "
1724 "forced.\n"), branch_name);
1727 /* If a hook exists, give it a chance to interrupt*/
1728 if (!ok_to_skip_pre_rebase &&
1729 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1730 argc ? argv[0] : NULL, NULL))
1731 die(_("The pre-rebase hook refused to rebase."));
1733 if (options.flags & REBASE_DIFFSTAT) {
1734 struct diff_options opts;
1736 if (options.flags & REBASE_VERBOSE) {
1737 if (is_null_oid(&merge_base))
1738 printf(_("Changes to %s:\n"),
1739 oid_to_hex(&options.onto->object.oid));
1740 else
1741 printf(_("Changes from %s to %s:\n"),
1742 oid_to_hex(&merge_base),
1743 oid_to_hex(&options.onto->object.oid));
1746 /* We want color (if set), but no pager */
1747 diff_setup(&opts);
1748 opts.stat_width = -1; /* use full terminal width */
1749 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1750 opts.output_format |=
1751 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1752 opts.detect_rename = DIFF_DETECT_RENAME;
1753 diff_setup_done(&opts);
1754 diff_tree_oid(is_null_oid(&merge_base) ?
1755 the_hash_algo->empty_tree : &merge_base,
1756 &options.onto->object.oid, "", &opts);
1757 diffcore_std(&opts);
1758 diff_flush(&opts);
1761 if (is_merge(&options))
1762 goto run_rebase;
1764 /* Detach HEAD and reset the tree */
1765 if (options.flags & REBASE_NO_QUIET)
1766 printf(_("First, rewinding head to replay your work on top of "
1767 "it...\n"));
1769 strbuf_addf(&msg, "%s: checkout %s",
1770 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1771 ropts.oid = &options.onto->object.oid;
1772 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1773 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1774 ropts.head_msg = msg.buf;
1775 ropts.default_reflog_action = DEFAULT_REFLOG_ACTION;
1776 if (reset_head(the_repository, &ropts))
1777 die(_("Could not detach HEAD"));
1778 strbuf_release(&msg);
1781 * If the onto is a proper descendant of the tip of the branch, then
1782 * we just fast-forwarded.
1784 strbuf_reset(&msg);
1785 if (oideq(&merge_base, &options.orig_head)) {
1786 printf(_("Fast-forwarded %s to %s.\n"),
1787 branch_name, options.onto_name);
1788 strbuf_addf(&msg, "rebase finished: %s onto %s",
1789 options.head_name ? options.head_name : "detached HEAD",
1790 oid_to_hex(&options.onto->object.oid));
1791 memset(&ropts, 0, sizeof(ropts));
1792 ropts.branch = options.head_name;
1793 ropts.flags = RESET_HEAD_REFS_ONLY;
1794 ropts.head_msg = msg.buf;
1795 reset_head(the_repository, &ropts);
1796 strbuf_release(&msg);
1797 ret = finish_rebase(&options);
1798 goto cleanup;
1801 strbuf_addf(&revisions, "%s..%s",
1802 options.root ? oid_to_hex(&options.onto->object.oid) :
1803 (options.restrict_revision ?
1804 oid_to_hex(&options.restrict_revision->object.oid) :
1805 oid_to_hex(&options.upstream->object.oid)),
1806 oid_to_hex(&options.orig_head));
1808 options.revisions = revisions.buf;
1810 run_rebase:
1811 ret = run_specific_rebase(&options, action);
1813 cleanup:
1814 strbuf_release(&buf);
1815 strbuf_release(&revisions);
1816 free(options.head_name);
1817 free(options.gpg_sign_opt);
1818 free(options.cmd);
1819 free(options.strategy);
1820 strbuf_release(&options.git_format_patch_opt);
1821 free(squash_onto_name);
1822 return !!ret;