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