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