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