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