Merge branch 'en/rebase-no-keep-empty'
[git.git] / builtin / rebase.c
blobb62b450f8c865ed5b73bf33c149c7e612cb6e2c3
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 "argv-array.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"
31 static char const * const builtin_rebase_usage[] = {
32 N_("git rebase [-i] [options] [--exec <cmd>] "
33 "[--onto <newbase> | --keep-base] [<upstream> [<branch>]]"),
34 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
35 "--root [<branch>]"),
36 N_("git rebase --continue | --abort | --skip | --edit-todo"),
37 NULL
40 static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
41 static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
42 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
43 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
45 enum rebase_type {
46 REBASE_UNSPECIFIED = -1,
47 REBASE_APPLY,
48 REBASE_MERGE,
49 REBASE_PRESERVE_MERGES
52 enum empty_type {
53 EMPTY_UNSPECIFIED = -1,
54 EMPTY_DROP,
55 EMPTY_KEEP,
56 EMPTY_ASK
59 struct rebase_options {
60 enum rebase_type type;
61 enum empty_type empty;
62 const char *default_backend;
63 const char *state_dir;
64 struct commit *upstream;
65 const char *upstream_name;
66 const char *upstream_arg;
67 char *head_name;
68 struct object_id orig_head;
69 struct commit *onto;
70 const char *onto_name;
71 const char *revisions;
72 const char *switch_to;
73 int root, root_with_onto;
74 struct object_id *squash_onto;
75 struct commit *restrict_revision;
76 int dont_finish_rebase;
77 enum {
78 REBASE_NO_QUIET = 1<<0,
79 REBASE_VERBOSE = 1<<1,
80 REBASE_DIFFSTAT = 1<<2,
81 REBASE_FORCE = 1<<3,
82 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
83 } flags;
84 struct argv_array git_am_opts;
85 const char *action;
86 int signoff;
87 int allow_rerere_autoupdate;
88 int keep_empty;
89 int autosquash;
90 char *gpg_sign_opt;
91 int autostash;
92 char *cmd;
93 int allow_empty_message;
94 int rebase_merges, rebase_cousins;
95 char *strategy, *strategy_opts;
96 struct strbuf git_format_patch_opt;
97 int reschedule_failed_exec;
98 int use_legacy_rebase;
101 #define REBASE_OPTIONS_INIT { \
102 .type = REBASE_UNSPECIFIED, \
103 .empty = EMPTY_UNSPECIFIED, \
104 .keep_empty = 1, \
105 .default_backend = "merge", \
106 .flags = REBASE_NO_QUIET, \
107 .git_am_opts = ARGV_ARRAY_INIT, \
108 .git_format_patch_opt = STRBUF_INIT \
111 static struct replay_opts get_replay_opts(const struct rebase_options *opts)
113 struct replay_opts replay = REPLAY_OPTS_INIT;
115 replay.action = REPLAY_INTERACTIVE_REBASE;
116 sequencer_init_config(&replay);
118 replay.signoff = opts->signoff;
119 replay.allow_ff = !(opts->flags & REBASE_FORCE);
120 if (opts->allow_rerere_autoupdate)
121 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
122 replay.allow_empty = 1;
123 replay.allow_empty_message = opts->allow_empty_message;
124 replay.drop_redundant_commits = (opts->empty == EMPTY_DROP);
125 replay.keep_redundant_commits = (opts->empty == EMPTY_KEEP);
126 replay.quiet = !(opts->flags & REBASE_NO_QUIET);
127 replay.verbose = opts->flags & REBASE_VERBOSE;
128 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
129 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
130 replay.strategy = opts->strategy;
131 if (opts->strategy_opts)
132 parse_strategy_opts(&replay, opts->strategy_opts);
134 if (opts->squash_onto) {
135 oidcpy(&replay.squash_onto, opts->squash_onto);
136 replay.have_squash_onto = 1;
139 return replay;
142 enum action {
143 ACTION_NONE = 0,
144 ACTION_CONTINUE,
145 ACTION_SKIP,
146 ACTION_ABORT,
147 ACTION_QUIT,
148 ACTION_EDIT_TODO,
149 ACTION_SHOW_CURRENT_PATCH,
150 ACTION_SHORTEN_OIDS,
151 ACTION_EXPAND_OIDS,
152 ACTION_CHECK_TODO_LIST,
153 ACTION_REARRANGE_SQUASH,
154 ACTION_ADD_EXEC
157 static const char *action_names[] = { "undefined",
158 "continue",
159 "skip",
160 "abort",
161 "quit",
162 "edit_todo",
163 "show_current_patch" };
165 static int add_exec_commands(struct string_list *commands)
167 const char *todo_file = rebase_path_todo();
168 struct todo_list todo_list = TODO_LIST_INIT;
169 int res;
171 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
172 return error_errno(_("could not read '%s'."), todo_file);
174 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
175 &todo_list)) {
176 todo_list_release(&todo_list);
177 return error(_("unusable todo list: '%s'"), todo_file);
180 todo_list_add_exec_commands(&todo_list, commands);
181 res = todo_list_write_to_file(the_repository, &todo_list,
182 todo_file, NULL, NULL, -1, 0);
183 todo_list_release(&todo_list);
185 if (res)
186 return error_errno(_("could not write '%s'."), todo_file);
187 return 0;
190 static int rearrange_squash_in_todo_file(void)
192 const char *todo_file = rebase_path_todo();
193 struct todo_list todo_list = TODO_LIST_INIT;
194 int res = 0;
196 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
197 return error_errno(_("could not read '%s'."), todo_file);
198 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
199 &todo_list)) {
200 todo_list_release(&todo_list);
201 return error(_("unusable todo list: '%s'"), todo_file);
204 res = todo_list_rearrange_squash(&todo_list);
205 if (!res)
206 res = todo_list_write_to_file(the_repository, &todo_list,
207 todo_file, NULL, NULL, -1, 0);
209 todo_list_release(&todo_list);
211 if (res)
212 return error_errno(_("could not write '%s'."), todo_file);
213 return 0;
216 static int transform_todo_file(unsigned flags)
218 const char *todo_file = rebase_path_todo();
219 struct todo_list todo_list = TODO_LIST_INIT;
220 int res;
222 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
223 return error_errno(_("could not read '%s'."), todo_file);
225 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
226 &todo_list)) {
227 todo_list_release(&todo_list);
228 return error(_("unusable todo list: '%s'"), todo_file);
231 res = todo_list_write_to_file(the_repository, &todo_list, todo_file,
232 NULL, NULL, -1, flags);
233 todo_list_release(&todo_list);
235 if (res)
236 return error_errno(_("could not write '%s'."), todo_file);
237 return 0;
240 static int edit_todo_file(unsigned flags)
242 const char *todo_file = rebase_path_todo();
243 struct todo_list todo_list = TODO_LIST_INIT,
244 new_todo = TODO_LIST_INIT;
245 int res = 0;
247 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
248 return error_errno(_("could not read '%s'."), todo_file);
250 strbuf_stripspace(&todo_list.buf, 1);
251 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
252 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
253 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
254 res = error_errno(_("could not write '%s'"), todo_file);
256 todo_list_release(&todo_list);
257 todo_list_release(&new_todo);
259 return res;
262 static int get_revision_ranges(struct commit *upstream, struct commit *onto,
263 struct object_id *orig_head, const char **head_hash,
264 char **revisions, char **shortrevisions)
266 struct commit *base_rev = upstream ? upstream : onto;
267 const char *shorthead;
269 *head_hash = find_unique_abbrev(orig_head, GIT_MAX_HEXSZ);
270 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
271 *head_hash);
273 shorthead = find_unique_abbrev(orig_head, DEFAULT_ABBREV);
275 if (upstream) {
276 const char *shortrev;
278 shortrev = find_unique_abbrev(&base_rev->object.oid,
279 DEFAULT_ABBREV);
281 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
282 } else
283 *shortrevisions = xstrdup(shorthead);
285 return 0;
288 static int init_basic_state(struct replay_opts *opts, const char *head_name,
289 struct commit *onto, const char *orig_head)
291 FILE *interactive;
293 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
294 return error_errno(_("could not create temporary %s"), merge_dir());
296 delete_reflog("REBASE_HEAD");
298 interactive = fopen(path_interactive(), "w");
299 if (!interactive)
300 return error_errno(_("could not mark as interactive"));
301 fclose(interactive);
303 return write_basic_state(opts, head_name, onto, orig_head);
306 static void split_exec_commands(const char *cmd, struct string_list *commands)
308 if (cmd && *cmd) {
309 string_list_split(commands, cmd, '\n', -1);
311 /* rebase.c adds a new line to cmd after every command,
312 * so here the last command is always empty */
313 string_list_remove_empty_items(commands, 0);
317 static int do_interactive_rebase(struct rebase_options *opts, unsigned flags)
319 int ret;
320 const char *head_hash = NULL;
321 char *revisions = NULL, *shortrevisions = NULL;
322 struct argv_array make_script_args = ARGV_ARRAY_INIT;
323 struct todo_list todo_list = TODO_LIST_INIT;
324 struct replay_opts replay = get_replay_opts(opts);
325 struct string_list commands = STRING_LIST_INIT_DUP;
327 if (get_revision_ranges(opts->upstream, opts->onto, &opts->orig_head,
328 &head_hash, &revisions, &shortrevisions))
329 return -1;
331 if (init_basic_state(&replay,
332 opts->head_name ? opts->head_name : "detached HEAD",
333 opts->onto, head_hash)) {
334 free(revisions);
335 free(shortrevisions);
337 return -1;
340 if (!opts->upstream && opts->squash_onto)
341 write_file(path_squash_onto(), "%s\n",
342 oid_to_hex(opts->squash_onto));
344 argv_array_pushl(&make_script_args, "", revisions, NULL);
345 if (opts->restrict_revision)
346 argv_array_pushf(&make_script_args, "^%s",
347 oid_to_hex(&opts->restrict_revision->object.oid));
349 ret = sequencer_make_script(the_repository, &todo_list.buf,
350 make_script_args.argc, make_script_args.argv,
351 flags);
353 if (ret)
354 error(_("could not generate todo list"));
355 else {
356 discard_cache();
357 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
358 &todo_list))
359 BUG("unusable todo list");
361 split_exec_commands(opts->cmd, &commands);
362 ret = complete_action(the_repository, &replay, flags,
363 shortrevisions, opts->onto_name, opts->onto, head_hash,
364 &commands, opts->autosquash, &todo_list);
367 string_list_clear(&commands, 0);
368 free(revisions);
369 free(shortrevisions);
370 todo_list_release(&todo_list);
371 argv_array_clear(&make_script_args);
373 return ret;
376 static int run_sequencer_rebase(struct rebase_options *opts,
377 enum action command)
379 unsigned flags = 0;
380 int abbreviate_commands = 0, ret = 0;
382 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
384 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
385 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
386 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
387 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
388 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
389 flags |= command == ACTION_SHORTEN_OIDS ? TODO_LIST_SHORTEN_IDS : 0;
391 switch (command) {
392 case ACTION_NONE: {
393 if (!opts->onto && !opts->upstream)
394 die(_("a base commit must be provided with --upstream or --onto"));
396 ret = do_interactive_rebase(opts, flags);
397 break;
399 case ACTION_SKIP: {
400 struct string_list merge_rr = STRING_LIST_INIT_DUP;
402 rerere_clear(the_repository, &merge_rr);
404 /* fallthrough */
405 case ACTION_CONTINUE: {
406 struct replay_opts replay_opts = get_replay_opts(opts);
408 ret = sequencer_continue(the_repository, &replay_opts);
409 break;
411 case ACTION_EDIT_TODO:
412 ret = edit_todo_file(flags);
413 break;
414 case ACTION_SHOW_CURRENT_PATCH: {
415 struct child_process cmd = CHILD_PROCESS_INIT;
417 cmd.git_cmd = 1;
418 argv_array_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
419 ret = run_command(&cmd);
421 break;
423 case ACTION_SHORTEN_OIDS:
424 case ACTION_EXPAND_OIDS:
425 ret = transform_todo_file(flags);
426 break;
427 case ACTION_CHECK_TODO_LIST:
428 ret = check_todo_list_from_file(the_repository);
429 break;
430 case ACTION_REARRANGE_SQUASH:
431 ret = rearrange_squash_in_todo_file();
432 break;
433 case ACTION_ADD_EXEC: {
434 struct string_list commands = STRING_LIST_INIT_DUP;
436 split_exec_commands(opts->cmd, &commands);
437 ret = add_exec_commands(&commands);
438 string_list_clear(&commands, 0);
439 break;
441 default:
442 BUG("invalid command '%d'", command);
445 return ret;
448 static void imply_merge(struct rebase_options *opts, const char *option);
449 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
450 int unset)
452 struct rebase_options *opts = opt->value;
454 BUG_ON_OPT_ARG(arg);
456 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
457 opts->keep_empty = !unset;
458 opts->type = REBASE_MERGE;
459 return 0;
462 static const char * const builtin_rebase_interactive_usage[] = {
463 N_("git rebase--interactive [<options>]"),
464 NULL
467 int cmd_rebase__interactive(int argc, const char **argv, const char *prefix)
469 struct rebase_options opts = REBASE_OPTIONS_INIT;
470 struct object_id squash_onto = null_oid;
471 enum action command = ACTION_NONE;
472 struct option options[] = {
473 OPT_NEGBIT(0, "ff", &opts.flags, N_("allow fast-forward"),
474 REBASE_FORCE),
475 { OPTION_CALLBACK, 'k', "keep-empty", &options, NULL,
476 N_("keep commits which start empty"),
477 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
478 parse_opt_keep_empty },
479 OPT_BOOL_F(0, "allow-empty-message", &opts.allow_empty_message,
480 N_("allow commits with empty messages"),
481 PARSE_OPT_HIDDEN),
482 OPT_BOOL(0, "rebase-merges", &opts.rebase_merges, N_("rebase merge commits")),
483 OPT_BOOL(0, "rebase-cousins", &opts.rebase_cousins,
484 N_("keep original branch points of cousins")),
485 OPT_BOOL(0, "autosquash", &opts.autosquash,
486 N_("move commits that begin with squash!/fixup!")),
487 OPT_BOOL(0, "signoff", &opts.signoff, N_("sign commits")),
488 OPT_BIT('v', "verbose", &opts.flags,
489 N_("display a diffstat of what changed upstream"),
490 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
491 OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),
492 ACTION_CONTINUE),
493 OPT_CMDMODE(0, "skip", &command, N_("skip commit"), ACTION_SKIP),
494 OPT_CMDMODE(0, "edit-todo", &command, N_("edit the todo list"),
495 ACTION_EDIT_TODO),
496 OPT_CMDMODE(0, "show-current-patch", &command, N_("show the current patch"),
497 ACTION_SHOW_CURRENT_PATCH),
498 OPT_CMDMODE(0, "shorten-ids", &command,
499 N_("shorten commit ids in the todo list"), ACTION_SHORTEN_OIDS),
500 OPT_CMDMODE(0, "expand-ids", &command,
501 N_("expand commit ids in the todo list"), ACTION_EXPAND_OIDS),
502 OPT_CMDMODE(0, "check-todo-list", &command,
503 N_("check the todo list"), ACTION_CHECK_TODO_LIST),
504 OPT_CMDMODE(0, "rearrange-squash", &command,
505 N_("rearrange fixup/squash lines"), ACTION_REARRANGE_SQUASH),
506 OPT_CMDMODE(0, "add-exec-commands", &command,
507 N_("insert exec commands in todo list"), ACTION_ADD_EXEC),
508 { OPTION_CALLBACK, 0, "onto", &opts.onto, N_("onto"), N_("onto"),
509 PARSE_OPT_NONEG, parse_opt_commit, 0 },
510 { OPTION_CALLBACK, 0, "restrict-revision", &opts.restrict_revision,
511 N_("restrict-revision"), N_("restrict revision"),
512 PARSE_OPT_NONEG, parse_opt_commit, 0 },
513 { OPTION_CALLBACK, 0, "squash-onto", &squash_onto, N_("squash-onto"),
514 N_("squash onto"), PARSE_OPT_NONEG, parse_opt_object_id, 0 },
515 { OPTION_CALLBACK, 0, "upstream", &opts.upstream, N_("upstream"),
516 N_("the upstream commit"), PARSE_OPT_NONEG, parse_opt_commit,
517 0 },
518 OPT_STRING(0, "head-name", &opts.head_name, N_("head-name"), N_("head name")),
519 { OPTION_STRING, 'S', "gpg-sign", &opts.gpg_sign_opt, N_("key-id"),
520 N_("GPG-sign commits"),
521 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
522 OPT_STRING(0, "strategy", &opts.strategy, N_("strategy"),
523 N_("rebase strategy")),
524 OPT_STRING(0, "strategy-opts", &opts.strategy_opts, N_("strategy-opts"),
525 N_("strategy options")),
526 OPT_STRING(0, "switch-to", &opts.switch_to, N_("switch-to"),
527 N_("the branch or commit to checkout")),
528 OPT_STRING(0, "onto-name", &opts.onto_name, N_("onto-name"), N_("onto name")),
529 OPT_STRING(0, "cmd", &opts.cmd, N_("cmd"), N_("the command to run")),
530 OPT_RERERE_AUTOUPDATE(&opts.allow_rerere_autoupdate),
531 OPT_BOOL(0, "reschedule-failed-exec", &opts.reschedule_failed_exec,
532 N_("automatically re-schedule any `exec` that fails")),
533 OPT_END()
536 opts.rebase_cousins = -1;
538 if (argc == 1)
539 usage_with_options(builtin_rebase_interactive_usage, options);
541 argc = parse_options(argc, argv, prefix, options,
542 builtin_rebase_interactive_usage, PARSE_OPT_KEEP_ARGV0);
544 if (!is_null_oid(&squash_onto))
545 opts.squash_onto = &squash_onto;
547 if (opts.rebase_cousins >= 0 && !opts.rebase_merges)
548 warning(_("--[no-]rebase-cousins has no effect without "
549 "--rebase-merges"));
551 return !!run_sequencer_rebase(&opts, command);
554 static int is_merge(struct rebase_options *opts)
556 return opts->type == REBASE_MERGE ||
557 opts->type == REBASE_PRESERVE_MERGES;
560 static void imply_merge(struct rebase_options *opts, const char *option)
562 switch (opts->type) {
563 case REBASE_APPLY:
564 die(_("%s requires the merge backend"), option);
565 break;
566 case REBASE_MERGE:
567 case REBASE_PRESERVE_MERGES:
568 break;
569 default:
570 opts->type = REBASE_MERGE; /* implied */
571 break;
575 /* Returns the filename prefixed by the state_dir */
576 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
578 static struct strbuf path = STRBUF_INIT;
579 static size_t prefix_len;
581 if (!prefix_len) {
582 strbuf_addf(&path, "%s/", opts->state_dir);
583 prefix_len = path.len;
586 strbuf_setlen(&path, prefix_len);
587 strbuf_addstr(&path, filename);
588 return path.buf;
591 /* Read one file, then strip line endings */
592 static int read_one(const char *path, struct strbuf *buf)
594 if (strbuf_read_file(buf, path, 0) < 0)
595 return error_errno(_("could not read '%s'"), path);
596 strbuf_trim_trailing_newline(buf);
597 return 0;
600 /* Initialize the rebase options from the state directory. */
601 static int read_basic_state(struct rebase_options *opts)
603 struct strbuf head_name = STRBUF_INIT;
604 struct strbuf buf = STRBUF_INIT;
605 struct object_id oid;
607 if (read_one(state_dir_path("head-name", opts), &head_name) ||
608 read_one(state_dir_path("onto", opts), &buf))
609 return -1;
610 opts->head_name = starts_with(head_name.buf, "refs/") ?
611 xstrdup(head_name.buf) : NULL;
612 strbuf_release(&head_name);
613 if (get_oid(buf.buf, &oid))
614 return error(_("could not get 'onto': '%s'"), buf.buf);
615 opts->onto = lookup_commit_or_die(&oid, buf.buf);
618 * We always write to orig-head, but interactive rebase used to write to
619 * head. Fall back to reading from head to cover for the case that the
620 * user upgraded git with an ongoing interactive rebase.
622 strbuf_reset(&buf);
623 if (file_exists(state_dir_path("orig-head", opts))) {
624 if (read_one(state_dir_path("orig-head", opts), &buf))
625 return -1;
626 } else if (read_one(state_dir_path("head", opts), &buf))
627 return -1;
628 if (get_oid(buf.buf, &opts->orig_head))
629 return error(_("invalid orig-head: '%s'"), buf.buf);
631 if (file_exists(state_dir_path("quiet", opts)))
632 opts->flags &= ~REBASE_NO_QUIET;
633 else
634 opts->flags |= REBASE_NO_QUIET;
636 if (file_exists(state_dir_path("verbose", opts)))
637 opts->flags |= REBASE_VERBOSE;
639 if (file_exists(state_dir_path("signoff", opts))) {
640 opts->signoff = 1;
641 opts->flags |= REBASE_FORCE;
644 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
645 strbuf_reset(&buf);
646 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
647 &buf))
648 return -1;
649 if (!strcmp(buf.buf, "--rerere-autoupdate"))
650 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
651 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
652 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
653 else
654 warning(_("ignoring invalid allow_rerere_autoupdate: "
655 "'%s'"), buf.buf);
658 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
659 strbuf_reset(&buf);
660 if (read_one(state_dir_path("gpg_sign_opt", opts),
661 &buf))
662 return -1;
663 free(opts->gpg_sign_opt);
664 opts->gpg_sign_opt = xstrdup(buf.buf);
667 if (file_exists(state_dir_path("strategy", opts))) {
668 strbuf_reset(&buf);
669 if (read_one(state_dir_path("strategy", opts), &buf))
670 return -1;
671 free(opts->strategy);
672 opts->strategy = xstrdup(buf.buf);
675 if (file_exists(state_dir_path("strategy_opts", opts))) {
676 strbuf_reset(&buf);
677 if (read_one(state_dir_path("strategy_opts", opts), &buf))
678 return -1;
679 free(opts->strategy_opts);
680 opts->strategy_opts = xstrdup(buf.buf);
683 strbuf_release(&buf);
685 return 0;
688 static int rebase_write_basic_state(struct rebase_options *opts)
690 write_file(state_dir_path("head-name", opts), "%s",
691 opts->head_name ? opts->head_name : "detached HEAD");
692 write_file(state_dir_path("onto", opts), "%s",
693 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
694 write_file(state_dir_path("orig-head", opts), "%s",
695 oid_to_hex(&opts->orig_head));
696 if (!(opts->flags & REBASE_NO_QUIET))
697 write_file(state_dir_path("quiet", opts), "%s", "");
698 if (opts->flags & REBASE_VERBOSE)
699 write_file(state_dir_path("verbose", opts), "%s", "");
700 if (opts->strategy)
701 write_file(state_dir_path("strategy", opts), "%s",
702 opts->strategy);
703 if (opts->strategy_opts)
704 write_file(state_dir_path("strategy_opts", opts), "%s",
705 opts->strategy_opts);
706 if (opts->allow_rerere_autoupdate > 0)
707 write_file(state_dir_path("allow_rerere_autoupdate", opts),
708 "-%s-rerere-autoupdate",
709 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
710 "" : "-no");
711 if (opts->gpg_sign_opt)
712 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
713 opts->gpg_sign_opt);
714 if (opts->signoff)
715 write_file(state_dir_path("signoff", opts), "--signoff");
717 return 0;
720 static int apply_autostash(struct rebase_options *opts)
722 const char *path = state_dir_path("autostash", opts);
723 struct strbuf autostash = STRBUF_INIT;
724 struct child_process stash_apply = CHILD_PROCESS_INIT;
726 if (!file_exists(path))
727 return 0;
729 if (read_one(path, &autostash))
730 return error(_("Could not read '%s'"), path);
731 /* Ensure that the hash is not mistaken for a number */
732 strbuf_addstr(&autostash, "^0");
733 argv_array_pushl(&stash_apply.args,
734 "stash", "apply", autostash.buf, NULL);
735 stash_apply.git_cmd = 1;
736 stash_apply.no_stderr = stash_apply.no_stdout =
737 stash_apply.no_stdin = 1;
738 if (!run_command(&stash_apply))
739 printf(_("Applied autostash.\n"));
740 else {
741 struct argv_array args = ARGV_ARRAY_INIT;
742 int res = 0;
744 argv_array_pushl(&args,
745 "stash", "store", "-m", "autostash", "-q",
746 autostash.buf, NULL);
747 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
748 res = error(_("Cannot store %s"), autostash.buf);
749 argv_array_clear(&args);
750 strbuf_release(&autostash);
751 if (res)
752 return res;
754 fprintf(stderr,
755 _("Applying autostash resulted in conflicts.\n"
756 "Your changes are safe in the stash.\n"
757 "You can run \"git stash pop\" or \"git stash drop\" "
758 "at any time.\n"));
761 strbuf_release(&autostash);
762 return 0;
765 static int finish_rebase(struct rebase_options *opts)
767 struct strbuf dir = STRBUF_INIT;
768 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
769 int ret = 0;
771 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
772 apply_autostash(opts);
773 close_object_store(the_repository->objects);
775 * We ignore errors in 'gc --auto', since the
776 * user should see them.
778 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
779 if (opts->type == REBASE_MERGE) {
780 struct replay_opts replay = REPLAY_OPTS_INIT;
782 replay.action = REPLAY_INTERACTIVE_REBASE;
783 ret = sequencer_remove_state(&replay);
784 } else {
785 strbuf_addstr(&dir, opts->state_dir);
786 if (remove_dir_recursively(&dir, 0))
787 ret = error(_("could not remove '%s'"),
788 opts->state_dir);
789 strbuf_release(&dir);
792 return ret;
795 static struct commit *peel_committish(const char *name)
797 struct object *obj;
798 struct object_id oid;
800 if (get_oid(name, &oid))
801 return NULL;
802 obj = parse_object(the_repository, &oid);
803 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
806 static void add_var(struct strbuf *buf, const char *name, const char *value)
808 if (!value)
809 strbuf_addf(buf, "unset %s; ", name);
810 else {
811 strbuf_addf(buf, "%s=", name);
812 sq_quote_buf(buf, value);
813 strbuf_addstr(buf, "; ");
817 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
819 #define RESET_HEAD_DETACH (1<<0)
820 #define RESET_HEAD_HARD (1<<1)
821 #define RESET_HEAD_RUN_POST_CHECKOUT_HOOK (1<<2)
822 #define RESET_HEAD_REFS_ONLY (1<<3)
823 #define RESET_ORIG_HEAD (1<<4)
825 static int reset_head(struct object_id *oid, const char *action,
826 const char *switch_to_branch, unsigned flags,
827 const char *reflog_orig_head, const char *reflog_head)
829 unsigned detach_head = flags & RESET_HEAD_DETACH;
830 unsigned reset_hard = flags & RESET_HEAD_HARD;
831 unsigned run_hook = flags & RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
832 unsigned refs_only = flags & RESET_HEAD_REFS_ONLY;
833 unsigned update_orig_head = flags & RESET_ORIG_HEAD;
834 struct object_id head_oid;
835 struct tree_desc desc[2] = { { NULL }, { NULL } };
836 struct lock_file lock = LOCK_INIT;
837 struct unpack_trees_options unpack_tree_opts;
838 struct tree *tree;
839 const char *reflog_action;
840 struct strbuf msg = STRBUF_INIT;
841 size_t prefix_len;
842 struct object_id *orig = NULL, oid_orig,
843 *old_orig = NULL, oid_old_orig;
844 int ret = 0, nr = 0;
846 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
847 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
849 if (!refs_only && hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
850 ret = -1;
851 goto leave_reset_head;
854 if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
855 ret = error(_("could not determine HEAD revision"));
856 goto leave_reset_head;
859 if (!oid)
860 oid = &head_oid;
862 if (refs_only)
863 goto reset_head_refs;
865 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
866 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
867 unpack_tree_opts.head_idx = 1;
868 unpack_tree_opts.src_index = the_repository->index;
869 unpack_tree_opts.dst_index = the_repository->index;
870 unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
871 unpack_tree_opts.update = 1;
872 unpack_tree_opts.merge = 1;
873 init_checkout_metadata(&unpack_tree_opts.meta, switch_to_branch, oid, NULL);
874 if (!detach_head)
875 unpack_tree_opts.reset = 1;
877 if (repo_read_index_unmerged(the_repository) < 0) {
878 ret = error(_("could not read index"));
879 goto leave_reset_head;
882 if (!reset_hard && !fill_tree_descriptor(the_repository, &desc[nr++], &head_oid)) {
883 ret = error(_("failed to find tree of %s"),
884 oid_to_hex(&head_oid));
885 goto leave_reset_head;
888 if (!fill_tree_descriptor(the_repository, &desc[nr++], oid)) {
889 ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
890 goto leave_reset_head;
893 if (unpack_trees(nr, desc, &unpack_tree_opts)) {
894 ret = -1;
895 goto leave_reset_head;
898 tree = parse_tree_indirect(oid);
899 prime_cache_tree(the_repository, the_repository->index, tree);
901 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
902 ret = error(_("could not write index"));
903 goto leave_reset_head;
906 reset_head_refs:
907 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
908 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
909 prefix_len = msg.len;
911 if (update_orig_head) {
912 if (!get_oid("ORIG_HEAD", &oid_old_orig))
913 old_orig = &oid_old_orig;
914 if (!get_oid("HEAD", &oid_orig)) {
915 orig = &oid_orig;
916 if (!reflog_orig_head) {
917 strbuf_addstr(&msg, "updating ORIG_HEAD");
918 reflog_orig_head = msg.buf;
920 update_ref(reflog_orig_head, "ORIG_HEAD", orig,
921 old_orig, 0, UPDATE_REFS_MSG_ON_ERR);
922 } else if (old_orig)
923 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
926 if (!reflog_head) {
927 strbuf_setlen(&msg, prefix_len);
928 strbuf_addstr(&msg, "updating HEAD");
929 reflog_head = msg.buf;
931 if (!switch_to_branch)
932 ret = update_ref(reflog_head, "HEAD", oid, orig,
933 detach_head ? REF_NO_DEREF : 0,
934 UPDATE_REFS_MSG_ON_ERR);
935 else {
936 ret = update_ref(reflog_head, switch_to_branch, oid,
937 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
938 if (!ret)
939 ret = create_symref("HEAD", switch_to_branch,
940 reflog_head);
942 if (run_hook)
943 run_hook_le(NULL, "post-checkout",
944 oid_to_hex(orig ? orig : &null_oid),
945 oid_to_hex(oid), "1", NULL);
947 leave_reset_head:
948 strbuf_release(&msg);
949 rollback_lock_file(&lock);
950 while (nr)
951 free((void *)desc[--nr].buffer);
952 return ret;
955 static int move_to_original_branch(struct rebase_options *opts)
957 struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
958 int ret;
960 if (!opts->head_name)
961 return 0; /* nothing to move back to */
963 if (!opts->onto)
964 BUG("move_to_original_branch without onto");
966 strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
967 opts->head_name, oid_to_hex(&opts->onto->object.oid));
968 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
969 opts->head_name);
970 ret = reset_head(NULL, "", opts->head_name, RESET_HEAD_REFS_ONLY,
971 orig_head_reflog.buf, head_reflog.buf);
973 strbuf_release(&orig_head_reflog);
974 strbuf_release(&head_reflog);
975 return ret;
978 static const char *resolvemsg =
979 N_("Resolve all conflicts manually, mark them as resolved with\n"
980 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
981 "You can instead skip this commit: run \"git rebase --skip\".\n"
982 "To abort and get back to the state before \"git rebase\", run "
983 "\"git rebase --abort\".");
985 static int run_am(struct rebase_options *opts)
987 struct child_process am = CHILD_PROCESS_INIT;
988 struct child_process format_patch = CHILD_PROCESS_INIT;
989 struct strbuf revisions = STRBUF_INIT;
990 int status;
991 char *rebased_patches;
993 am.git_cmd = 1;
994 argv_array_push(&am.args, "am");
996 if (opts->action && !strcmp("continue", opts->action)) {
997 argv_array_push(&am.args, "--resolved");
998 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
999 if (opts->gpg_sign_opt)
1000 argv_array_push(&am.args, opts->gpg_sign_opt);
1001 status = run_command(&am);
1002 if (status)
1003 return status;
1005 return move_to_original_branch(opts);
1007 if (opts->action && !strcmp("skip", opts->action)) {
1008 argv_array_push(&am.args, "--skip");
1009 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
1010 status = run_command(&am);
1011 if (status)
1012 return status;
1014 return move_to_original_branch(opts);
1016 if (opts->action && !strcmp("show-current-patch", opts->action)) {
1017 argv_array_push(&am.args, "--show-current-patch");
1018 return run_command(&am);
1021 strbuf_addf(&revisions, "%s...%s",
1022 oid_to_hex(opts->root ?
1023 /* this is now equivalent to !opts->upstream */
1024 &opts->onto->object.oid :
1025 &opts->upstream->object.oid),
1026 oid_to_hex(&opts->orig_head));
1028 rebased_patches = xstrdup(git_path("rebased-patches"));
1029 format_patch.out = open(rebased_patches,
1030 O_WRONLY | O_CREAT | O_TRUNC, 0666);
1031 if (format_patch.out < 0) {
1032 status = error_errno(_("could not open '%s' for writing"),
1033 rebased_patches);
1034 free(rebased_patches);
1035 argv_array_clear(&am.args);
1036 return status;
1039 format_patch.git_cmd = 1;
1040 argv_array_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
1041 "--full-index", "--cherry-pick", "--right-only",
1042 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
1043 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
1044 "--no-base", NULL);
1045 if (opts->git_format_patch_opt.len)
1046 argv_array_split(&format_patch.args,
1047 opts->git_format_patch_opt.buf);
1048 argv_array_push(&format_patch.args, revisions.buf);
1049 if (opts->restrict_revision)
1050 argv_array_pushf(&format_patch.args, "^%s",
1051 oid_to_hex(&opts->restrict_revision->object.oid));
1053 status = run_command(&format_patch);
1054 if (status) {
1055 unlink(rebased_patches);
1056 free(rebased_patches);
1057 argv_array_clear(&am.args);
1059 reset_head(&opts->orig_head, "checkout", opts->head_name, 0,
1060 "HEAD", NULL);
1061 error(_("\ngit encountered an error while preparing the "
1062 "patches to replay\n"
1063 "these revisions:\n"
1064 "\n %s\n\n"
1065 "As a result, git cannot rebase them."),
1066 opts->revisions);
1068 strbuf_release(&revisions);
1069 return status;
1071 strbuf_release(&revisions);
1073 am.in = open(rebased_patches, O_RDONLY);
1074 if (am.in < 0) {
1075 status = error_errno(_("could not open '%s' for reading"),
1076 rebased_patches);
1077 free(rebased_patches);
1078 argv_array_clear(&am.args);
1079 return status;
1082 argv_array_pushv(&am.args, opts->git_am_opts.argv);
1083 argv_array_push(&am.args, "--rebasing");
1084 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
1085 argv_array_push(&am.args, "--patch-format=mboxrd");
1086 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
1087 argv_array_push(&am.args, "--rerere-autoupdate");
1088 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
1089 argv_array_push(&am.args, "--no-rerere-autoupdate");
1090 if (opts->gpg_sign_opt)
1091 argv_array_push(&am.args, opts->gpg_sign_opt);
1092 status = run_command(&am);
1093 unlink(rebased_patches);
1094 free(rebased_patches);
1096 if (!status) {
1097 return move_to_original_branch(opts);
1100 if (is_directory(opts->state_dir))
1101 rebase_write_basic_state(opts);
1103 return status;
1106 static int run_specific_rebase(struct rebase_options *opts, enum action action)
1108 const char *argv[] = { NULL, NULL };
1109 struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
1110 int status;
1111 const char *backend, *backend_func;
1113 if (opts->type == REBASE_MERGE) {
1114 /* Run sequencer-based rebase */
1115 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
1116 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1117 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
1118 opts->autosquash = 0;
1120 if (opts->gpg_sign_opt) {
1121 /* remove the leading "-S" */
1122 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
1123 free(opts->gpg_sign_opt);
1124 opts->gpg_sign_opt = tmp;
1127 status = run_sequencer_rebase(opts, action);
1128 goto finished_rebase;
1131 if (opts->type == REBASE_APPLY) {
1132 status = run_am(opts);
1133 goto finished_rebase;
1136 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
1137 add_var(&script_snippet, "state_dir", opts->state_dir);
1139 add_var(&script_snippet, "upstream_name", opts->upstream_name);
1140 add_var(&script_snippet, "upstream", opts->upstream ?
1141 oid_to_hex(&opts->upstream->object.oid) : NULL);
1142 add_var(&script_snippet, "head_name",
1143 opts->head_name ? opts->head_name : "detached HEAD");
1144 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
1145 add_var(&script_snippet, "onto", opts->onto ?
1146 oid_to_hex(&opts->onto->object.oid) : NULL);
1147 add_var(&script_snippet, "onto_name", opts->onto_name);
1148 add_var(&script_snippet, "revisions", opts->revisions);
1149 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
1150 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
1151 sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
1152 add_var(&script_snippet, "git_am_opt", buf.buf);
1153 strbuf_release(&buf);
1154 add_var(&script_snippet, "verbose",
1155 opts->flags & REBASE_VERBOSE ? "t" : "");
1156 add_var(&script_snippet, "diffstat",
1157 opts->flags & REBASE_DIFFSTAT ? "t" : "");
1158 add_var(&script_snippet, "force_rebase",
1159 opts->flags & REBASE_FORCE ? "t" : "");
1160 if (opts->switch_to)
1161 add_var(&script_snippet, "switch_to", opts->switch_to);
1162 add_var(&script_snippet, "action", opts->action ? opts->action : "");
1163 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
1164 add_var(&script_snippet, "allow_rerere_autoupdate",
1165 opts->allow_rerere_autoupdate ?
1166 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
1167 "--rerere-autoupdate" : "--no-rerere-autoupdate" : "");
1168 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
1169 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
1170 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
1171 add_var(&script_snippet, "cmd", opts->cmd);
1172 add_var(&script_snippet, "allow_empty_message",
1173 opts->allow_empty_message ? "--allow-empty-message" : "");
1174 add_var(&script_snippet, "rebase_merges",
1175 opts->rebase_merges ? "t" : "");
1176 add_var(&script_snippet, "rebase_cousins",
1177 opts->rebase_cousins ? "t" : "");
1178 add_var(&script_snippet, "strategy", opts->strategy);
1179 add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
1180 add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
1181 add_var(&script_snippet, "squash_onto",
1182 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
1183 add_var(&script_snippet, "git_format_patch_opt",
1184 opts->git_format_patch_opt.buf);
1186 if (is_merge(opts) &&
1187 !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1188 strbuf_addstr(&script_snippet,
1189 "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
1190 opts->autosquash = 0;
1193 switch (opts->type) {
1194 case REBASE_PRESERVE_MERGES:
1195 backend = "git-rebase--preserve-merges";
1196 backend_func = "git_rebase__preserve_merges";
1197 break;
1198 default:
1199 BUG("Unhandled rebase type %d", opts->type);
1200 break;
1203 strbuf_addf(&script_snippet,
1204 ". git-sh-setup && . %s && %s", backend, backend_func);
1205 argv[0] = script_snippet.buf;
1207 status = run_command_v_opt(argv, RUN_USING_SHELL);
1208 finished_rebase:
1209 if (opts->dont_finish_rebase)
1210 ; /* do nothing */
1211 else if (opts->type == REBASE_MERGE)
1212 ; /* merge backend cleans up after itself */
1213 else if (status == 0) {
1214 if (!file_exists(state_dir_path("stopped-sha", opts)))
1215 finish_rebase(opts);
1216 } else if (status == 2) {
1217 struct strbuf dir = STRBUF_INIT;
1219 apply_autostash(opts);
1220 strbuf_addstr(&dir, opts->state_dir);
1221 remove_dir_recursively(&dir, 0);
1222 strbuf_release(&dir);
1223 die("Nothing to do");
1226 strbuf_release(&script_snippet);
1228 return status ? -1 : 0;
1231 static int rebase_config(const char *var, const char *value, void *data)
1233 struct rebase_options *opts = data;
1235 if (!strcmp(var, "rebase.stat")) {
1236 if (git_config_bool(var, value))
1237 opts->flags |= REBASE_DIFFSTAT;
1238 else
1239 opts->flags &= ~REBASE_DIFFSTAT;
1240 return 0;
1243 if (!strcmp(var, "rebase.autosquash")) {
1244 opts->autosquash = git_config_bool(var, value);
1245 return 0;
1248 if (!strcmp(var, "commit.gpgsign")) {
1249 free(opts->gpg_sign_opt);
1250 opts->gpg_sign_opt = git_config_bool(var, value) ?
1251 xstrdup("-S") : NULL;
1252 return 0;
1255 if (!strcmp(var, "rebase.autostash")) {
1256 opts->autostash = git_config_bool(var, value);
1257 return 0;
1260 if (!strcmp(var, "rebase.reschedulefailedexec")) {
1261 opts->reschedule_failed_exec = git_config_bool(var, value);
1262 return 0;
1265 if (!strcmp(var, "rebase.usebuiltin")) {
1266 opts->use_legacy_rebase = !git_config_bool(var, value);
1267 return 0;
1270 if (!strcmp(var, "rebase.backend")) {
1271 return git_config_string(&opts->default_backend, var, value);
1274 return git_default_config(var, value, data);
1278 * Determines whether the commits in from..to are linear, i.e. contain
1279 * no merge commits. This function *expects* `from` to be an ancestor of
1280 * `to`.
1282 static int is_linear_history(struct commit *from, struct commit *to)
1284 while (to && to != from) {
1285 parse_commit(to);
1286 if (!to->parents)
1287 return 1;
1288 if (to->parents->next)
1289 return 0;
1290 to = to->parents->item;
1292 return 1;
1295 static int can_fast_forward(struct commit *onto, struct commit *upstream,
1296 struct commit *restrict_revision,
1297 struct object_id *head_oid, struct object_id *merge_base)
1299 struct commit *head = lookup_commit(the_repository, head_oid);
1300 struct commit_list *merge_bases = NULL;
1301 int res = 0;
1303 if (!head)
1304 goto done;
1306 merge_bases = get_merge_bases(onto, head);
1307 if (!merge_bases || merge_bases->next) {
1308 oidcpy(merge_base, &null_oid);
1309 goto done;
1312 oidcpy(merge_base, &merge_bases->item->object.oid);
1313 if (!oideq(merge_base, &onto->object.oid))
1314 goto done;
1316 if (restrict_revision && !oideq(&restrict_revision->object.oid, merge_base))
1317 goto done;
1319 if (!upstream)
1320 goto done;
1322 free_commit_list(merge_bases);
1323 merge_bases = get_merge_bases(upstream, head);
1324 if (!merge_bases || merge_bases->next)
1325 goto done;
1327 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
1328 goto done;
1330 res = 1;
1332 done:
1333 free_commit_list(merge_bases);
1334 return res && is_linear_history(onto, head);
1337 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
1339 struct rebase_options *opts = opt->value;
1341 BUG_ON_OPT_NEG(unset);
1342 BUG_ON_OPT_ARG(arg);
1344 opts->type = REBASE_APPLY;
1346 return 0;
1349 /* -i followed by -m is still -i */
1350 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
1352 struct rebase_options *opts = opt->value;
1354 BUG_ON_OPT_NEG(unset);
1355 BUG_ON_OPT_ARG(arg);
1357 if (!is_merge(opts))
1358 opts->type = REBASE_MERGE;
1360 return 0;
1363 /* -i followed by -p is still explicitly interactive, but -p alone is not */
1364 static int parse_opt_interactive(const struct option *opt, const char *arg,
1365 int unset)
1367 struct rebase_options *opts = opt->value;
1369 BUG_ON_OPT_NEG(unset);
1370 BUG_ON_OPT_ARG(arg);
1372 opts->type = REBASE_MERGE;
1373 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
1375 return 0;
1378 static enum empty_type parse_empty_value(const char *value)
1380 if (!strcasecmp(value, "drop"))
1381 return EMPTY_DROP;
1382 else if (!strcasecmp(value, "keep"))
1383 return EMPTY_KEEP;
1384 else if (!strcasecmp(value, "ask"))
1385 return EMPTY_ASK;
1387 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
1390 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
1392 struct rebase_options *options = opt->value;
1393 enum empty_type value = parse_empty_value(arg);
1395 BUG_ON_OPT_NEG(unset);
1397 options->empty = value;
1398 return 0;
1401 static void NORETURN error_on_missing_default_upstream(void)
1403 struct branch *current_branch = branch_get(NULL);
1405 printf(_("%s\n"
1406 "Please specify which branch you want to rebase against.\n"
1407 "See git-rebase(1) for details.\n"
1408 "\n"
1409 " git rebase '<branch>'\n"
1410 "\n"),
1411 current_branch ? _("There is no tracking information for "
1412 "the current branch.") :
1413 _("You are not currently on a branch."));
1415 if (current_branch) {
1416 const char *remote = current_branch->remote_name;
1418 if (!remote)
1419 remote = _("<remote>");
1421 printf(_("If you wish to set tracking information for this "
1422 "branch you can do so with:\n"
1423 "\n"
1424 " git branch --set-upstream-to=%s/<branch> %s\n"
1425 "\n"),
1426 remote, current_branch->name);
1428 exit(1);
1431 static void set_reflog_action(struct rebase_options *options)
1433 const char *env;
1434 struct strbuf buf = STRBUF_INIT;
1436 if (!is_merge(options))
1437 return;
1439 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1440 if (env && strcmp("rebase", env))
1441 return; /* only override it if it is "rebase" */
1443 strbuf_addf(&buf, "rebase (%s)", options->action);
1444 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1445 strbuf_release(&buf);
1448 static int check_exec_cmd(const char *cmd)
1450 if (strchr(cmd, '\n'))
1451 return error(_("exec commands cannot contain newlines"));
1453 /* Does the command consist purely of whitespace? */
1454 if (!cmd[strspn(cmd, " \t\r\f\v")])
1455 return error(_("empty exec command"));
1457 return 0;
1461 int cmd_rebase(int argc, const char **argv, const char *prefix)
1463 struct rebase_options options = REBASE_OPTIONS_INIT;
1464 const char *branch_name;
1465 int ret, flags, total_argc, in_progress = 0;
1466 int keep_base = 0;
1467 int ok_to_skip_pre_rebase = 0;
1468 struct strbuf msg = STRBUF_INIT;
1469 struct strbuf revisions = STRBUF_INIT;
1470 struct strbuf buf = STRBUF_INIT;
1471 struct object_id merge_base;
1472 enum action action = ACTION_NONE;
1473 const char *gpg_sign = NULL;
1474 struct string_list exec = STRING_LIST_INIT_NODUP;
1475 const char *rebase_merges = NULL;
1476 int fork_point = -1;
1477 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1478 struct object_id squash_onto;
1479 char *squash_onto_name = NULL;
1480 int reschedule_failed_exec = -1;
1481 int allow_preemptive_ff = 1;
1482 struct option builtin_rebase_options[] = {
1483 OPT_STRING(0, "onto", &options.onto_name,
1484 N_("revision"),
1485 N_("rebase onto given branch instead of upstream")),
1486 OPT_BOOL(0, "keep-base", &keep_base,
1487 N_("use the merge-base of upstream and branch as the current base")),
1488 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1489 N_("allow pre-rebase hook to run")),
1490 OPT_NEGBIT('q', "quiet", &options.flags,
1491 N_("be quiet. implies --no-stat"),
1492 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1493 OPT_BIT('v', "verbose", &options.flags,
1494 N_("display a diffstat of what changed upstream"),
1495 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1496 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1497 N_("do not show diffstat of what changed upstream"),
1498 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1499 OPT_BOOL(0, "signoff", &options.signoff,
1500 N_("add a Signed-off-by: line to each commit")),
1501 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
1502 NULL, N_("passed to 'git am'"),
1503 PARSE_OPT_NOARG),
1504 OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
1505 &options.git_am_opts, NULL,
1506 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1507 OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
1508 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1509 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1510 N_("passed to 'git apply'"), 0),
1511 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1512 N_("action"), N_("passed to 'git apply'"), 0),
1513 OPT_BIT('f', "force-rebase", &options.flags,
1514 N_("cherry-pick all commits, even if unchanged"),
1515 REBASE_FORCE),
1516 OPT_BIT(0, "no-ff", &options.flags,
1517 N_("cherry-pick all commits, even if unchanged"),
1518 REBASE_FORCE),
1519 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1520 ACTION_CONTINUE),
1521 OPT_CMDMODE(0, "skip", &action,
1522 N_("skip current patch and continue"), ACTION_SKIP),
1523 OPT_CMDMODE(0, "abort", &action,
1524 N_("abort and check out the original branch"),
1525 ACTION_ABORT),
1526 OPT_CMDMODE(0, "quit", &action,
1527 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1528 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1529 "during an interactive rebase"), ACTION_EDIT_TODO),
1530 OPT_CMDMODE(0, "show-current-patch", &action,
1531 N_("show the patch file being applied or merged"),
1532 ACTION_SHOW_CURRENT_PATCH),
1533 { OPTION_CALLBACK, 0, "apply", &options, NULL,
1534 N_("use apply strategies to rebase"),
1535 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1536 parse_opt_am },
1537 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
1538 N_("use merging strategies to rebase"),
1539 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1540 parse_opt_merge },
1541 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
1542 N_("let the user edit the list of commits to rebase"),
1543 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1544 parse_opt_interactive },
1545 OPT_SET_INT_F('p', "preserve-merges", &options.type,
1546 N_("(DEPRECATED) try to recreate merges instead of "
1547 "ignoring them"),
1548 REBASE_PRESERVE_MERGES, PARSE_OPT_HIDDEN),
1549 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1550 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1551 N_("how to handle commits that become empty"),
1552 PARSE_OPT_NONEG, parse_opt_empty),
1553 { OPTION_CALLBACK, 'k', "keep-empty", &options, NULL,
1554 N_("keep commits which start empty"),
1555 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1556 parse_opt_keep_empty },
1557 OPT_BOOL(0, "autosquash", &options.autosquash,
1558 N_("move commits that begin with "
1559 "squash!/fixup! under -i")),
1560 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1561 N_("GPG-sign commits"),
1562 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1563 OPT_BOOL(0, "autostash", &options.autostash,
1564 N_("automatically stash/stash pop before and after")),
1565 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1566 N_("add exec lines after each commit of the "
1567 "editable list")),
1568 OPT_BOOL_F(0, "allow-empty-message",
1569 &options.allow_empty_message,
1570 N_("allow rebasing commits with empty messages"),
1571 PARSE_OPT_HIDDEN),
1572 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1573 N_("mode"),
1574 N_("try to rebase merges instead of skipping them"),
1575 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1576 OPT_BOOL(0, "fork-point", &fork_point,
1577 N_("use 'merge-base --fork-point' to refine upstream")),
1578 OPT_STRING('s', "strategy", &options.strategy,
1579 N_("strategy"), N_("use the given merge strategy")),
1580 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1581 N_("option"),
1582 N_("pass the argument through to the merge "
1583 "strategy")),
1584 OPT_BOOL(0, "root", &options.root,
1585 N_("rebase all reachable commits up to the root(s)")),
1586 OPT_BOOL(0, "reschedule-failed-exec",
1587 &reschedule_failed_exec,
1588 N_("automatically re-schedule any `exec` that fails")),
1589 OPT_END(),
1591 int i;
1593 if (argc == 2 && !strcmp(argv[1], "-h"))
1594 usage_with_options(builtin_rebase_usage,
1595 builtin_rebase_options);
1597 options.allow_empty_message = 1;
1598 git_config(rebase_config, &options);
1599 /* options.gpg_sign_opt will be either "-S" or NULL */
1600 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1601 FREE_AND_NULL(options.gpg_sign_opt);
1603 if (options.use_legacy_rebase ||
1604 !git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1))
1605 warning(_("the rebase.useBuiltin support has been removed!\n"
1606 "See its entry in 'git help config' for details."));
1608 strbuf_reset(&buf);
1609 strbuf_addf(&buf, "%s/applying", apply_dir());
1610 if(file_exists(buf.buf))
1611 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1613 if (is_directory(apply_dir())) {
1614 options.type = REBASE_APPLY;
1615 options.state_dir = apply_dir();
1616 } else if (is_directory(merge_dir())) {
1617 strbuf_reset(&buf);
1618 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1619 if (is_directory(buf.buf)) {
1620 options.type = REBASE_PRESERVE_MERGES;
1621 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1622 } else {
1623 strbuf_reset(&buf);
1624 strbuf_addf(&buf, "%s/interactive", merge_dir());
1625 if(file_exists(buf.buf)) {
1626 options.type = REBASE_MERGE;
1627 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1628 } else
1629 options.type = REBASE_MERGE;
1631 options.state_dir = merge_dir();
1634 if (options.type != REBASE_UNSPECIFIED)
1635 in_progress = 1;
1637 total_argc = argc;
1638 argc = parse_options(argc, argv, prefix,
1639 builtin_rebase_options,
1640 builtin_rebase_usage, 0);
1642 if (action != ACTION_NONE && total_argc != 2) {
1643 usage_with_options(builtin_rebase_usage,
1644 builtin_rebase_options);
1647 if (argc > 2)
1648 usage_with_options(builtin_rebase_usage,
1649 builtin_rebase_options);
1651 if (options.type == REBASE_PRESERVE_MERGES)
1652 warning(_("git rebase --preserve-merges is deprecated. "
1653 "Use --rebase-merges instead."));
1655 if (keep_base) {
1656 if (options.onto_name)
1657 die(_("cannot combine '--keep-base' with '--onto'"));
1658 if (options.root)
1659 die(_("cannot combine '--keep-base' with '--root'"));
1662 if (action != ACTION_NONE && !in_progress)
1663 die(_("No rebase in progress?"));
1664 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1666 if (action == ACTION_EDIT_TODO && !is_merge(&options))
1667 die(_("The --edit-todo action can only be used during "
1668 "interactive rebase."));
1670 if (trace2_is_enabled()) {
1671 if (is_merge(&options))
1672 trace2_cmd_mode("interactive");
1673 else if (exec.nr)
1674 trace2_cmd_mode("interactive-exec");
1675 else
1676 trace2_cmd_mode(action_names[action]);
1679 switch (action) {
1680 case ACTION_CONTINUE: {
1681 struct object_id head;
1682 struct lock_file lock_file = LOCK_INIT;
1683 int fd;
1685 options.action = "continue";
1686 set_reflog_action(&options);
1688 /* Sanity check */
1689 if (get_oid("HEAD", &head))
1690 die(_("Cannot read HEAD"));
1692 fd = hold_locked_index(&lock_file, 0);
1693 if (repo_read_index(the_repository) < 0)
1694 die(_("could not read index"));
1695 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1696 NULL);
1697 if (0 <= fd)
1698 repo_update_index_if_able(the_repository, &lock_file);
1699 rollback_lock_file(&lock_file);
1701 if (has_unstaged_changes(the_repository, 1)) {
1702 puts(_("You must edit all merge conflicts and then\n"
1703 "mark them as resolved using git add"));
1704 exit(1);
1706 if (read_basic_state(&options))
1707 exit(1);
1708 goto run_rebase;
1710 case ACTION_SKIP: {
1711 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1713 options.action = "skip";
1714 set_reflog_action(&options);
1716 rerere_clear(the_repository, &merge_rr);
1717 string_list_clear(&merge_rr, 1);
1719 if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1720 NULL, NULL) < 0)
1721 die(_("could not discard worktree changes"));
1722 remove_branch_state(the_repository, 0);
1723 if (read_basic_state(&options))
1724 exit(1);
1725 goto run_rebase;
1727 case ACTION_ABORT: {
1728 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1729 options.action = "abort";
1730 set_reflog_action(&options);
1732 rerere_clear(the_repository, &merge_rr);
1733 string_list_clear(&merge_rr, 1);
1735 if (read_basic_state(&options))
1736 exit(1);
1737 if (reset_head(&options.orig_head, "reset",
1738 options.head_name, RESET_HEAD_HARD,
1739 NULL, NULL) < 0)
1740 die(_("could not move back to %s"),
1741 oid_to_hex(&options.orig_head));
1742 remove_branch_state(the_repository, 0);
1743 ret = !!finish_rebase(&options);
1744 goto cleanup;
1746 case ACTION_QUIT: {
1747 if (options.type == REBASE_MERGE) {
1748 struct replay_opts replay = REPLAY_OPTS_INIT;
1750 replay.action = REPLAY_INTERACTIVE_REBASE;
1751 ret = !!sequencer_remove_state(&replay);
1752 } else {
1753 strbuf_reset(&buf);
1754 strbuf_addstr(&buf, options.state_dir);
1755 ret = !!remove_dir_recursively(&buf, 0);
1756 if (ret)
1757 error(_("could not remove '%s'"),
1758 options.state_dir);
1760 goto cleanup;
1762 case ACTION_EDIT_TODO:
1763 options.action = "edit-todo";
1764 options.dont_finish_rebase = 1;
1765 goto run_rebase;
1766 case ACTION_SHOW_CURRENT_PATCH:
1767 options.action = "show-current-patch";
1768 options.dont_finish_rebase = 1;
1769 goto run_rebase;
1770 case ACTION_NONE:
1771 break;
1772 default:
1773 BUG("action: %d", action);
1776 /* Make sure no rebase is in progress */
1777 if (in_progress) {
1778 const char *last_slash = strrchr(options.state_dir, '/');
1779 const char *state_dir_base =
1780 last_slash ? last_slash + 1 : options.state_dir;
1781 const char *cmd_live_rebase =
1782 "git rebase (--continue | --abort | --skip)";
1783 strbuf_reset(&buf);
1784 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1785 die(_("It seems that there is already a %s directory, and\n"
1786 "I wonder if you are in the middle of another rebase. "
1787 "If that is the\n"
1788 "case, please try\n\t%s\n"
1789 "If that is not the case, please\n\t%s\n"
1790 "and run me again. I am stopping in case you still "
1791 "have something\n"
1792 "valuable there.\n"),
1793 state_dir_base, cmd_live_rebase, buf.buf);
1796 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1797 (action != ACTION_NONE) ||
1798 (exec.nr > 0) ||
1799 options.autosquash) {
1800 allow_preemptive_ff = 0;
1803 for (i = 0; i < options.git_am_opts.argc; i++) {
1804 const char *option = options.git_am_opts.argv[i], *p;
1805 if (!strcmp(option, "--committer-date-is-author-date") ||
1806 !strcmp(option, "--ignore-date") ||
1807 !strcmp(option, "--whitespace=fix") ||
1808 !strcmp(option, "--whitespace=strip"))
1809 allow_preemptive_ff = 0;
1810 else if (skip_prefix(option, "-C", &p)) {
1811 while (*p)
1812 if (!isdigit(*(p++)))
1813 die(_("switch `C' expects a "
1814 "numerical value"));
1815 } else if (skip_prefix(option, "--whitespace=", &p)) {
1816 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1817 strcmp(p, "error") && strcmp(p, "error-all"))
1818 die("Invalid whitespace option: '%s'", p);
1822 for (i = 0; i < exec.nr; i++)
1823 if (check_exec_cmd(exec.items[i].string))
1824 exit(1);
1826 if (!(options.flags & REBASE_NO_QUIET))
1827 argv_array_push(&options.git_am_opts, "-q");
1829 if (options.empty != EMPTY_UNSPECIFIED)
1830 imply_merge(&options, "--empty");
1832 if (gpg_sign)
1833 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1835 if (exec.nr) {
1836 int i;
1838 imply_merge(&options, "--exec");
1840 strbuf_reset(&buf);
1841 for (i = 0; i < exec.nr; i++)
1842 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1843 options.cmd = xstrdup(buf.buf);
1846 if (rebase_merges) {
1847 if (!*rebase_merges)
1848 ; /* default mode; do nothing */
1849 else if (!strcmp("rebase-cousins", rebase_merges))
1850 options.rebase_cousins = 1;
1851 else if (strcmp("no-rebase-cousins", rebase_merges))
1852 die(_("Unknown mode: %s"), rebase_merges);
1853 options.rebase_merges = 1;
1854 imply_merge(&options, "--rebase-merges");
1857 if (strategy_options.nr) {
1858 int i;
1860 if (!options.strategy)
1861 options.strategy = "recursive";
1863 strbuf_reset(&buf);
1864 for (i = 0; i < strategy_options.nr; i++)
1865 strbuf_addf(&buf, " --%s",
1866 strategy_options.items[i].string);
1867 options.strategy_opts = xstrdup(buf.buf);
1870 if (options.strategy) {
1871 options.strategy = xstrdup(options.strategy);
1872 switch (options.type) {
1873 case REBASE_APPLY:
1874 die(_("--strategy requires --merge or --interactive"));
1875 case REBASE_MERGE:
1876 case REBASE_PRESERVE_MERGES:
1877 /* compatible */
1878 break;
1879 case REBASE_UNSPECIFIED:
1880 options.type = REBASE_MERGE;
1881 break;
1882 default:
1883 BUG("unhandled rebase type (%d)", options.type);
1887 if (options.type == REBASE_MERGE)
1888 imply_merge(&options, "--merge");
1890 if (options.root && !options.onto_name)
1891 imply_merge(&options, "--root without --onto");
1893 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1894 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1896 if (options.git_am_opts.argc || options.type == REBASE_APPLY) {
1897 /* all am options except -q are compatible only with --apply */
1898 for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1899 if (strcmp(options.git_am_opts.argv[i], "-q"))
1900 break;
1902 if (i >= 0) {
1903 if (is_merge(&options))
1904 die(_("cannot combine apply options with "
1905 "merge options"));
1906 else
1907 options.type = REBASE_APPLY;
1911 if (options.type == REBASE_UNSPECIFIED) {
1912 if (!strcmp(options.default_backend, "merge"))
1913 imply_merge(&options, "--merge");
1914 else if (!strcmp(options.default_backend, "apply"))
1915 options.type = REBASE_APPLY;
1916 else
1917 die(_("Unknown rebase backend: %s"),
1918 options.default_backend);
1921 switch (options.type) {
1922 case REBASE_MERGE:
1923 case REBASE_PRESERVE_MERGES:
1924 options.state_dir = merge_dir();
1925 break;
1926 case REBASE_APPLY:
1927 options.state_dir = apply_dir();
1928 break;
1929 default:
1930 BUG("options.type was just set above; should be unreachable.");
1933 if (options.empty == EMPTY_UNSPECIFIED) {
1934 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1935 options.empty = EMPTY_ASK;
1936 else if (exec.nr > 0)
1937 options.empty = EMPTY_KEEP;
1938 else
1939 options.empty = EMPTY_DROP;
1941 if (reschedule_failed_exec > 0 && !is_merge(&options))
1942 die(_("--reschedule-failed-exec requires "
1943 "--exec or --interactive"));
1944 if (reschedule_failed_exec >= 0)
1945 options.reschedule_failed_exec = reschedule_failed_exec;
1947 if (options.signoff) {
1948 if (options.type == REBASE_PRESERVE_MERGES)
1949 die("cannot combine '--signoff' with "
1950 "'--preserve-merges'");
1951 argv_array_push(&options.git_am_opts, "--signoff");
1952 options.flags |= REBASE_FORCE;
1955 if (options.type == REBASE_PRESERVE_MERGES) {
1957 * Note: incompatibility with --signoff handled in signoff block above
1958 * Note: incompatibility with --interactive is just a strong warning;
1959 * git-rebase.txt caveats with "unless you know what you are doing"
1961 if (options.rebase_merges)
1962 die(_("cannot combine '--preserve-merges' with "
1963 "'--rebase-merges'"));
1965 if (options.reschedule_failed_exec)
1966 die(_("error: cannot combine '--preserve-merges' with "
1967 "'--reschedule-failed-exec'"));
1970 if (!options.root) {
1971 if (argc < 1) {
1972 struct branch *branch;
1974 branch = branch_get(NULL);
1975 options.upstream_name = branch_get_upstream(branch,
1976 NULL);
1977 if (!options.upstream_name)
1978 error_on_missing_default_upstream();
1979 if (fork_point < 0)
1980 fork_point = 1;
1981 } else {
1982 options.upstream_name = argv[0];
1983 argc--;
1984 argv++;
1985 if (!strcmp(options.upstream_name, "-"))
1986 options.upstream_name = "@{-1}";
1988 options.upstream = peel_committish(options.upstream_name);
1989 if (!options.upstream)
1990 die(_("invalid upstream '%s'"), options.upstream_name);
1991 options.upstream_arg = options.upstream_name;
1992 } else {
1993 if (!options.onto_name) {
1994 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1995 &squash_onto, NULL, NULL) < 0)
1996 die(_("Could not create new root commit"));
1997 options.squash_onto = &squash_onto;
1998 options.onto_name = squash_onto_name =
1999 xstrdup(oid_to_hex(&squash_onto));
2000 } else
2001 options.root_with_onto = 1;
2003 options.upstream_name = NULL;
2004 options.upstream = NULL;
2005 if (argc > 1)
2006 usage_with_options(builtin_rebase_usage,
2007 builtin_rebase_options);
2008 options.upstream_arg = "--root";
2011 /* Make sure the branch to rebase onto is valid. */
2012 if (keep_base) {
2013 strbuf_reset(&buf);
2014 strbuf_addstr(&buf, options.upstream_name);
2015 strbuf_addstr(&buf, "...");
2016 options.onto_name = xstrdup(buf.buf);
2017 } else if (!options.onto_name)
2018 options.onto_name = options.upstream_name;
2019 if (strstr(options.onto_name, "...")) {
2020 if (get_oid_mb(options.onto_name, &merge_base) < 0) {
2021 if (keep_base)
2022 die(_("'%s': need exactly one merge base with branch"),
2023 options.upstream_name);
2024 else
2025 die(_("'%s': need exactly one merge base"),
2026 options.onto_name);
2028 options.onto = lookup_commit_or_die(&merge_base,
2029 options.onto_name);
2030 } else {
2031 options.onto = peel_committish(options.onto_name);
2032 if (!options.onto)
2033 die(_("Does not point to a valid commit '%s'"),
2034 options.onto_name);
2038 * If the branch to rebase is given, that is the branch we will rebase
2039 * branch_name -- branch/commit being rebased, or
2040 * HEAD (already detached)
2041 * orig_head -- commit object name of tip of the branch before rebasing
2042 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
2044 if (argc == 1) {
2045 /* Is it "rebase other branchname" or "rebase other commit"? */
2046 branch_name = argv[0];
2047 options.switch_to = argv[0];
2049 /* Is it a local branch? */
2050 strbuf_reset(&buf);
2051 strbuf_addf(&buf, "refs/heads/%s", branch_name);
2052 if (!read_ref(buf.buf, &options.orig_head)) {
2053 die_if_checked_out(buf.buf, 1);
2054 options.head_name = xstrdup(buf.buf);
2055 /* If not is it a valid ref (branch or commit)? */
2056 } else if (!get_oid(branch_name, &options.orig_head))
2057 options.head_name = NULL;
2058 else
2059 die(_("fatal: no such branch/commit '%s'"),
2060 branch_name);
2061 } else if (argc == 0) {
2062 /* Do not need to switch branches, we are already on it. */
2063 options.head_name =
2064 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
2065 &flags));
2066 if (!options.head_name)
2067 die(_("No such ref: %s"), "HEAD");
2068 if (flags & REF_ISSYMREF) {
2069 if (!skip_prefix(options.head_name,
2070 "refs/heads/", &branch_name))
2071 branch_name = options.head_name;
2073 } else {
2074 FREE_AND_NULL(options.head_name);
2075 branch_name = "HEAD";
2077 if (get_oid("HEAD", &options.orig_head))
2078 die(_("Could not resolve HEAD to a revision"));
2079 } else
2080 BUG("unexpected number of arguments left to parse");
2082 if (fork_point > 0) {
2083 struct commit *head =
2084 lookup_commit_reference(the_repository,
2085 &options.orig_head);
2086 options.restrict_revision =
2087 get_fork_point(options.upstream_name, head);
2090 if (repo_read_index(the_repository) < 0)
2091 die(_("could not read index"));
2093 if (options.autostash) {
2094 struct lock_file lock_file = LOCK_INIT;
2095 int fd;
2097 fd = hold_locked_index(&lock_file, 0);
2098 refresh_cache(REFRESH_QUIET);
2099 if (0 <= fd)
2100 repo_update_index_if_able(the_repository, &lock_file);
2101 rollback_lock_file(&lock_file);
2103 if (has_unstaged_changes(the_repository, 1) ||
2104 has_uncommitted_changes(the_repository, 1)) {
2105 const char *autostash =
2106 state_dir_path("autostash", &options);
2107 struct child_process stash = CHILD_PROCESS_INIT;
2108 struct object_id oid;
2110 argv_array_pushl(&stash.args,
2111 "stash", "create", "autostash", NULL);
2112 stash.git_cmd = 1;
2113 stash.no_stdin = 1;
2114 strbuf_reset(&buf);
2115 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
2116 die(_("Cannot autostash"));
2117 strbuf_trim_trailing_newline(&buf);
2118 if (get_oid(buf.buf, &oid))
2119 die(_("Unexpected stash response: '%s'"),
2120 buf.buf);
2121 strbuf_reset(&buf);
2122 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
2124 if (safe_create_leading_directories_const(autostash))
2125 die(_("Could not create directory for '%s'"),
2126 options.state_dir);
2127 write_file(autostash, "%s", oid_to_hex(&oid));
2128 printf(_("Created autostash: %s\n"), buf.buf);
2129 if (reset_head(NULL, "reset --hard",
2130 NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
2131 die(_("could not reset --hard"));
2133 if (discard_index(the_repository->index) < 0 ||
2134 repo_read_index(the_repository) < 0)
2135 die(_("could not read index"));
2139 if (require_clean_work_tree(the_repository, "rebase",
2140 _("Please commit or stash them."), 1, 1)) {
2141 ret = 1;
2142 goto cleanup;
2146 * Now we are rebasing commits upstream..orig_head (or with --root,
2147 * everything leading up to orig_head) on top of onto.
2151 * Check if we are already based on onto with linear history,
2152 * in which case we could fast-forward without replacing the commits
2153 * with new commits recreated by replaying their changes.
2155 * Note that can_fast_forward() initializes merge_base, so we have to
2156 * call it before checking allow_preemptive_ff.
2158 if (can_fast_forward(options.onto, options.upstream, options.restrict_revision,
2159 &options.orig_head, &merge_base) &&
2160 allow_preemptive_ff) {
2161 int flag;
2163 if (!(options.flags & REBASE_FORCE)) {
2164 /* Lazily switch to the target branch if needed... */
2165 if (options.switch_to) {
2166 strbuf_reset(&buf);
2167 strbuf_addf(&buf, "%s: checkout %s",
2168 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
2169 options.switch_to);
2170 if (reset_head(&options.orig_head, "checkout",
2171 options.head_name,
2172 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2173 NULL, buf.buf) < 0) {
2174 ret = !!error(_("could not switch to "
2175 "%s"),
2176 options.switch_to);
2177 goto cleanup;
2181 if (!(options.flags & REBASE_NO_QUIET))
2182 ; /* be quiet */
2183 else if (!strcmp(branch_name, "HEAD") &&
2184 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2185 puts(_("HEAD is up to date."));
2186 else
2187 printf(_("Current branch %s is up to date.\n"),
2188 branch_name);
2189 ret = !!finish_rebase(&options);
2190 goto cleanup;
2191 } else if (!(options.flags & REBASE_NO_QUIET))
2192 ; /* be quiet */
2193 else if (!strcmp(branch_name, "HEAD") &&
2194 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2195 puts(_("HEAD is up to date, rebase forced."));
2196 else
2197 printf(_("Current branch %s is up to date, rebase "
2198 "forced.\n"), branch_name);
2201 /* If a hook exists, give it a chance to interrupt*/
2202 if (!ok_to_skip_pre_rebase &&
2203 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
2204 argc ? argv[0] : NULL, NULL))
2205 die(_("The pre-rebase hook refused to rebase."));
2207 if (options.flags & REBASE_DIFFSTAT) {
2208 struct diff_options opts;
2210 if (options.flags & REBASE_VERBOSE) {
2211 if (is_null_oid(&merge_base))
2212 printf(_("Changes to %s:\n"),
2213 oid_to_hex(&options.onto->object.oid));
2214 else
2215 printf(_("Changes from %s to %s:\n"),
2216 oid_to_hex(&merge_base),
2217 oid_to_hex(&options.onto->object.oid));
2220 /* We want color (if set), but no pager */
2221 diff_setup(&opts);
2222 opts.stat_width = -1; /* use full terminal width */
2223 opts.stat_graph_width = -1; /* respect statGraphWidth config */
2224 opts.output_format |=
2225 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
2226 opts.detect_rename = DIFF_DETECT_RENAME;
2227 diff_setup_done(&opts);
2228 diff_tree_oid(is_null_oid(&merge_base) ?
2229 the_hash_algo->empty_tree : &merge_base,
2230 &options.onto->object.oid, "", &opts);
2231 diffcore_std(&opts);
2232 diff_flush(&opts);
2235 if (is_merge(&options))
2236 goto run_rebase;
2238 /* Detach HEAD and reset the tree */
2239 if (options.flags & REBASE_NO_QUIET)
2240 printf(_("First, rewinding head to replay your work on top of "
2241 "it...\n"));
2243 strbuf_addf(&msg, "%s: checkout %s",
2244 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
2245 if (reset_head(&options.onto->object.oid, "checkout", NULL,
2246 RESET_HEAD_DETACH | RESET_ORIG_HEAD |
2247 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2248 NULL, msg.buf))
2249 die(_("Could not detach HEAD"));
2250 strbuf_release(&msg);
2253 * If the onto is a proper descendant of the tip of the branch, then
2254 * we just fast-forwarded.
2256 strbuf_reset(&msg);
2257 if (oideq(&merge_base, &options.orig_head)) {
2258 printf(_("Fast-forwarded %s to %s.\n"),
2259 branch_name, options.onto_name);
2260 strbuf_addf(&msg, "rebase finished: %s onto %s",
2261 options.head_name ? options.head_name : "detached HEAD",
2262 oid_to_hex(&options.onto->object.oid));
2263 reset_head(NULL, "Fast-forwarded", options.head_name,
2264 RESET_HEAD_REFS_ONLY, "HEAD", msg.buf);
2265 strbuf_release(&msg);
2266 ret = !!finish_rebase(&options);
2267 goto cleanup;
2270 strbuf_addf(&revisions, "%s..%s",
2271 options.root ? oid_to_hex(&options.onto->object.oid) :
2272 (options.restrict_revision ?
2273 oid_to_hex(&options.restrict_revision->object.oid) :
2274 oid_to_hex(&options.upstream->object.oid)),
2275 oid_to_hex(&options.orig_head));
2277 options.revisions = revisions.buf;
2279 run_rebase:
2280 ret = !!run_specific_rebase(&options, action);
2282 cleanup:
2283 strbuf_release(&buf);
2284 strbuf_release(&revisions);
2285 free(options.head_name);
2286 free(options.gpg_sign_opt);
2287 free(options.cmd);
2288 free(squash_onto_name);
2289 return ret;