refs API: make refs_ref_exists() not set errno
[git/debian.git] / builtin / rebase.c
blob8c6393f6d783834524095e4925131969abd99d6e
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,
52 REBASE_PRESERVE_MERGES
55 enum empty_type {
56 EMPTY_UNSPECIFIED = -1,
57 EMPTY_DROP,
58 EMPTY_KEEP,
59 EMPTY_ASK
62 struct rebase_options {
63 enum rebase_type type;
64 enum empty_type empty;
65 const char *default_backend;
66 const char *state_dir;
67 struct commit *upstream;
68 const char *upstream_name;
69 const char *upstream_arg;
70 char *head_name;
71 struct object_id orig_head;
72 struct commit *onto;
73 const char *onto_name;
74 const char *revisions;
75 const char *switch_to;
76 int root, root_with_onto;
77 struct object_id *squash_onto;
78 struct commit *restrict_revision;
79 int dont_finish_rebase;
80 enum {
81 REBASE_NO_QUIET = 1<<0,
82 REBASE_VERBOSE = 1<<1,
83 REBASE_DIFFSTAT = 1<<2,
84 REBASE_FORCE = 1<<3,
85 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
86 } flags;
87 struct strvec git_am_opts;
88 const char *action;
89 int signoff;
90 int allow_rerere_autoupdate;
91 int keep_empty;
92 int autosquash;
93 char *gpg_sign_opt;
94 int autostash;
95 int committer_date_is_author_date;
96 int ignore_date;
97 char *cmd;
98 int allow_empty_message;
99 int rebase_merges, rebase_cousins;
100 char *strategy, *strategy_opts;
101 struct strbuf git_format_patch_opt;
102 int reschedule_failed_exec;
103 int reapply_cherry_picks;
104 int fork_point;
107 #define REBASE_OPTIONS_INIT { \
108 .type = REBASE_UNSPECIFIED, \
109 .empty = EMPTY_UNSPECIFIED, \
110 .keep_empty = 1, \
111 .default_backend = "merge", \
112 .flags = REBASE_NO_QUIET, \
113 .git_am_opts = STRVEC_INIT, \
114 .git_format_patch_opt = STRBUF_INIT, \
115 .fork_point = -1, \
118 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
120 struct replay_opts replay = REPLAY_OPTS_INIT;
122 replay.action = REPLAY_INTERACTIVE_REBASE;
123 replay.strategy = NULL;
124 sequencer_init_config(&replay);
126 replay.signoff = opts->signoff;
127 replay.allow_ff = !(opts->flags & REBASE_FORCE);
128 if (opts->allow_rerere_autoupdate)
129 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
130 replay.allow_empty = 1;
131 replay.allow_empty_message = opts->allow_empty_message;
132 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
133 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
134 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
135 replay.verbose = opts->flags & REBASE_VERBOSE;
136 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
137 replay.committer_date_is_author_date =
138 opts->committer_date_is_author_date;
139 replay.ignore_date = opts->ignore_date;
140 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
141 if (opts->strategy)
142 replay.strategy = xstrdup_or_null(opts->strategy);
143 else if (!replay.strategy && replay.default_strategy) {
144 replay.strategy = replay.default_strategy;
145 replay.default_strategy = NULL;
148 if (opts->strategy_opts)
149 parse_strategy_opts(&replay, opts->strategy_opts);
151 if (opts->squash_onto) {
152 oidcpy(&replay.squash_onto, opts->squash_onto);
153 replay.have_squash_onto = 1;
156 return replay;
159 enum action {
160 ACTION_NONE = 0,
161 ACTION_CONTINUE,
162 ACTION_SKIP,
163 ACTION_ABORT,
164 ACTION_QUIT,
165 ACTION_EDIT_TODO,
166 ACTION_SHOW_CURRENT_PATCH,
167 ACTION_SHORTEN_OIDS,
168 ACTION_EXPAND_OIDS,
169 ACTION_CHECK_TODO_LIST,
170 ACTION_REARRANGE_SQUASH,
171 ACTION_ADD_EXEC
174 static const char *action_names[] = { "undefined",
175 "continue",
176 "skip",
177 "abort",
178 "quit",
179 "edit_todo",
180 "show_current_patch" };
182 static int add_exec_commands(struct string_list *commands)
184 const char *todo_file = rebase_path_todo();
185 struct todo_list todo_list = TODO_LIST_INIT;
186 int res;
188 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
189 return error_errno(_("could not read '%s'."), todo_file);
191 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
192 &todo_list)) {
193 todo_list_release(&todo_list);
194 return error(_("unusable todo list: '%s'"), todo_file);
197 todo_list_add_exec_commands(&todo_list, commands);
198 res = todo_list_write_to_file(the_repository, &todo_list,
199 todo_file, NULL, NULL, -1, 0);
200 todo_list_release(&todo_list);
202 if (res)
203 return error_errno(_("could not write '%s'."), todo_file);
204 return 0;
207 static int rearrange_squash_in_todo_file(void)
209 const char *todo_file = rebase_path_todo();
210 struct todo_list todo_list = TODO_LIST_INIT;
211 int res = 0;
213 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
214 return error_errno(_("could not read '%s'."), todo_file);
215 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
216 &todo_list)) {
217 todo_list_release(&todo_list);
218 return error(_("unusable todo list: '%s'"), todo_file);
221 res = todo_list_rearrange_squash(&todo_list);
222 if (!res)
223 res = todo_list_write_to_file(the_repository, &todo_list,
224 todo_file, NULL, NULL, -1, 0);
226 todo_list_release(&todo_list);
228 if (res)
229 return error_errno(_("could not write '%s'."), todo_file);
230 return 0;
233 static int transform_todo_file(unsigned flags)
235 const char *todo_file = rebase_path_todo();
236 struct todo_list todo_list = TODO_LIST_INIT;
237 int res;
239 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
240 return error_errno(_("could not read '%s'."), todo_file);
242 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
243 &todo_list)) {
244 todo_list_release(&todo_list);
245 return error(_("unusable todo list: '%s'"), todo_file);
248 res = todo_list_write_to_file(the_repository, &todo_list, todo_file,
249 NULL, NULL, -1, flags);
250 todo_list_release(&todo_list);
252 if (res)
253 return error_errno(_("could not write '%s'."), todo_file);
254 return 0;
257 static int edit_todo_file(unsigned flags)
259 const char *todo_file = rebase_path_todo();
260 struct todo_list todo_list = TODO_LIST_INIT,
261 new_todo = TODO_LIST_INIT;
262 int res = 0;
264 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
265 return error_errno(_("could not read '%s'."), todo_file);
267 strbuf_stripspace(&todo_list.buf, 1);
268 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
269 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
270 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
271 res = error_errno(_("could not write '%s'"), todo_file);
273 todo_list_release(&todo_list);
274 todo_list_release(&new_todo);
276 return res;
279 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
280 struct object_id *orig_head, char **revisions,
281 char **shortrevisions)
283 struct commit *base_rev = upstream ? upstream : onto;
284 const char *shorthead;
286 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
287 oid_to_hex(orig_head));
289 shorthead = find_unique_abbrev(orig_head, DEFAULT_ABBREV);
291 if (upstream) {
292 const char *shortrev;
294 shortrev = find_unique_abbrev(&base_rev->object.oid,
295 DEFAULT_ABBREV);
297 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
298 } else
299 *shortrevisions = xstrdup(shorthead);
301 return 0;
304 static int init_basic_state(struct replay_opts *opts, const char *head_name,
305 struct commit *onto,
306 const struct object_id *orig_head)
308 FILE *interactive;
310 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
311 return error_errno(_("could not create temporary %s"), merge_dir());
313 delete_reflog("REBASE_HEAD");
315 interactive = fopen(path_interactive(), "w");
316 if (!interactive)
317 return error_errno(_("could not mark as interactive"));
318 fclose(interactive);
320 return write_basic_state(opts, head_name, onto, orig_head);
323 static void split_exec_commands(const char *cmd, struct string_list *commands)
325 if (cmd && *cmd) {
326 string_list_split(commands, cmd, '\n', -1);
328 /* rebase.c adds a new line to cmd after every command,
329 * so here the last command is always empty */
330 string_list_remove_empty_items(commands, 0);
334 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
336 int ret;
337 char *revisions = NULL, *shortrevisions = NULL;
338 struct strvec make_script_args = STRVEC_INIT;
339 struct todo_list todo_list = TODO_LIST_INIT;
340 struct replay_opts replay = get_replay_opts(opts);
341 struct string_list commands = STRING_LIST_INIT_DUP;
343 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head,
344 &revisions, &shortrevisions))
345 return -1;
347 if (init_basic_state(&replay,
348 opts->head_name ? opts->head_name : "detached HEAD",
349 opts->onto, &opts->orig_head)) {
350 free(revisions);
351 free(shortrevisions);
353 return -1;
356 if (!opts->upstream && opts->squash_onto)
357 write_file(path_squash_onto(), "%s\n",
358 oid_to_hex(opts->squash_onto));
360 strvec_pushl(&make_script_args, "", revisions, NULL);
361 if (opts->restrict_revision)
362 strvec_pushf(&make_script_args, "^%s",
363 oid_to_hex(&opts->restrict_revision->object.oid));
365 ret = sequencer_make_script(the_repository, &todo_list.buf,
366 make_script_args.nr, make_script_args.v,
367 flags);
369 if (ret)
370 error(_("could not generate todo list"));
371 else {
372 discard_cache();
373 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
374 &todo_list))
375 BUG("unusable todo list");
377 split_exec_commands(opts->cmd, &commands);
378 ret = complete_action(the_repository, &replay, flags,
379 shortrevisions, opts->onto_name, opts->onto,
380 &opts->orig_head, &commands, opts->autosquash,
381 &todo_list);
384 string_list_clear(&commands, 0);
385 free(revisions);
386 free(shortrevisions);
387 todo_list_release(&todo_list);
388 strvec_clear(&make_script_args);
390 return ret;
393 static int run_sequencer_rebase(struct rebase_options *opts,
394 enum action command)
396 unsigned flags = 0;
397 int abbreviate_commands = 0, ret = 0;
399 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
401 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
402 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
403 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
404 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
405 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
406 flags |= command == ACTION_SHORTEN_OIDS ? TODO_LIST_SHORTEN_IDS : 0;
407 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
408 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
410 switch (command) {
411 case ACTION_NONE: {
412 if (!opts->onto && !opts->upstream)
413 die(_("a base commit must be provided with --upstream or --onto"));
415 ret = do_interactive_rebase(opts, flags);
416 break;
418 case ACTION_SKIP: {
419 struct string_list merge_rr = STRING_LIST_INIT_DUP;
421 rerere_clear(the_repository, &merge_rr);
423 /* fallthrough */
424 case ACTION_CONTINUE: {
425 struct replay_opts replay_opts = get_replay_opts(opts);
427 ret = sequencer_continue(the_repository, &replay_opts);
428 break;
430 case ACTION_EDIT_TODO:
431 ret = edit_todo_file(flags);
432 break;
433 case ACTION_SHOW_CURRENT_PATCH: {
434 struct child_process cmd = CHILD_PROCESS_INIT;
436 cmd.git_cmd = 1;
437 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
438 ret = run_command(&cmd);
440 break;
442 case ACTION_SHORTEN_OIDS:
443 case ACTION_EXPAND_OIDS:
444 ret = transform_todo_file(flags);
445 break;
446 case ACTION_CHECK_TODO_LIST:
447 ret = check_todo_list_from_file(the_repository);
448 break;
449 case ACTION_REARRANGE_SQUASH:
450 ret = rearrange_squash_in_todo_file();
451 break;
452 case ACTION_ADD_EXEC: {
453 struct string_list commands = STRING_LIST_INIT_DUP;
455 split_exec_commands(opts->cmd, &commands);
456 ret = add_exec_commands(&commands);
457 string_list_clear(&commands, 0);
458 break;
460 default:
461 BUG("invalid command '%d'", command);
464 return ret;
467 static void imply_merge(struct rebase_options *opts, const char *option);
468 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
469 int unset)
471 struct rebase_options *opts = opt->value;
473 BUG_ON_OPT_ARG(arg);
475 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
476 opts->keep_empty = !unset;
477 opts->type = REBASE_MERGE;
478 return 0;
481 static const char * const builtin_rebase_interactive_usage[] = {
482 N_("git rebase--interactive [<options>]"),
483 NULL
486 int cmd_rebase__interactive(int argc, const char **argv, const char *prefix)
488 struct rebase_options opts = REBASE_OPTIONS_INIT;
489 struct object_id squash_onto = *null_oid();
490 enum action command = ACTION_NONE;
491 struct option options[] = {
492 OPT_NEGBIT(0, "ff", &opts.flags, N_("allow fast-forward"),
493 REBASE_FORCE),
494 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
495 N_("keep commits which start empty"),
496 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
497 parse_opt_keep_empty),
498 OPT_BOOL_F(0, "allow-empty-message", &opts.allow_empty_message,
499 N_("allow commits with empty messages"),
500 PARSE_OPT_HIDDEN),
501 OPT_BOOL(0, "rebase-merges", &opts.rebase_merges, N_("rebase merge commits")),
502 OPT_BOOL(0, "rebase-cousins", &opts.rebase_cousins,
503 N_("keep original branch points of cousins")),
504 OPT_BOOL(0, "autosquash", &opts.autosquash,
505 N_("move commits that begin with squash!/fixup!")),
506 OPT_BOOL(0, "signoff", &opts.signoff, N_("sign commits")),
507 OPT_BIT('v', "verbose", &opts.flags,
508 N_("display a diffstat of what changed upstream"),
509 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
510 OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),
511 ACTION_CONTINUE),
512 OPT_CMDMODE(0, "skip", &command, N_("skip commit"), ACTION_SKIP),
513 OPT_CMDMODE(0, "edit-todo", &command, N_("edit the todo list"),
514 ACTION_EDIT_TODO),
515 OPT_CMDMODE(0, "show-current-patch", &command, N_("show the current patch"),
516 ACTION_SHOW_CURRENT_PATCH),
517 OPT_CMDMODE(0, "shorten-ids", &command,
518 N_("shorten commit ids in the todo list"), ACTION_SHORTEN_OIDS),
519 OPT_CMDMODE(0, "expand-ids", &command,
520 N_("expand commit ids in the todo list"), ACTION_EXPAND_OIDS),
521 OPT_CMDMODE(0, "check-todo-list", &command,
522 N_("check the todo list"), ACTION_CHECK_TODO_LIST),
523 OPT_CMDMODE(0, "rearrange-squash", &command,
524 N_("rearrange fixup/squash lines"), ACTION_REARRANGE_SQUASH),
525 OPT_CMDMODE(0, "add-exec-commands", &command,
526 N_("insert exec commands in todo list"), ACTION_ADD_EXEC),
527 { OPTION_CALLBACK, 0, "onto", &opts.onto, N_("onto"), N_("onto"),
528 PARSE_OPT_NONEG, parse_opt_commit, 0 },
529 { OPTION_CALLBACK, 0, "restrict-revision", &opts.restrict_revision,
530 N_("restrict-revision"), N_("restrict revision"),
531 PARSE_OPT_NONEG, parse_opt_commit, 0 },
532 { OPTION_CALLBACK, 0, "squash-onto", &squash_onto, N_("squash-onto"),
533 N_("squash onto"), PARSE_OPT_NONEG, parse_opt_object_id, 0 },
534 { OPTION_CALLBACK, 0, "upstream", &opts.upstream, N_("upstream"),
535 N_("the upstream commit"), PARSE_OPT_NONEG, parse_opt_commit,
536 0 },
537 OPT_STRING(0, "head-name", &opts.head_name, N_("head-name"), N_("head name")),
538 { OPTION_STRING, 'S', "gpg-sign", &opts.gpg_sign_opt, N_("key-id"),
539 N_("GPG-sign commits"),
540 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
541 OPT_STRING(0, "strategy", &opts.strategy, N_("strategy"),
542 N_("rebase strategy")),
543 OPT_STRING(0, "strategy-opts", &opts.strategy_opts, N_("strategy-opts"),
544 N_("strategy options")),
545 OPT_STRING(0, "switch-to", &opts.switch_to, N_("switch-to"),
546 N_("the branch or commit to checkout")),
547 OPT_STRING(0, "onto-name", &opts.onto_name, N_("onto-name"), N_("onto name")),
548 OPT_STRING(0, "cmd", &opts.cmd, N_("cmd"), N_("the command to run")),
549 OPT_RERERE_AUTOUPDATE(&opts.allow_rerere_autoupdate),
550 OPT_BOOL(0, "reschedule-failed-exec", &opts.reschedule_failed_exec,
551 N_("automatically re-schedule any `exec` that fails")),
552 OPT_END()
555 opts.rebase_cousins = -1;
557 if (argc == 1)
558 usage_with_options(builtin_rebase_interactive_usage, options);
560 argc = parse_options(argc, argv, prefix, options,
561 builtin_rebase_interactive_usage, PARSE_OPT_KEEP_ARGV0);
563 prepare_repo_settings(the_repository);
564 the_repository->settings.command_requires_full_index = 0;
566 if (!is_null_oid(&squash_onto))
567 opts.squash_onto = &squash_onto;
569 if (opts.rebase_cousins >= 0 && !opts.rebase_merges)
570 warning(_("--[no-]rebase-cousins has no effect without "
571 "--rebase-merges"));
573 return !!run_sequencer_rebase(&opts, command);
576 static int is_merge(struct rebase_options *opts)
578 return opts->type == REBASE_MERGE ||
579 opts->type == REBASE_PRESERVE_MERGES;
582 static void imply_merge(struct rebase_options *opts, const char *option)
584 switch (opts->type) {
585 case REBASE_APPLY:
586 die(_("%s requires the merge backend"), option);
587 break;
588 case REBASE_MERGE:
589 case REBASE_PRESERVE_MERGES:
590 break;
591 default:
592 opts->type = REBASE_MERGE; /* implied */
593 break;
597 /* Returns the filename prefixed by the state_dir */
598 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
600 static struct strbuf path = STRBUF_INIT;
601 static size_t prefix_len;
603 if (!prefix_len) {
604 strbuf_addf(&path, "%s/", opts->state_dir);
605 prefix_len = path.len;
608 strbuf_setlen(&path, prefix_len);
609 strbuf_addstr(&path, filename);
610 return path.buf;
613 /* Initialize the rebase options from the state directory. */
614 static int read_basic_state(struct rebase_options *opts)
616 struct strbuf head_name = STRBUF_INIT;
617 struct strbuf buf = STRBUF_INIT;
618 struct object_id oid;
620 if (!read_oneliner(&head_name, state_dir_path("head-name", opts),
621 READ_ONELINER_WARN_MISSING) ||
622 !read_oneliner(&buf, state_dir_path("onto", opts),
623 READ_ONELINER_WARN_MISSING))
624 return -1;
625 opts->head_name = starts_with(head_name.buf, "refs/") ?
626 xstrdup(head_name.buf) : NULL;
627 strbuf_release(&head_name);
628 if (get_oid(buf.buf, &oid))
629 return error(_("could not get 'onto': '%s'"), buf.buf);
630 opts->onto = lookup_commit_or_die(&oid, buf.buf);
633 * We always write to orig-head, but interactive rebase used to write to
634 * head. Fall back to reading from head to cover for the case that the
635 * user upgraded git with an ongoing interactive rebase.
637 strbuf_reset(&buf);
638 if (file_exists(state_dir_path("orig-head", opts))) {
639 if (!read_oneliner(&buf, state_dir_path("orig-head", opts),
640 READ_ONELINER_WARN_MISSING))
641 return -1;
642 } else if (!read_oneliner(&buf, state_dir_path("head", opts),
643 READ_ONELINER_WARN_MISSING))
644 return -1;
645 if (get_oid(buf.buf, &opts->orig_head))
646 return error(_("invalid orig-head: '%s'"), buf.buf);
648 if (file_exists(state_dir_path("quiet", opts)))
649 opts->flags &= ~REBASE_NO_QUIET;
650 else
651 opts->flags |= REBASE_NO_QUIET;
653 if (file_exists(state_dir_path("verbose", opts)))
654 opts->flags |= REBASE_VERBOSE;
656 if (file_exists(state_dir_path("signoff", opts))) {
657 opts->signoff = 1;
658 opts->flags |= REBASE_FORCE;
661 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
662 strbuf_reset(&buf);
663 if (!read_oneliner(&buf, state_dir_path("allow_rerere_autoupdate", opts),
664 READ_ONELINER_WARN_MISSING))
665 return -1;
666 if (!strcmp(buf.buf, "--rerere-autoupdate"))
667 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
668 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
669 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
670 else
671 warning(_("ignoring invalid allow_rerere_autoupdate: "
672 "'%s'"), buf.buf);
675 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
676 strbuf_reset(&buf);
677 if (!read_oneliner(&buf, state_dir_path("gpg_sign_opt", opts),
678 READ_ONELINER_WARN_MISSING))
679 return -1;
680 free(opts->gpg_sign_opt);
681 opts->gpg_sign_opt = xstrdup(buf.buf);
684 if (file_exists(state_dir_path("strategy", opts))) {
685 strbuf_reset(&buf);
686 if (!read_oneliner(&buf, state_dir_path("strategy", opts),
687 READ_ONELINER_WARN_MISSING))
688 return -1;
689 free(opts->strategy);
690 opts->strategy = xstrdup(buf.buf);
693 if (file_exists(state_dir_path("strategy_opts", opts))) {
694 strbuf_reset(&buf);
695 if (!read_oneliner(&buf, state_dir_path("strategy_opts", opts),
696 READ_ONELINER_WARN_MISSING))
697 return -1;
698 free(opts->strategy_opts);
699 opts->strategy_opts = xstrdup(buf.buf);
702 strbuf_release(&buf);
704 return 0;
707 static int rebase_write_basic_state(struct rebase_options *opts)
709 write_file(state_dir_path("head-name", opts), "%s",
710 opts->head_name ? opts->head_name : "detached HEAD");
711 write_file(state_dir_path("onto", opts), "%s",
712 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
713 write_file(state_dir_path("orig-head", opts), "%s",
714 oid_to_hex(&opts->orig_head));
715 if (!(opts->flags & REBASE_NO_QUIET))
716 write_file(state_dir_path("quiet", opts), "%s", "");
717 if (opts->flags & REBASE_VERBOSE)
718 write_file(state_dir_path("verbose", opts), "%s", "");
719 if (opts->strategy)
720 write_file(state_dir_path("strategy", opts), "%s",
721 opts->strategy);
722 if (opts->strategy_opts)
723 write_file(state_dir_path("strategy_opts", opts), "%s",
724 opts->strategy_opts);
725 if (opts->allow_rerere_autoupdate > 0)
726 write_file(state_dir_path("allow_rerere_autoupdate", opts),
727 "-%s-rerere-autoupdate",
728 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
729 "" : "-no");
730 if (opts->gpg_sign_opt)
731 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
732 opts->gpg_sign_opt);
733 if (opts->signoff)
734 write_file(state_dir_path("signoff", opts), "--signoff");
736 return 0;
739 static int finish_rebase(struct rebase_options *opts)
741 struct strbuf dir = STRBUF_INIT;
742 int ret = 0;
744 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
745 unlink(git_path_auto_merge(the_repository));
746 apply_autostash(state_dir_path("autostash", opts));
748 * We ignore errors in 'git maintenance run --auto', since the
749 * user should see them.
751 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
752 if (opts->type == REBASE_MERGE) {
753 struct replay_opts replay = REPLAY_OPTS_INIT;
755 replay.action = REPLAY_INTERACTIVE_REBASE;
756 ret = sequencer_remove_state(&replay);
757 } else {
758 strbuf_addstr(&dir, opts->state_dir);
759 if (remove_dir_recursively(&dir, 0))
760 ret = error(_("could not remove '%s'"),
761 opts->state_dir);
762 strbuf_release(&dir);
765 return ret;
768 static void add_var(struct strbuf *buf, const char *name, const char *value)
770 if (!value)
771 strbuf_addf(buf, "unset %s; ", name);
772 else {
773 strbuf_addf(buf, "%s=", name);
774 sq_quote_buf(buf, value);
775 strbuf_addstr(buf, "; ");
779 static int move_to_original_branch(struct rebase_options *opts)
781 struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
782 int ret;
784 if (!opts->head_name)
785 return 0; /* nothing to move back to */
787 if (!opts->onto)
788 BUG("move_to_original_branch without onto");
790 strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
791 opts->head_name, oid_to_hex(&opts->onto->object.oid));
792 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
793 opts->head_name);
794 ret = reset_head(the_repository, NULL, "", opts->head_name,
795 RESET_HEAD_REFS_ONLY,
796 orig_head_reflog.buf, head_reflog.buf,
797 DEFAULT_REFLOG_ACTION);
799 strbuf_release(&orig_head_reflog);
800 strbuf_release(&head_reflog);
801 return ret;
804 static const char *resolvemsg =
805 N_("Resolve all conflicts manually, mark them as resolved with\n"
806 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
807 "You can instead skip this commit: run \"git rebase --skip\".\n"
808 "To abort and get back to the state before \"git rebase\", run "
809 "\"git rebase --abort\".");
811 static int run_am(struct rebase_options *opts)
813 struct child_process am = CHILD_PROCESS_INIT;
814 struct child_process format_patch = CHILD_PROCESS_INIT;
815 struct strbuf revisions = STRBUF_INIT;
816 int status;
817 char *rebased_patches;
819 am.git_cmd = 1;
820 strvec_push(&am.args, "am");
822 if (opts->action && !strcmp("continue", opts->action)) {
823 strvec_push(&am.args, "--resolved");
824 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
825 if (opts->gpg_sign_opt)
826 strvec_push(&am.args, opts->gpg_sign_opt);
827 status = run_command(&am);
828 if (status)
829 return status;
831 return move_to_original_branch(opts);
833 if (opts->action && !strcmp("skip", opts->action)) {
834 strvec_push(&am.args, "--skip");
835 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
836 status = run_command(&am);
837 if (status)
838 return status;
840 return move_to_original_branch(opts);
842 if (opts->action && !strcmp("show-current-patch", opts->action)) {
843 strvec_push(&am.args, "--show-current-patch");
844 return run_command(&am);
847 strbuf_addf(&revisions, "%s...%s",
848 oid_to_hex(opts->root ?
849 /* this is now equivalent to !opts->upstream */
850 &opts->onto->object.oid :
851 &opts->upstream->object.oid),
852 oid_to_hex(&opts->orig_head));
854 rebased_patches = xstrdup(git_path("rebased-patches"));
855 format_patch.out = open(rebased_patches,
856 O_WRONLY | O_CREAT | O_TRUNC, 0666);
857 if (format_patch.out < 0) {
858 status = error_errno(_("could not open '%s' for writing"),
859 rebased_patches);
860 free(rebased_patches);
861 strvec_clear(&am.args);
862 return status;
865 format_patch.git_cmd = 1;
866 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
867 "--full-index", "--cherry-pick", "--right-only",
868 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
869 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
870 "--no-base", NULL);
871 if (opts->git_format_patch_opt.len)
872 strvec_split(&format_patch.args,
873 opts->git_format_patch_opt.buf);
874 strvec_push(&format_patch.args, revisions.buf);
875 if (opts->restrict_revision)
876 strvec_pushf(&format_patch.args, "^%s",
877 oid_to_hex(&opts->restrict_revision->object.oid));
879 status = run_command(&format_patch);
880 if (status) {
881 unlink(rebased_patches);
882 free(rebased_patches);
883 strvec_clear(&am.args);
885 reset_head(the_repository, &opts->orig_head, "checkout",
886 opts->head_name, 0,
887 "HEAD", NULL, DEFAULT_REFLOG_ACTION);
888 error(_("\ngit encountered an error while preparing the "
889 "patches to replay\n"
890 "these revisions:\n"
891 "\n %s\n\n"
892 "As a result, git cannot rebase them."),
893 opts->revisions);
895 strbuf_release(&revisions);
896 return status;
898 strbuf_release(&revisions);
900 am.in = open(rebased_patches, O_RDONLY);
901 if (am.in < 0) {
902 status = error_errno(_("could not open '%s' for reading"),
903 rebased_patches);
904 free(rebased_patches);
905 strvec_clear(&am.args);
906 return status;
909 strvec_pushv(&am.args, opts->git_am_opts.v);
910 strvec_push(&am.args, "--rebasing");
911 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
912 strvec_push(&am.args, "--patch-format=mboxrd");
913 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
914 strvec_push(&am.args, "--rerere-autoupdate");
915 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
916 strvec_push(&am.args, "--no-rerere-autoupdate");
917 if (opts->gpg_sign_opt)
918 strvec_push(&am.args, opts->gpg_sign_opt);
919 status = run_command(&am);
920 unlink(rebased_patches);
921 free(rebased_patches);
923 if (!status) {
924 return move_to_original_branch(opts);
927 if (is_directory(opts->state_dir))
928 rebase_write_basic_state(opts);
930 return status;
933 static int run_specific_rebase(struct rebase_options *opts, enum action action)
935 const char *argv[] = { NULL, NULL };
936 struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
937 int status;
938 const char *backend, *backend_func;
940 if (opts->type == REBASE_MERGE) {
941 /* Run sequencer-based rebase */
942 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
943 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
944 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
945 opts->autosquash = 0;
947 if (opts->gpg_sign_opt) {
948 /* remove the leading "-S" */
949 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
950 free(opts->gpg_sign_opt);
951 opts->gpg_sign_opt = tmp;
954 status = run_sequencer_rebase(opts, action);
955 goto finished_rebase;
958 if (opts->type == REBASE_APPLY) {
959 status = run_am(opts);
960 goto finished_rebase;
963 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
964 add_var(&script_snippet, "state_dir", opts->state_dir);
966 add_var(&script_snippet, "upstream_name", opts->upstream_name);
967 add_var(&script_snippet, "upstream", opts->upstream ?
968 oid_to_hex(&opts->upstream->object.oid) : NULL);
969 add_var(&script_snippet, "head_name",
970 opts->head_name ? opts->head_name : "detached HEAD");
971 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
972 add_var(&script_snippet, "onto", opts->onto ?
973 oid_to_hex(&opts->onto->object.oid) : NULL);
974 add_var(&script_snippet, "onto_name", opts->onto_name);
975 add_var(&script_snippet, "revisions", opts->revisions);
976 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
977 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
978 sq_quote_argv_pretty(&buf, opts->git_am_opts.v);
979 add_var(&script_snippet, "git_am_opt", buf.buf);
980 strbuf_release(&buf);
981 add_var(&script_snippet, "verbose",
982 opts->flags & REBASE_VERBOSE ? "t" : "");
983 add_var(&script_snippet, "diffstat",
984 opts->flags & REBASE_DIFFSTAT ? "t" : "");
985 add_var(&script_snippet, "force_rebase",
986 opts->flags & REBASE_FORCE ? "t" : "");
987 if (opts->switch_to)
988 add_var(&script_snippet, "switch_to", opts->switch_to);
989 add_var(&script_snippet, "action", opts->action ? opts->action : "");
990 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
991 add_var(&script_snippet, "allow_rerere_autoupdate",
992 opts->allow_rerere_autoupdate ?
993 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
994 "--rerere-autoupdate" : "--no-rerere-autoupdate" : "");
995 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
996 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
997 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
998 add_var(&script_snippet, "cmd", opts->cmd);
999 add_var(&script_snippet, "allow_empty_message",
1000 opts->allow_empty_message ? "--allow-empty-message" : "");
1001 add_var(&script_snippet, "rebase_merges",
1002 opts->rebase_merges ? "t" : "");
1003 add_var(&script_snippet, "rebase_cousins",
1004 opts->rebase_cousins ? "t" : "");
1005 add_var(&script_snippet, "strategy", opts->strategy);
1006 add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
1007 add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
1008 add_var(&script_snippet, "squash_onto",
1009 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
1010 add_var(&script_snippet, "git_format_patch_opt",
1011 opts->git_format_patch_opt.buf);
1013 if (is_merge(opts) &&
1014 !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1015 strbuf_addstr(&script_snippet,
1016 "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
1017 opts->autosquash = 0;
1020 switch (opts->type) {
1021 case REBASE_PRESERVE_MERGES:
1022 backend = "git-rebase--preserve-merges";
1023 backend_func = "git_rebase__preserve_merges";
1024 break;
1025 default:
1026 BUG("Unhandled rebase type %d", opts->type);
1027 break;
1030 strbuf_addf(&script_snippet,
1031 ". git-sh-setup && . %s && %s", backend, backend_func);
1032 argv[0] = script_snippet.buf;
1034 status = run_command_v_opt(argv, RUN_USING_SHELL);
1035 finished_rebase:
1036 if (opts->dont_finish_rebase)
1037 ; /* do nothing */
1038 else if (opts->type == REBASE_MERGE)
1039 ; /* merge backend cleans up after itself */
1040 else if (status == 0) {
1041 if (!file_exists(state_dir_path("stopped-sha", opts)))
1042 finish_rebase(opts);
1043 } else if (status == 2) {
1044 struct strbuf dir = STRBUF_INIT;
1046 apply_autostash(state_dir_path("autostash", opts));
1047 strbuf_addstr(&dir, opts->state_dir);
1048 remove_dir_recursively(&dir, 0);
1049 strbuf_release(&dir);
1050 die("Nothing to do");
1053 strbuf_release(&script_snippet);
1055 return status ? -1 : 0;
1058 static int rebase_config(const char *var, const char *value, void *data)
1060 struct rebase_options *opts = data;
1062 if (!strcmp(var, "rebase.stat")) {
1063 if (git_config_bool(var, value))
1064 opts->flags |= REBASE_DIFFSTAT;
1065 else
1066 opts->flags &= ~REBASE_DIFFSTAT;
1067 return 0;
1070 if (!strcmp(var, "rebase.autosquash")) {
1071 opts->autosquash = git_config_bool(var, value);
1072 return 0;
1075 if (!strcmp(var, "commit.gpgsign")) {
1076 free(opts->gpg_sign_opt);
1077 opts->gpg_sign_opt = git_config_bool(var, value) ?
1078 xstrdup("-S") : NULL;
1079 return 0;
1082 if (!strcmp(var, "rebase.autostash")) {
1083 opts->autostash = git_config_bool(var, value);
1084 return 0;
1087 if (!strcmp(var, "rebase.reschedulefailedexec")) {
1088 opts->reschedule_failed_exec = git_config_bool(var, value);
1089 return 0;
1092 if (!strcmp(var, "rebase.forkpoint")) {
1093 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
1094 return 0;
1097 if (!strcmp(var, "rebase.backend")) {
1098 return git_config_string(&opts->default_backend, var, value);
1101 return git_default_config(var, value, data);
1105 * Determines whether the commits in from..to are linear, i.e. contain
1106 * no merge commits. This function *expects* `from` to be an ancestor of
1107 * `to`.
1109 static int is_linear_history(struct commit *from, struct commit *to)
1111 while (to && to != from) {
1112 parse_commit(to);
1113 if (!to->parents)
1114 return 1;
1115 if (to->parents->next)
1116 return 0;
1117 to = to->parents->item;
1119 return 1;
1122 static int can_fast_forward(struct commit *onto, struct commit *upstream,
1123 struct commit *restrict_revision,
1124 struct object_id *head_oid, struct object_id *merge_base)
1126 struct commit *head = lookup_commit(the_repository, head_oid);
1127 struct commit_list *merge_bases = NULL;
1128 int res = 0;
1130 if (!head)
1131 goto done;
1133 merge_bases = get_merge_bases(onto, head);
1134 if (!merge_bases || merge_bases->next) {
1135 oidcpy(merge_base, null_oid());
1136 goto done;
1139 oidcpy(merge_base, &merge_bases->item->object.oid);
1140 if (!oideq(merge_base, &onto->object.oid))
1141 goto done;
1143 if (restrict_revision && !oideq(&restrict_revision->object.oid, merge_base))
1144 goto done;
1146 if (!upstream)
1147 goto done;
1149 free_commit_list(merge_bases);
1150 merge_bases = get_merge_bases(upstream, head);
1151 if (!merge_bases || merge_bases->next)
1152 goto done;
1154 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
1155 goto done;
1157 res = 1;
1159 done:
1160 free_commit_list(merge_bases);
1161 return res && is_linear_history(onto, head);
1164 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
1166 struct rebase_options *opts = opt->value;
1168 BUG_ON_OPT_NEG(unset);
1169 BUG_ON_OPT_ARG(arg);
1171 opts->type = REBASE_APPLY;
1173 return 0;
1176 /* -i followed by -m is still -i */
1177 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
1179 struct rebase_options *opts = opt->value;
1181 BUG_ON_OPT_NEG(unset);
1182 BUG_ON_OPT_ARG(arg);
1184 if (!is_merge(opts))
1185 opts->type = REBASE_MERGE;
1187 return 0;
1190 /* -i followed by -p is still explicitly interactive, but -p alone is not */
1191 static int parse_opt_interactive(const struct option *opt, const char *arg,
1192 int unset)
1194 struct rebase_options *opts = opt->value;
1196 BUG_ON_OPT_NEG(unset);
1197 BUG_ON_OPT_ARG(arg);
1199 opts->type = REBASE_MERGE;
1200 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
1202 return 0;
1205 static enum empty_type parse_empty_value(const char *value)
1207 if (!strcasecmp(value, "drop"))
1208 return EMPTY_DROP;
1209 else if (!strcasecmp(value, "keep"))
1210 return EMPTY_KEEP;
1211 else if (!strcasecmp(value, "ask"))
1212 return EMPTY_ASK;
1214 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
1217 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
1219 struct rebase_options *options = opt->value;
1220 enum empty_type value = parse_empty_value(arg);
1222 BUG_ON_OPT_NEG(unset);
1224 options->empty = value;
1225 return 0;
1228 static void NORETURN error_on_missing_default_upstream(void)
1230 struct branch *current_branch = branch_get(NULL);
1232 printf(_("%s\n"
1233 "Please specify which branch you want to rebase against.\n"
1234 "See git-rebase(1) for details.\n"
1235 "\n"
1236 " git rebase '<branch>'\n"
1237 "\n"),
1238 current_branch ? _("There is no tracking information for "
1239 "the current branch.") :
1240 _("You are not currently on a branch."));
1242 if (current_branch) {
1243 const char *remote = current_branch->remote_name;
1245 if (!remote)
1246 remote = _("<remote>");
1248 printf(_("If you wish to set tracking information for this "
1249 "branch you can do so with:\n"
1250 "\n"
1251 " git branch --set-upstream-to=%s/<branch> %s\n"
1252 "\n"),
1253 remote, current_branch->name);
1255 exit(1);
1258 static void set_reflog_action(struct rebase_options *options)
1260 const char *env;
1261 struct strbuf buf = STRBUF_INIT;
1263 if (!is_merge(options))
1264 return;
1266 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1267 if (env && strcmp("rebase", env))
1268 return; /* only override it if it is "rebase" */
1270 strbuf_addf(&buf, "rebase (%s)", options->action);
1271 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1272 strbuf_release(&buf);
1275 static int check_exec_cmd(const char *cmd)
1277 if (strchr(cmd, '\n'))
1278 return error(_("exec commands cannot contain newlines"));
1280 /* Does the command consist purely of whitespace? */
1281 if (!cmd[strspn(cmd, " \t\r\f\v")])
1282 return error(_("empty exec command"));
1284 return 0;
1287 int cmd_rebase(int argc, const char **argv, const char *prefix)
1289 struct rebase_options options = REBASE_OPTIONS_INIT;
1290 const char *branch_name;
1291 int ret, flags, total_argc, in_progress = 0;
1292 int keep_base = 0;
1293 int ok_to_skip_pre_rebase = 0;
1294 struct strbuf msg = STRBUF_INIT;
1295 struct strbuf revisions = STRBUF_INIT;
1296 struct strbuf buf = STRBUF_INIT;
1297 struct object_id merge_base;
1298 int ignore_whitespace = 0;
1299 enum action action = ACTION_NONE;
1300 const char *gpg_sign = NULL;
1301 struct string_list exec = STRING_LIST_INIT_NODUP;
1302 const char *rebase_merges = NULL;
1303 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1304 struct object_id squash_onto;
1305 char *squash_onto_name = NULL;
1306 int reschedule_failed_exec = -1;
1307 int allow_preemptive_ff = 1;
1308 struct option builtin_rebase_options[] = {
1309 OPT_STRING(0, "onto", &options.onto_name,
1310 N_("revision"),
1311 N_("rebase onto given branch instead of upstream")),
1312 OPT_BOOL(0, "keep-base", &keep_base,
1313 N_("use the merge-base of upstream and branch as the current base")),
1314 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1315 N_("allow pre-rebase hook to run")),
1316 OPT_NEGBIT('q', "quiet", &options.flags,
1317 N_("be quiet. implies --no-stat"),
1318 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1319 OPT_BIT('v', "verbose", &options.flags,
1320 N_("display a diffstat of what changed upstream"),
1321 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1322 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1323 N_("do not show diffstat of what changed upstream"),
1324 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1325 OPT_BOOL(0, "signoff", &options.signoff,
1326 N_("add a Signed-off-by trailer to each commit")),
1327 OPT_BOOL(0, "committer-date-is-author-date",
1328 &options.committer_date_is_author_date,
1329 N_("make committer date match author date")),
1330 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1331 N_("ignore author date and use current date")),
1332 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1333 N_("synonym of --reset-author-date")),
1334 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1335 N_("passed to 'git apply'"), 0),
1336 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1337 N_("ignore changes in whitespace")),
1338 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1339 N_("action"), N_("passed to 'git apply'"), 0),
1340 OPT_BIT('f', "force-rebase", &options.flags,
1341 N_("cherry-pick all commits, even if unchanged"),
1342 REBASE_FORCE),
1343 OPT_BIT(0, "no-ff", &options.flags,
1344 N_("cherry-pick all commits, even if unchanged"),
1345 REBASE_FORCE),
1346 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1347 ACTION_CONTINUE),
1348 OPT_CMDMODE(0, "skip", &action,
1349 N_("skip current patch and continue"), ACTION_SKIP),
1350 OPT_CMDMODE(0, "abort", &action,
1351 N_("abort and check out the original branch"),
1352 ACTION_ABORT),
1353 OPT_CMDMODE(0, "quit", &action,
1354 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1355 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1356 "during an interactive rebase"), ACTION_EDIT_TODO),
1357 OPT_CMDMODE(0, "show-current-patch", &action,
1358 N_("show the patch file being applied or merged"),
1359 ACTION_SHOW_CURRENT_PATCH),
1360 OPT_CALLBACK_F(0, "apply", &options, NULL,
1361 N_("use apply strategies to rebase"),
1362 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1363 parse_opt_am),
1364 OPT_CALLBACK_F('m', "merge", &options, NULL,
1365 N_("use merging strategies to rebase"),
1366 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1367 parse_opt_merge),
1368 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1369 N_("let the user edit the list of commits to rebase"),
1370 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1371 parse_opt_interactive),
1372 OPT_SET_INT_F('p', "preserve-merges", &options.type,
1373 N_("(DEPRECATED) try to recreate merges instead of "
1374 "ignoring them"),
1375 REBASE_PRESERVE_MERGES, PARSE_OPT_HIDDEN),
1376 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1377 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1378 N_("how to handle commits that become empty"),
1379 PARSE_OPT_NONEG, parse_opt_empty),
1380 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1381 N_("keep commits which start empty"),
1382 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1383 parse_opt_keep_empty),
1384 OPT_BOOL(0, "autosquash", &options.autosquash,
1385 N_("move commits that begin with "
1386 "squash!/fixup! under -i")),
1387 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1388 N_("GPG-sign commits"),
1389 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1390 OPT_AUTOSTASH(&options.autostash),
1391 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1392 N_("add exec lines after each commit of the "
1393 "editable list")),
1394 OPT_BOOL_F(0, "allow-empty-message",
1395 &options.allow_empty_message,
1396 N_("allow rebasing commits with empty messages"),
1397 PARSE_OPT_HIDDEN),
1398 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1399 N_("mode"),
1400 N_("try to rebase merges instead of skipping them"),
1401 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1402 OPT_BOOL(0, "fork-point", &options.fork_point,
1403 N_("use 'merge-base --fork-point' to refine upstream")),
1404 OPT_STRING('s', "strategy", &options.strategy,
1405 N_("strategy"), N_("use the given merge strategy")),
1406 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1407 N_("option"),
1408 N_("pass the argument through to the merge "
1409 "strategy")),
1410 OPT_BOOL(0, "root", &options.root,
1411 N_("rebase all reachable commits up to the root(s)")),
1412 OPT_BOOL(0, "reschedule-failed-exec",
1413 &reschedule_failed_exec,
1414 N_("automatically re-schedule any `exec` that fails")),
1415 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1416 N_("apply all changes, even those already present upstream")),
1417 OPT_END(),
1419 int i;
1421 if (argc == 2 && !strcmp(argv[1], "-h"))
1422 usage_with_options(builtin_rebase_usage,
1423 builtin_rebase_options);
1425 prepare_repo_settings(the_repository);
1426 the_repository->settings.command_requires_full_index = 0;
1428 options.allow_empty_message = 1;
1429 git_config(rebase_config, &options);
1430 /* options.gpg_sign_opt will be either "-S" or NULL */
1431 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1432 FREE_AND_NULL(options.gpg_sign_opt);
1434 strbuf_reset(&buf);
1435 strbuf_addf(&buf, "%s/applying", apply_dir());
1436 if(file_exists(buf.buf))
1437 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1439 if (is_directory(apply_dir())) {
1440 options.type = REBASE_APPLY;
1441 options.state_dir = apply_dir();
1442 } else if (is_directory(merge_dir())) {
1443 strbuf_reset(&buf);
1444 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1445 if (is_directory(buf.buf)) {
1446 options.type = REBASE_PRESERVE_MERGES;
1447 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1448 } else {
1449 strbuf_reset(&buf);
1450 strbuf_addf(&buf, "%s/interactive", merge_dir());
1451 if(file_exists(buf.buf)) {
1452 options.type = REBASE_MERGE;
1453 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1454 } else
1455 options.type = REBASE_MERGE;
1457 options.state_dir = merge_dir();
1460 if (options.type != REBASE_UNSPECIFIED)
1461 in_progress = 1;
1463 total_argc = argc;
1464 argc = parse_options(argc, argv, prefix,
1465 builtin_rebase_options,
1466 builtin_rebase_usage, 0);
1468 if (action != ACTION_NONE && total_argc != 2) {
1469 usage_with_options(builtin_rebase_usage,
1470 builtin_rebase_options);
1473 if (argc > 2)
1474 usage_with_options(builtin_rebase_usage,
1475 builtin_rebase_options);
1477 if (options.type == REBASE_PRESERVE_MERGES)
1478 warning(_("git rebase --preserve-merges is deprecated. "
1479 "Use --rebase-merges instead."));
1481 if (keep_base) {
1482 if (options.onto_name)
1483 die(_("cannot combine '--keep-base' with '--onto'"));
1484 if (options.root)
1485 die(_("cannot combine '--keep-base' with '--root'"));
1488 if (options.root && options.fork_point > 0)
1489 die(_("cannot combine '--root' with '--fork-point'"));
1491 if (action != ACTION_NONE && !in_progress)
1492 die(_("No rebase in progress?"));
1493 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1495 if (action == ACTION_EDIT_TODO && !is_merge(&options))
1496 die(_("The --edit-todo action can only be used during "
1497 "interactive rebase."));
1499 if (trace2_is_enabled()) {
1500 if (is_merge(&options))
1501 trace2_cmd_mode("interactive");
1502 else if (exec.nr)
1503 trace2_cmd_mode("interactive-exec");
1504 else
1505 trace2_cmd_mode(action_names[action]);
1508 switch (action) {
1509 case ACTION_CONTINUE: {
1510 struct object_id head;
1511 struct lock_file lock_file = LOCK_INIT;
1512 int fd;
1514 options.action = "continue";
1515 set_reflog_action(&options);
1517 /* Sanity check */
1518 if (get_oid("HEAD", &head))
1519 die(_("Cannot read HEAD"));
1521 fd = hold_locked_index(&lock_file, 0);
1522 if (repo_read_index(the_repository) < 0)
1523 die(_("could not read index"));
1524 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1525 NULL);
1526 if (0 <= fd)
1527 repo_update_index_if_able(the_repository, &lock_file);
1528 rollback_lock_file(&lock_file);
1530 if (has_unstaged_changes(the_repository, 1)) {
1531 puts(_("You must edit all merge conflicts and then\n"
1532 "mark them as resolved using git add"));
1533 exit(1);
1535 if (read_basic_state(&options))
1536 exit(1);
1537 goto run_rebase;
1539 case ACTION_SKIP: {
1540 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1542 options.action = "skip";
1543 set_reflog_action(&options);
1545 rerere_clear(the_repository, &merge_rr);
1546 string_list_clear(&merge_rr, 1);
1548 if (reset_head(the_repository, NULL, "reset", NULL, RESET_HEAD_HARD,
1549 NULL, NULL, DEFAULT_REFLOG_ACTION) < 0)
1550 die(_("could not discard worktree changes"));
1551 remove_branch_state(the_repository, 0);
1552 if (read_basic_state(&options))
1553 exit(1);
1554 goto run_rebase;
1556 case ACTION_ABORT: {
1557 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1558 options.action = "abort";
1559 set_reflog_action(&options);
1561 rerere_clear(the_repository, &merge_rr);
1562 string_list_clear(&merge_rr, 1);
1564 if (read_basic_state(&options))
1565 exit(1);
1566 if (reset_head(the_repository, &options.orig_head, "reset",
1567 options.head_name, RESET_HEAD_HARD,
1568 NULL, NULL, DEFAULT_REFLOG_ACTION) < 0)
1569 die(_("could not move back to %s"),
1570 oid_to_hex(&options.orig_head));
1571 remove_branch_state(the_repository, 0);
1572 ret = finish_rebase(&options);
1573 goto cleanup;
1575 case ACTION_QUIT: {
1576 save_autostash(state_dir_path("autostash", &options));
1577 if (options.type == REBASE_MERGE) {
1578 struct replay_opts replay = REPLAY_OPTS_INIT;
1580 replay.action = REPLAY_INTERACTIVE_REBASE;
1581 ret = sequencer_remove_state(&replay);
1582 } else {
1583 strbuf_reset(&buf);
1584 strbuf_addstr(&buf, options.state_dir);
1585 ret = remove_dir_recursively(&buf, 0);
1586 if (ret)
1587 error(_("could not remove '%s'"),
1588 options.state_dir);
1590 goto cleanup;
1592 case ACTION_EDIT_TODO:
1593 options.action = "edit-todo";
1594 options.dont_finish_rebase = 1;
1595 goto run_rebase;
1596 case ACTION_SHOW_CURRENT_PATCH:
1597 options.action = "show-current-patch";
1598 options.dont_finish_rebase = 1;
1599 goto run_rebase;
1600 case ACTION_NONE:
1601 break;
1602 default:
1603 BUG("action: %d", action);
1606 /* Make sure no rebase is in progress */
1607 if (in_progress) {
1608 const char *last_slash = strrchr(options.state_dir, '/');
1609 const char *state_dir_base =
1610 last_slash ? last_slash + 1 : options.state_dir;
1611 const char *cmd_live_rebase =
1612 "git rebase (--continue | --abort | --skip)";
1613 strbuf_reset(&buf);
1614 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1615 die(_("It seems that there is already a %s directory, and\n"
1616 "I wonder if you are in the middle of another rebase. "
1617 "If that is the\n"
1618 "case, please try\n\t%s\n"
1619 "If that is not the case, please\n\t%s\n"
1620 "and run me again. I am stopping in case you still "
1621 "have something\n"
1622 "valuable there.\n"),
1623 state_dir_base, cmd_live_rebase, buf.buf);
1626 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1627 (action != ACTION_NONE) ||
1628 (exec.nr > 0) ||
1629 options.autosquash) {
1630 allow_preemptive_ff = 0;
1632 if (options.committer_date_is_author_date || options.ignore_date)
1633 options.flags |= REBASE_FORCE;
1635 for (i = 0; i < options.git_am_opts.nr; i++) {
1636 const char *option = options.git_am_opts.v[i], *p;
1637 if (!strcmp(option, "--whitespace=fix") ||
1638 !strcmp(option, "--whitespace=strip"))
1639 allow_preemptive_ff = 0;
1640 else if (skip_prefix(option, "-C", &p)) {
1641 while (*p)
1642 if (!isdigit(*(p++)))
1643 die(_("switch `C' expects a "
1644 "numerical value"));
1645 } else if (skip_prefix(option, "--whitespace=", &p)) {
1646 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1647 strcmp(p, "error") && strcmp(p, "error-all"))
1648 die("Invalid whitespace option: '%s'", p);
1652 for (i = 0; i < exec.nr; i++)
1653 if (check_exec_cmd(exec.items[i].string))
1654 exit(1);
1656 if (!(options.flags & REBASE_NO_QUIET))
1657 strvec_push(&options.git_am_opts, "-q");
1659 if (options.empty != EMPTY_UNSPECIFIED)
1660 imply_merge(&options, "--empty");
1662 if (options.reapply_cherry_picks)
1663 imply_merge(&options, "--reapply-cherry-picks");
1665 if (gpg_sign)
1666 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1668 if (exec.nr) {
1669 int i;
1671 imply_merge(&options, "--exec");
1673 strbuf_reset(&buf);
1674 for (i = 0; i < exec.nr; i++)
1675 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1676 options.cmd = xstrdup(buf.buf);
1679 if (rebase_merges) {
1680 if (!*rebase_merges)
1681 ; /* default mode; do nothing */
1682 else if (!strcmp("rebase-cousins", rebase_merges))
1683 options.rebase_cousins = 1;
1684 else if (strcmp("no-rebase-cousins", rebase_merges))
1685 die(_("Unknown mode: %s"), rebase_merges);
1686 options.rebase_merges = 1;
1687 imply_merge(&options, "--rebase-merges");
1690 if (options.type == REBASE_APPLY) {
1691 if (ignore_whitespace)
1692 strvec_push(&options.git_am_opts,
1693 "--ignore-whitespace");
1694 if (options.committer_date_is_author_date)
1695 strvec_push(&options.git_am_opts,
1696 "--committer-date-is-author-date");
1697 if (options.ignore_date)
1698 strvec_push(&options.git_am_opts, "--ignore-date");
1699 } else {
1700 /* REBASE_MERGE and PRESERVE_MERGES */
1701 if (ignore_whitespace) {
1702 string_list_append(&strategy_options,
1703 "ignore-space-change");
1707 if (strategy_options.nr) {
1708 int i;
1710 if (!options.strategy)
1711 options.strategy = "ort";
1713 strbuf_reset(&buf);
1714 for (i = 0; i < strategy_options.nr; i++)
1715 strbuf_addf(&buf, " --%s",
1716 strategy_options.items[i].string);
1717 options.strategy_opts = xstrdup(buf.buf);
1720 if (options.strategy) {
1721 options.strategy = xstrdup(options.strategy);
1722 switch (options.type) {
1723 case REBASE_APPLY:
1724 die(_("--strategy requires --merge or --interactive"));
1725 case REBASE_MERGE:
1726 case REBASE_PRESERVE_MERGES:
1727 /* compatible */
1728 break;
1729 case REBASE_UNSPECIFIED:
1730 options.type = REBASE_MERGE;
1731 break;
1732 default:
1733 BUG("unhandled rebase type (%d)", options.type);
1737 if (options.type == REBASE_MERGE)
1738 imply_merge(&options, "--merge");
1740 if (options.root && !options.onto_name)
1741 imply_merge(&options, "--root without --onto");
1743 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1744 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1746 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1747 /* all am options except -q are compatible only with --apply */
1748 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1749 if (strcmp(options.git_am_opts.v[i], "-q"))
1750 break;
1752 if (i >= 0) {
1753 if (is_merge(&options))
1754 die(_("cannot combine apply options with "
1755 "merge options"));
1756 else
1757 options.type = REBASE_APPLY;
1761 if (options.type == REBASE_UNSPECIFIED) {
1762 if (!strcmp(options.default_backend, "merge"))
1763 imply_merge(&options, "--merge");
1764 else if (!strcmp(options.default_backend, "apply"))
1765 options.type = REBASE_APPLY;
1766 else
1767 die(_("Unknown rebase backend: %s"),
1768 options.default_backend);
1771 if (options.type == REBASE_MERGE &&
1772 !options.strategy &&
1773 getenv("GIT_TEST_MERGE_ALGORITHM"))
1774 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1776 switch (options.type) {
1777 case REBASE_MERGE:
1778 case REBASE_PRESERVE_MERGES:
1779 options.state_dir = merge_dir();
1780 break;
1781 case REBASE_APPLY:
1782 options.state_dir = apply_dir();
1783 break;
1784 default:
1785 BUG("options.type was just set above; should be unreachable.");
1788 if (options.empty == EMPTY_UNSPECIFIED) {
1789 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1790 options.empty = EMPTY_ASK;
1791 else if (exec.nr > 0)
1792 options.empty = EMPTY_KEEP;
1793 else
1794 options.empty = EMPTY_DROP;
1796 if (reschedule_failed_exec > 0 && !is_merge(&options))
1797 die(_("--reschedule-failed-exec requires "
1798 "--exec or --interactive"));
1799 if (reschedule_failed_exec >= 0)
1800 options.reschedule_failed_exec = reschedule_failed_exec;
1802 if (options.signoff) {
1803 if (options.type == REBASE_PRESERVE_MERGES)
1804 die("cannot combine '--signoff' with "
1805 "'--preserve-merges'");
1806 strvec_push(&options.git_am_opts, "--signoff");
1807 options.flags |= REBASE_FORCE;
1810 if (options.type == REBASE_PRESERVE_MERGES) {
1812 * Note: incompatibility with --signoff handled in signoff block above
1813 * Note: incompatibility with --interactive is just a strong warning;
1814 * git-rebase.txt caveats with "unless you know what you are doing"
1816 if (options.rebase_merges)
1817 die(_("cannot combine '--preserve-merges' with "
1818 "'--rebase-merges'"));
1820 if (options.reschedule_failed_exec)
1821 die(_("error: cannot combine '--preserve-merges' with "
1822 "'--reschedule-failed-exec'"));
1825 if (!options.root) {
1826 if (argc < 1) {
1827 struct branch *branch;
1829 branch = branch_get(NULL);
1830 options.upstream_name = branch_get_upstream(branch,
1831 NULL);
1832 if (!options.upstream_name)
1833 error_on_missing_default_upstream();
1834 if (options.fork_point < 0)
1835 options.fork_point = 1;
1836 } else {
1837 options.upstream_name = argv[0];
1838 argc--;
1839 argv++;
1840 if (!strcmp(options.upstream_name, "-"))
1841 options.upstream_name = "@{-1}";
1843 options.upstream =
1844 lookup_commit_reference_by_name(options.upstream_name);
1845 if (!options.upstream)
1846 die(_("invalid upstream '%s'"), options.upstream_name);
1847 options.upstream_arg = options.upstream_name;
1848 } else {
1849 if (!options.onto_name) {
1850 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1851 &squash_onto, NULL, NULL) < 0)
1852 die(_("Could not create new root commit"));
1853 options.squash_onto = &squash_onto;
1854 options.onto_name = squash_onto_name =
1855 xstrdup(oid_to_hex(&squash_onto));
1856 } else
1857 options.root_with_onto = 1;
1859 options.upstream_name = NULL;
1860 options.upstream = NULL;
1861 if (argc > 1)
1862 usage_with_options(builtin_rebase_usage,
1863 builtin_rebase_options);
1864 options.upstream_arg = "--root";
1867 /* Make sure the branch to rebase onto is valid. */
1868 if (keep_base) {
1869 strbuf_reset(&buf);
1870 strbuf_addstr(&buf, options.upstream_name);
1871 strbuf_addstr(&buf, "...");
1872 options.onto_name = xstrdup(buf.buf);
1873 } else if (!options.onto_name)
1874 options.onto_name = options.upstream_name;
1875 if (strstr(options.onto_name, "...")) {
1876 if (get_oid_mb(options.onto_name, &merge_base) < 0) {
1877 if (keep_base)
1878 die(_("'%s': need exactly one merge base with branch"),
1879 options.upstream_name);
1880 else
1881 die(_("'%s': need exactly one merge base"),
1882 options.onto_name);
1884 options.onto = lookup_commit_or_die(&merge_base,
1885 options.onto_name);
1886 } else {
1887 options.onto =
1888 lookup_commit_reference_by_name(options.onto_name);
1889 if (!options.onto)
1890 die(_("Does not point to a valid commit '%s'"),
1891 options.onto_name);
1895 * If the branch to rebase is given, that is the branch we will rebase
1896 * branch_name -- branch/commit being rebased, or
1897 * HEAD (already detached)
1898 * orig_head -- commit object name of tip of the branch before rebasing
1899 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1901 if (argc == 1) {
1902 /* Is it "rebase other branchname" or "rebase other commit"? */
1903 branch_name = argv[0];
1904 options.switch_to = argv[0];
1906 /* Is it a local branch? */
1907 strbuf_reset(&buf);
1908 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1909 if (!read_ref(buf.buf, &options.orig_head)) {
1910 die_if_checked_out(buf.buf, 1);
1911 options.head_name = xstrdup(buf.buf);
1912 /* If not is it a valid ref (branch or commit)? */
1913 } else {
1914 struct commit *commit =
1915 lookup_commit_reference_by_name(branch_name);
1916 if (!commit)
1917 die(_("no such branch/commit '%s'"),
1918 branch_name);
1919 oidcpy(&options.orig_head, &commit->object.oid);
1920 options.head_name = NULL;
1922 } else if (argc == 0) {
1923 /* Do not need to switch branches, we are already on it. */
1924 options.head_name =
1925 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1926 &flags));
1927 if (!options.head_name)
1928 die(_("No such ref: %s"), "HEAD");
1929 if (flags & REF_ISSYMREF) {
1930 if (!skip_prefix(options.head_name,
1931 "refs/heads/", &branch_name))
1932 branch_name = options.head_name;
1934 } else {
1935 FREE_AND_NULL(options.head_name);
1936 branch_name = "HEAD";
1938 if (get_oid("HEAD", &options.orig_head))
1939 die(_("Could not resolve HEAD to a revision"));
1940 } else
1941 BUG("unexpected number of arguments left to parse");
1943 if (options.fork_point > 0) {
1944 struct commit *head =
1945 lookup_commit_reference(the_repository,
1946 &options.orig_head);
1947 options.restrict_revision =
1948 get_fork_point(options.upstream_name, head);
1951 if (repo_read_index(the_repository) < 0)
1952 die(_("could not read index"));
1954 if (options.autostash) {
1955 create_autostash(the_repository, state_dir_path("autostash", &options),
1956 DEFAULT_REFLOG_ACTION);
1959 if (require_clean_work_tree(the_repository, "rebase",
1960 _("Please commit or stash them."), 1, 1)) {
1961 ret = -1;
1962 goto cleanup;
1966 * Now we are rebasing commits upstream..orig_head (or with --root,
1967 * everything leading up to orig_head) on top of onto.
1971 * Check if we are already based on onto with linear history,
1972 * in which case we could fast-forward without replacing the commits
1973 * with new commits recreated by replaying their changes.
1975 * Note that can_fast_forward() initializes merge_base, so we have to
1976 * call it before checking allow_preemptive_ff.
1978 if (can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1979 &options.orig_head, &merge_base) &&
1980 allow_preemptive_ff) {
1981 int flag;
1983 if (!(options.flags & REBASE_FORCE)) {
1984 /* Lazily switch to the target branch if needed... */
1985 if (options.switch_to) {
1986 strbuf_reset(&buf);
1987 strbuf_addf(&buf, "%s: checkout %s",
1988 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
1989 options.switch_to);
1990 if (reset_head(the_repository,
1991 &options.orig_head, "checkout",
1992 options.head_name,
1993 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
1994 NULL, buf.buf,
1995 DEFAULT_REFLOG_ACTION) < 0) {
1996 ret = error(_("could not switch to "
1997 "%s"),
1998 options.switch_to);
1999 goto cleanup;
2003 if (!(options.flags & REBASE_NO_QUIET))
2004 ; /* be quiet */
2005 else if (!strcmp(branch_name, "HEAD") &&
2006 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2007 puts(_("HEAD is up to date."));
2008 else
2009 printf(_("Current branch %s is up to date.\n"),
2010 branch_name);
2011 ret = finish_rebase(&options);
2012 goto cleanup;
2013 } else if (!(options.flags & REBASE_NO_QUIET))
2014 ; /* be quiet */
2015 else if (!strcmp(branch_name, "HEAD") &&
2016 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2017 puts(_("HEAD is up to date, rebase forced."));
2018 else
2019 printf(_("Current branch %s is up to date, rebase "
2020 "forced.\n"), branch_name);
2023 /* If a hook exists, give it a chance to interrupt*/
2024 if (!ok_to_skip_pre_rebase &&
2025 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
2026 argc ? argv[0] : NULL, NULL))
2027 die(_("The pre-rebase hook refused to rebase."));
2029 if (options.flags & REBASE_DIFFSTAT) {
2030 struct diff_options opts;
2032 if (options.flags & REBASE_VERBOSE) {
2033 if (is_null_oid(&merge_base))
2034 printf(_("Changes to %s:\n"),
2035 oid_to_hex(&options.onto->object.oid));
2036 else
2037 printf(_("Changes from %s to %s:\n"),
2038 oid_to_hex(&merge_base),
2039 oid_to_hex(&options.onto->object.oid));
2042 /* We want color (if set), but no pager */
2043 diff_setup(&opts);
2044 opts.stat_width = -1; /* use full terminal width */
2045 opts.stat_graph_width = -1; /* respect statGraphWidth config */
2046 opts.output_format |=
2047 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
2048 opts.detect_rename = DIFF_DETECT_RENAME;
2049 diff_setup_done(&opts);
2050 diff_tree_oid(is_null_oid(&merge_base) ?
2051 the_hash_algo->empty_tree : &merge_base,
2052 &options.onto->object.oid, "", &opts);
2053 diffcore_std(&opts);
2054 diff_flush(&opts);
2057 if (is_merge(&options))
2058 goto run_rebase;
2060 /* Detach HEAD and reset the tree */
2061 if (options.flags & REBASE_NO_QUIET)
2062 printf(_("First, rewinding head to replay your work on top of "
2063 "it...\n"));
2065 strbuf_addf(&msg, "%s: checkout %s",
2066 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
2067 if (reset_head(the_repository, &options.onto->object.oid, "checkout", NULL,
2068 RESET_HEAD_DETACH | RESET_ORIG_HEAD |
2069 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2070 NULL, msg.buf, DEFAULT_REFLOG_ACTION))
2071 die(_("Could not detach HEAD"));
2072 strbuf_release(&msg);
2075 * If the onto is a proper descendant of the tip of the branch, then
2076 * we just fast-forwarded.
2078 strbuf_reset(&msg);
2079 if (oideq(&merge_base, &options.orig_head)) {
2080 printf(_("Fast-forwarded %s to %s.\n"),
2081 branch_name, options.onto_name);
2082 strbuf_addf(&msg, "rebase finished: %s onto %s",
2083 options.head_name ? options.head_name : "detached HEAD",
2084 oid_to_hex(&options.onto->object.oid));
2085 reset_head(the_repository, NULL, "Fast-forwarded", options.head_name,
2086 RESET_HEAD_REFS_ONLY, "HEAD", msg.buf,
2087 DEFAULT_REFLOG_ACTION);
2088 strbuf_release(&msg);
2089 ret = finish_rebase(&options);
2090 goto cleanup;
2093 strbuf_addf(&revisions, "%s..%s",
2094 options.root ? oid_to_hex(&options.onto->object.oid) :
2095 (options.restrict_revision ?
2096 oid_to_hex(&options.restrict_revision->object.oid) :
2097 oid_to_hex(&options.upstream->object.oid)),
2098 oid_to_hex(&options.orig_head));
2100 options.revisions = revisions.buf;
2102 run_rebase:
2103 ret = run_specific_rebase(&options, action);
2105 cleanup:
2106 strbuf_release(&buf);
2107 strbuf_release(&revisions);
2108 free(options.head_name);
2109 free(options.gpg_sign_opt);
2110 free(options.cmd);
2111 free(options.strategy);
2112 strbuf_release(&options.git_format_patch_opt);
2113 free(squash_onto_name);
2114 return !!ret;