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