]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/rebase.c
Merge branch 'jc/orphan-unborn'
[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 int status;
586 char *rebased_patches;
587
588 am.git_cmd = 1;
589 strvec_push(&am.args, "am");
590 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
591 opts->reflog_action);
592 if (opts->action == ACTION_CONTINUE) {
593 strvec_push(&am.args, "--resolved");
594 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
595 if (opts->gpg_sign_opt)
596 strvec_push(&am.args, opts->gpg_sign_opt);
597 status = run_command(&am);
598 if (status)
599 return status;
600
601 return move_to_original_branch(opts);
602 }
603 if (opts->action == ACTION_SKIP) {
604 strvec_push(&am.args, "--skip");
605 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
606 status = run_command(&am);
607 if (status)
608 return status;
609
610 return move_to_original_branch(opts);
611 }
612 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
613 strvec_push(&am.args, "--show-current-patch");
614 return run_command(&am);
615 }
616
617 rebased_patches = xstrdup(git_path("rebased-patches"));
618 format_patch.out = open(rebased_patches,
619 O_WRONLY | O_CREAT | O_TRUNC, 0666);
620 if (format_patch.out < 0) {
621 status = error_errno(_("could not open '%s' for writing"),
622 rebased_patches);
623 free(rebased_patches);
624 strvec_clear(&am.args);
625 return status;
626 }
627
628 format_patch.git_cmd = 1;
629 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
630 "--full-index", "--cherry-pick", "--right-only",
631 "--default-prefix", "--no-renames",
632 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
633 "--no-base", NULL);
634 if (opts->git_format_patch_opt.len)
635 strvec_split(&format_patch.args,
636 opts->git_format_patch_opt.buf);
637 strvec_pushf(&format_patch.args, "%s...%s",
638 oid_to_hex(opts->root ?
639 /* this is now equivalent to !opts->upstream */
640 &opts->onto->object.oid :
641 &opts->upstream->object.oid),
642 oid_to_hex(&opts->orig_head->object.oid));
643 if (opts->restrict_revision)
644 strvec_pushf(&format_patch.args, "^%s",
645 oid_to_hex(&opts->restrict_revision->object.oid));
646
647 status = run_command(&format_patch);
648 if (status) {
649 struct reset_head_opts ropts = { 0 };
650 unlink(rebased_patches);
651 free(rebased_patches);
652 strvec_clear(&am.args);
653
654 ropts.oid = &opts->orig_head->object.oid;
655 ropts.branch = opts->head_name;
656 ropts.default_reflog_action = opts->reflog_action;
657 reset_head(the_repository, &ropts);
658 error(_("\ngit encountered an error while preparing the "
659 "patches to replay\n"
660 "these revisions:\n"
661 "\n %s\n\n"
662 "As a result, git cannot rebase them."),
663 opts->revisions);
664
665 return status;
666 }
667
668 am.in = open(rebased_patches, O_RDONLY);
669 if (am.in < 0) {
670 status = error_errno(_("could not open '%s' for reading"),
671 rebased_patches);
672 free(rebased_patches);
673 strvec_clear(&am.args);
674 return status;
675 }
676
677 strvec_pushv(&am.args, opts->git_am_opts.v);
678 strvec_push(&am.args, "--rebasing");
679 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
680 strvec_push(&am.args, "--patch-format=mboxrd");
681 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
682 strvec_push(&am.args, "--rerere-autoupdate");
683 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
684 strvec_push(&am.args, "--no-rerere-autoupdate");
685 if (opts->gpg_sign_opt)
686 strvec_push(&am.args, opts->gpg_sign_opt);
687 status = run_command(&am);
688 unlink(rebased_patches);
689 free(rebased_patches);
690
691 if (!status) {
692 return move_to_original_branch(opts);
693 }
694
695 if (is_directory(opts->state_dir))
696 rebase_write_basic_state(opts);
697
698 return status;
699 }
700
701 static int run_specific_rebase(struct rebase_options *opts)
702 {
703 int status;
704
705 if (opts->type == REBASE_MERGE) {
706 /* Run sequencer-based rebase */
707 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
708 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT))
709 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
710 if (opts->gpg_sign_opt) {
711 /* remove the leading "-S" */
712 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
713 free(opts->gpg_sign_opt);
714 opts->gpg_sign_opt = tmp;
715 }
716
717 status = run_sequencer_rebase(opts);
718 } else if (opts->type == REBASE_APPLY)
719 status = run_am(opts);
720 else
721 BUG("Unhandled rebase type %d", opts->type);
722
723 if (opts->dont_finish_rebase)
724 ; /* do nothing */
725 else if (opts->type == REBASE_MERGE)
726 ; /* merge backend cleans up after itself */
727 else if (status == 0) {
728 if (!file_exists(state_dir_path("stopped-sha", opts)))
729 finish_rebase(opts);
730 } else if (status == 2) {
731 struct strbuf dir = STRBUF_INIT;
732
733 apply_autostash(state_dir_path("autostash", opts));
734 strbuf_addstr(&dir, opts->state_dir);
735 remove_dir_recursively(&dir, 0);
736 strbuf_release(&dir);
737 die("Nothing to do");
738 }
739
740 return status ? -1 : 0;
741 }
742
743 static void parse_rebase_merges_value(struct rebase_options *options, const char *value)
744 {
745 if (!strcmp("no-rebase-cousins", value))
746 options->rebase_cousins = 0;
747 else if (!strcmp("rebase-cousins", value))
748 options->rebase_cousins = 1;
749 else
750 die(_("Unknown rebase-merges mode: %s"), value);
751 }
752
753 static int rebase_config(const char *var, const char *value,
754 const struct config_context *ctx, void *data)
755 {
756 struct rebase_options *opts = data;
757
758 if (!strcmp(var, "rebase.stat")) {
759 if (git_config_bool(var, value))
760 opts->flags |= REBASE_DIFFSTAT;
761 else
762 opts->flags &= ~REBASE_DIFFSTAT;
763 return 0;
764 }
765
766 if (!strcmp(var, "rebase.autosquash")) {
767 opts->config_autosquash = git_config_bool(var, value);
768 return 0;
769 }
770
771 if (!strcmp(var, "commit.gpgsign")) {
772 free(opts->gpg_sign_opt);
773 opts->gpg_sign_opt = git_config_bool(var, value) ?
774 xstrdup("-S") : NULL;
775 return 0;
776 }
777
778 if (!strcmp(var, "rebase.autostash")) {
779 opts->autostash = git_config_bool(var, value);
780 return 0;
781 }
782
783 if (!strcmp(var, "rebase.rebasemerges")) {
784 opts->config_rebase_merges = git_parse_maybe_bool(value);
785 if (opts->config_rebase_merges < 0) {
786 opts->config_rebase_merges = 1;
787 parse_rebase_merges_value(opts, value);
788 } else {
789 opts->rebase_cousins = 0;
790 }
791 return 0;
792 }
793
794 if (!strcmp(var, "rebase.updaterefs")) {
795 opts->config_update_refs = git_config_bool(var, value);
796 return 0;
797 }
798
799 if (!strcmp(var, "rebase.reschedulefailedexec")) {
800 opts->reschedule_failed_exec = git_config_bool(var, value);
801 return 0;
802 }
803
804 if (!strcmp(var, "rebase.forkpoint")) {
805 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
806 return 0;
807 }
808
809 if (!strcmp(var, "rebase.backend")) {
810 return git_config_string(&opts->default_backend, var, value);
811 }
812
813 return git_default_config(var, value, ctx, data);
814 }
815
816 static int checkout_up_to_date(struct rebase_options *options)
817 {
818 struct strbuf buf = STRBUF_INIT;
819 struct reset_head_opts ropts = { 0 };
820 int ret = 0;
821
822 strbuf_addf(&buf, "%s: checkout %s",
823 options->reflog_action, options->switch_to);
824 ropts.oid = &options->orig_head->object.oid;
825 ropts.branch = options->head_name;
826 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
827 if (!ropts.branch)
828 ropts.flags |= RESET_HEAD_DETACH;
829 ropts.head_msg = buf.buf;
830 if (reset_head(the_repository, &ropts) < 0)
831 ret = error(_("could not switch to %s"), options->switch_to);
832 strbuf_release(&buf);
833
834 return ret;
835 }
836
837 /*
838 * Determines whether the commits in from..to are linear, i.e. contain
839 * no merge commits. This function *expects* `from` to be an ancestor of
840 * `to`.
841 */
842 static int is_linear_history(struct commit *from, struct commit *to)
843 {
844 while (to && to != from) {
845 repo_parse_commit(the_repository, to);
846 if (!to->parents)
847 return 1;
848 if (to->parents->next)
849 return 0;
850 to = to->parents->item;
851 }
852 return 1;
853 }
854
855 static int can_fast_forward(struct commit *onto, struct commit *upstream,
856 struct commit *restrict_revision,
857 struct commit *head, struct object_id *branch_base)
858 {
859 struct commit_list *merge_bases = NULL;
860 int res = 0;
861
862 if (is_null_oid(branch_base))
863 goto done; /* fill_branch_base() found multiple merge bases */
864
865 if (!oideq(branch_base, &onto->object.oid))
866 goto done;
867
868 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
869 goto done;
870
871 if (!upstream)
872 goto done;
873
874 merge_bases = repo_get_merge_bases(the_repository, upstream, head);
875 if (!merge_bases || merge_bases->next)
876 goto done;
877
878 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
879 goto done;
880
881 res = 1;
882
883 done:
884 free_commit_list(merge_bases);
885 return res && is_linear_history(onto, head);
886 }
887
888 static void fill_branch_base(struct rebase_options *options,
889 struct object_id *branch_base)
890 {
891 struct commit_list *merge_bases = NULL;
892
893 merge_bases = repo_get_merge_bases(the_repository, options->onto,
894 options->orig_head);
895 if (!merge_bases || merge_bases->next)
896 oidcpy(branch_base, null_oid());
897 else
898 oidcpy(branch_base, &merge_bases->item->object.oid);
899
900 free_commit_list(merge_bases);
901 }
902
903 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
904 {
905 struct rebase_options *opts = opt->value;
906
907 BUG_ON_OPT_NEG(unset);
908 BUG_ON_OPT_ARG(arg);
909
910 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
911 die(_("apply options and merge options cannot be used together"));
912
913 opts->type = REBASE_APPLY;
914
915 return 0;
916 }
917
918 /* -i followed by -m is still -i */
919 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
920 {
921 struct rebase_options *opts = opt->value;
922
923 BUG_ON_OPT_NEG(unset);
924 BUG_ON_OPT_ARG(arg);
925
926 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
927 die(_("apply options and merge options cannot be used together"));
928
929 opts->type = REBASE_MERGE;
930
931 return 0;
932 }
933
934 /* -i followed by -r is still explicitly interactive, but -r alone is not */
935 static int parse_opt_interactive(const struct option *opt, const char *arg,
936 int unset)
937 {
938 struct rebase_options *opts = opt->value;
939
940 BUG_ON_OPT_NEG(unset);
941 BUG_ON_OPT_ARG(arg);
942
943 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
944 die(_("apply options and merge options cannot be used together"));
945
946 opts->type = REBASE_MERGE;
947 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
948
949 return 0;
950 }
951
952 static enum empty_type parse_empty_value(const char *value)
953 {
954 if (!strcasecmp(value, "drop"))
955 return EMPTY_DROP;
956 else if (!strcasecmp(value, "keep"))
957 return EMPTY_KEEP;
958 else if (!strcasecmp(value, "ask"))
959 return EMPTY_ASK;
960
961 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
962 }
963
964 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
965 int unset)
966 {
967 struct rebase_options *opts = opt->value;
968
969 BUG_ON_OPT_ARG(arg);
970
971 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
972 opts->keep_empty = !unset;
973 return 0;
974 }
975
976 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
977 {
978 struct rebase_options *options = opt->value;
979 enum empty_type value = parse_empty_value(arg);
980
981 BUG_ON_OPT_NEG(unset);
982
983 options->empty = value;
984 return 0;
985 }
986
987 static int parse_opt_rebase_merges(const struct option *opt, const char *arg, int unset)
988 {
989 struct rebase_options *options = opt->value;
990
991 options->rebase_merges = !unset;
992 options->rebase_cousins = 0;
993
994 if (arg) {
995 if (!*arg) {
996 warning(_("--rebase-merges with an empty string "
997 "argument is deprecated and will stop "
998 "working in a future version of Git. Use "
999 "--rebase-merges without an argument "
1000 "instead, which does the same thing."));
1001 return 0;
1002 }
1003 parse_rebase_merges_value(options, arg);
1004 }
1005
1006 return 0;
1007 }
1008
1009 static void NORETURN error_on_missing_default_upstream(void)
1010 {
1011 struct branch *current_branch = branch_get(NULL);
1012
1013 printf(_("%s\n"
1014 "Please specify which branch you want to rebase against.\n"
1015 "See git-rebase(1) for details.\n"
1016 "\n"
1017 " git rebase '<branch>'\n"
1018 "\n"),
1019 current_branch ? _("There is no tracking information for "
1020 "the current branch.") :
1021 _("You are not currently on a branch."));
1022
1023 if (current_branch) {
1024 const char *remote = current_branch->remote_name;
1025
1026 if (!remote)
1027 remote = _("<remote>");
1028
1029 printf(_("If you wish to set tracking information for this "
1030 "branch you can do so with:\n"
1031 "\n"
1032 " git branch --set-upstream-to=%s/<branch> %s\n"
1033 "\n"),
1034 remote, current_branch->name);
1035 }
1036 exit(1);
1037 }
1038
1039 static int check_exec_cmd(const char *cmd)
1040 {
1041 if (strchr(cmd, '\n'))
1042 return error(_("exec commands cannot contain newlines"));
1043
1044 /* Does the command consist purely of whitespace? */
1045 if (!cmd[strspn(cmd, " \t\r\f\v")])
1046 return error(_("empty exec command"));
1047
1048 return 0;
1049 }
1050
1051 int cmd_rebase(int argc, const char **argv, const char *prefix)
1052 {
1053 struct rebase_options options = REBASE_OPTIONS_INIT;
1054 const char *branch_name;
1055 int ret, flags, total_argc, in_progress = 0;
1056 int keep_base = 0;
1057 int ok_to_skip_pre_rebase = 0;
1058 struct strbuf msg = STRBUF_INIT;
1059 struct strbuf revisions = STRBUF_INIT;
1060 struct strbuf buf = STRBUF_INIT;
1061 struct object_id branch_base;
1062 int ignore_whitespace = 0;
1063 const char *gpg_sign = NULL;
1064 struct object_id squash_onto;
1065 char *squash_onto_name = NULL;
1066 char *keep_base_onto_name = NULL;
1067 int reschedule_failed_exec = -1;
1068 int allow_preemptive_ff = 1;
1069 int preserve_merges_selected = 0;
1070 struct reset_head_opts ropts = { 0 };
1071 struct option builtin_rebase_options[] = {
1072 OPT_STRING(0, "onto", &options.onto_name,
1073 N_("revision"),
1074 N_("rebase onto given branch instead of upstream")),
1075 OPT_BOOL(0, "keep-base", &keep_base,
1076 N_("use the merge-base of upstream and branch as the current base")),
1077 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1078 N_("allow pre-rebase hook to run")),
1079 OPT_NEGBIT('q', "quiet", &options.flags,
1080 N_("be quiet. implies --no-stat"),
1081 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1082 OPT_BIT('v', "verbose", &options.flags,
1083 N_("display a diffstat of what changed upstream"),
1084 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1085 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1086 N_("do not show diffstat of what changed upstream"),
1087 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1088 OPT_BOOL(0, "signoff", &options.signoff,
1089 N_("add a Signed-off-by trailer to each commit")),
1090 OPT_BOOL(0, "committer-date-is-author-date",
1091 &options.committer_date_is_author_date,
1092 N_("make committer date match author date")),
1093 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1094 N_("ignore author date and use current date")),
1095 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1096 N_("synonym of --reset-author-date")),
1097 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1098 N_("passed to 'git apply'"), 0),
1099 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1100 N_("ignore changes in whitespace")),
1101 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1102 N_("action"), N_("passed to 'git apply'"), 0),
1103 OPT_BIT('f', "force-rebase", &options.flags,
1104 N_("cherry-pick all commits, even if unchanged"),
1105 REBASE_FORCE),
1106 OPT_BIT(0, "no-ff", &options.flags,
1107 N_("cherry-pick all commits, even if unchanged"),
1108 REBASE_FORCE),
1109 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1110 ACTION_CONTINUE),
1111 OPT_CMDMODE(0, "skip", &options.action,
1112 N_("skip current patch and continue"), ACTION_SKIP),
1113 OPT_CMDMODE(0, "abort", &options.action,
1114 N_("abort and check out the original branch"),
1115 ACTION_ABORT),
1116 OPT_CMDMODE(0, "quit", &options.action,
1117 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1118 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1119 "during an interactive rebase"), ACTION_EDIT_TODO),
1120 OPT_CMDMODE(0, "show-current-patch", &options.action,
1121 N_("show the patch file being applied or merged"),
1122 ACTION_SHOW_CURRENT_PATCH),
1123 OPT_CALLBACK_F(0, "apply", &options, NULL,
1124 N_("use apply strategies to rebase"),
1125 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1126 parse_opt_am),
1127 OPT_CALLBACK_F('m', "merge", &options, NULL,
1128 N_("use merging strategies to rebase"),
1129 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1130 parse_opt_merge),
1131 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1132 N_("let the user edit the list of commits to rebase"),
1133 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1134 parse_opt_interactive),
1135 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1136 N_("(REMOVED) was: try to recreate merges "
1137 "instead of ignoring them"),
1138 1, PARSE_OPT_HIDDEN),
1139 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1140 OPT_CALLBACK_F(0, "empty", &options, "(drop|keep|ask)",
1141 N_("how to handle commits that become empty"),
1142 PARSE_OPT_NONEG, parse_opt_empty),
1143 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1144 N_("keep commits which start empty"),
1145 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1146 parse_opt_keep_empty),
1147 OPT_BOOL(0, "autosquash", &options.autosquash,
1148 N_("move commits that begin with "
1149 "squash!/fixup! under -i")),
1150 OPT_BOOL(0, "update-refs", &options.update_refs,
1151 N_("update branches that point to commits "
1152 "that are being rebased")),
1153 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1154 N_("GPG-sign commits"),
1155 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1156 OPT_AUTOSTASH(&options.autostash),
1157 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1158 N_("add exec lines after each commit of the "
1159 "editable list")),
1160 OPT_BOOL_F(0, "allow-empty-message",
1161 &options.allow_empty_message,
1162 N_("allow rebasing commits with empty messages"),
1163 PARSE_OPT_HIDDEN),
1164 OPT_CALLBACK_F('r', "rebase-merges", &options, N_("mode"),
1165 N_("try to rebase merges instead of skipping them"),
1166 PARSE_OPT_OPTARG, parse_opt_rebase_merges),
1167 OPT_BOOL(0, "fork-point", &options.fork_point,
1168 N_("use 'merge-base --fork-point' to refine upstream")),
1169 OPT_STRING('s', "strategy", &options.strategy,
1170 N_("strategy"), N_("use the given merge strategy")),
1171 OPT_STRING_LIST('X', "strategy-option", &options.strategy_opts,
1172 N_("option"),
1173 N_("pass the argument through to the merge "
1174 "strategy")),
1175 OPT_BOOL(0, "root", &options.root,
1176 N_("rebase all reachable commits up to the root(s)")),
1177 OPT_BOOL(0, "reschedule-failed-exec",
1178 &reschedule_failed_exec,
1179 N_("automatically re-schedule any `exec` that fails")),
1180 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1181 N_("apply all changes, even those already present upstream")),
1182 OPT_END(),
1183 };
1184 int i;
1185
1186 if (argc == 2 && !strcmp(argv[1], "-h"))
1187 usage_with_options(builtin_rebase_usage,
1188 builtin_rebase_options);
1189
1190 prepare_repo_settings(the_repository);
1191 the_repository->settings.command_requires_full_index = 0;
1192
1193 git_config(rebase_config, &options);
1194 /* options.gpg_sign_opt will be either "-S" or NULL */
1195 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1196 FREE_AND_NULL(options.gpg_sign_opt);
1197
1198 strbuf_reset(&buf);
1199 strbuf_addf(&buf, "%s/applying", apply_dir());
1200 if(file_exists(buf.buf))
1201 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1202
1203 if (is_directory(apply_dir())) {
1204 options.type = REBASE_APPLY;
1205 options.state_dir = apply_dir();
1206 } else if (is_directory(merge_dir())) {
1207 strbuf_reset(&buf);
1208 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1209 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1210 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1211 "Use `git rebase --abort` to terminate current rebase.\n"
1212 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1213 } else {
1214 strbuf_reset(&buf);
1215 strbuf_addf(&buf, "%s/interactive", merge_dir());
1216 options.type = REBASE_MERGE;
1217 if (file_exists(buf.buf))
1218 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1219 }
1220 options.state_dir = merge_dir();
1221 }
1222
1223 if (options.type != REBASE_UNSPECIFIED)
1224 in_progress = 1;
1225
1226 total_argc = argc;
1227 argc = parse_options(argc, argv, prefix,
1228 builtin_rebase_options,
1229 builtin_rebase_usage, 0);
1230
1231 if (preserve_merges_selected)
1232 die(_("--preserve-merges was replaced by --rebase-merges\n"
1233 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1234 "which is no longer supported; use 'merges' instead"));
1235
1236 if (options.action != ACTION_NONE && total_argc != 2) {
1237 usage_with_options(builtin_rebase_usage,
1238 builtin_rebase_options);
1239 }
1240
1241 if (argc > 2)
1242 usage_with_options(builtin_rebase_usage,
1243 builtin_rebase_options);
1244
1245 if (keep_base) {
1246 if (options.onto_name)
1247 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1248 if (options.root)
1249 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1250 /*
1251 * --keep-base defaults to --no-fork-point to keep the
1252 * base the same.
1253 */
1254 if (options.fork_point < 0)
1255 options.fork_point = 0;
1256 }
1257 if (options.root && options.fork_point > 0)
1258 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1259
1260 if (options.action != ACTION_NONE && !in_progress)
1261 die(_("No rebase in progress?"));
1262
1263 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1264 die(_("The --edit-todo action can only be used during "
1265 "interactive rebase."));
1266
1267 if (trace2_is_enabled()) {
1268 if (is_merge(&options))
1269 trace2_cmd_mode("interactive");
1270 else if (options.exec.nr)
1271 trace2_cmd_mode("interactive-exec");
1272 else
1273 trace2_cmd_mode(action_names[options.action]);
1274 }
1275
1276 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1277 options.reflog_action =
1278 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1279
1280 switch (options.action) {
1281 case ACTION_CONTINUE: {
1282 struct object_id head;
1283 struct lock_file lock_file = LOCK_INIT;
1284 int fd;
1285
1286 /* Sanity check */
1287 if (repo_get_oid(the_repository, "HEAD", &head))
1288 die(_("Cannot read HEAD"));
1289
1290 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1291 if (repo_read_index(the_repository) < 0)
1292 die(_("could not read index"));
1293 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1294 NULL);
1295 if (0 <= fd)
1296 repo_update_index_if_able(the_repository, &lock_file);
1297 rollback_lock_file(&lock_file);
1298
1299 if (has_unstaged_changes(the_repository, 1)) {
1300 puts(_("You must edit all merge conflicts and then\n"
1301 "mark them as resolved using git add"));
1302 exit(1);
1303 }
1304 if (read_basic_state(&options))
1305 exit(1);
1306 goto run_rebase;
1307 }
1308 case ACTION_SKIP: {
1309 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1310
1311 rerere_clear(the_repository, &merge_rr);
1312 string_list_clear(&merge_rr, 1);
1313 ropts.flags = RESET_HEAD_HARD;
1314 if (reset_head(the_repository, &ropts) < 0)
1315 die(_("could not discard worktree changes"));
1316 remove_branch_state(the_repository, 0);
1317 if (read_basic_state(&options))
1318 exit(1);
1319 goto run_rebase;
1320 }
1321 case ACTION_ABORT: {
1322 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1323 struct strbuf head_msg = STRBUF_INIT;
1324
1325 rerere_clear(the_repository, &merge_rr);
1326 string_list_clear(&merge_rr, 1);
1327
1328 if (read_basic_state(&options))
1329 exit(1);
1330
1331 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1332 options.reflog_action,
1333 options.head_name ? options.head_name
1334 : oid_to_hex(&options.orig_head->object.oid));
1335 ropts.oid = &options.orig_head->object.oid;
1336 ropts.head_msg = head_msg.buf;
1337 ropts.branch = options.head_name;
1338 ropts.flags = RESET_HEAD_HARD;
1339 if (reset_head(the_repository, &ropts) < 0)
1340 die(_("could not move back to %s"),
1341 oid_to_hex(&options.orig_head->object.oid));
1342 strbuf_release(&head_msg);
1343 remove_branch_state(the_repository, 0);
1344 ret = finish_rebase(&options);
1345 goto cleanup;
1346 }
1347 case ACTION_QUIT: {
1348 save_autostash(state_dir_path("autostash", &options));
1349 if (options.type == REBASE_MERGE) {
1350 struct replay_opts replay = REPLAY_OPTS_INIT;
1351
1352 replay.action = REPLAY_INTERACTIVE_REBASE;
1353 ret = sequencer_remove_state(&replay);
1354 replay_opts_release(&replay);
1355 } else {
1356 strbuf_reset(&buf);
1357 strbuf_addstr(&buf, options.state_dir);
1358 ret = remove_dir_recursively(&buf, 0);
1359 if (ret)
1360 error(_("could not remove '%s'"),
1361 options.state_dir);
1362 }
1363 goto cleanup;
1364 }
1365 case ACTION_EDIT_TODO:
1366 options.dont_finish_rebase = 1;
1367 goto run_rebase;
1368 case ACTION_SHOW_CURRENT_PATCH:
1369 options.dont_finish_rebase = 1;
1370 goto run_rebase;
1371 case ACTION_NONE:
1372 break;
1373 default:
1374 BUG("action: %d", options.action);
1375 }
1376
1377 /* Make sure no rebase is in progress */
1378 if (in_progress) {
1379 const char *last_slash = strrchr(options.state_dir, '/');
1380 const char *state_dir_base =
1381 last_slash ? last_slash + 1 : options.state_dir;
1382 const char *cmd_live_rebase =
1383 "git rebase (--continue | --abort | --skip)";
1384 strbuf_reset(&buf);
1385 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1386 die(_("It seems that there is already a %s directory, and\n"
1387 "I wonder if you are in the middle of another rebase. "
1388 "If that is the\n"
1389 "case, please try\n\t%s\n"
1390 "If that is not the case, please\n\t%s\n"
1391 "and run me again. I am stopping in case you still "
1392 "have something\n"
1393 "valuable there.\n"),
1394 state_dir_base, cmd_live_rebase, buf.buf);
1395 }
1396
1397 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1398 (options.action != ACTION_NONE) ||
1399 (options.exec.nr > 0) ||
1400 options.autosquash == 1) {
1401 allow_preemptive_ff = 0;
1402 }
1403 if (options.committer_date_is_author_date || options.ignore_date)
1404 options.flags |= REBASE_FORCE;
1405
1406 for (i = 0; i < options.git_am_opts.nr; i++) {
1407 const char *option = options.git_am_opts.v[i], *p;
1408 if (!strcmp(option, "--whitespace=fix") ||
1409 !strcmp(option, "--whitespace=strip"))
1410 allow_preemptive_ff = 0;
1411 else if (skip_prefix(option, "-C", &p)) {
1412 while (*p)
1413 if (!isdigit(*(p++)))
1414 die(_("switch `C' expects a "
1415 "numerical value"));
1416 } else if (skip_prefix(option, "--whitespace=", &p)) {
1417 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1418 strcmp(p, "error") && strcmp(p, "error-all"))
1419 die("Invalid whitespace option: '%s'", p);
1420 }
1421 }
1422
1423 for (i = 0; i < options.exec.nr; i++)
1424 if (check_exec_cmd(options.exec.items[i].string))
1425 exit(1);
1426
1427 if (!(options.flags & REBASE_NO_QUIET))
1428 strvec_push(&options.git_am_opts, "-q");
1429
1430 if (options.empty != EMPTY_UNSPECIFIED)
1431 imply_merge(&options, "--empty");
1432
1433 if (options.reapply_cherry_picks < 0)
1434 /*
1435 * We default to --no-reapply-cherry-picks unless
1436 * --keep-base is given; when --keep-base is given, we want
1437 * to default to --reapply-cherry-picks.
1438 */
1439 options.reapply_cherry_picks = keep_base;
1440 else if (!keep_base)
1441 /*
1442 * The apply backend always searches for and drops cherry
1443 * picks. This is often not wanted with --keep-base, so
1444 * --keep-base allows --reapply-cherry-picks to be
1445 * simulated by altering the upstream such that
1446 * cherry-picks cannot be detected and thus all commits are
1447 * reapplied. Thus, --[no-]reapply-cherry-picks is
1448 * supported when --keep-base is specified, but not when
1449 * --keep-base is left out.
1450 */
1451 imply_merge(&options, options.reapply_cherry_picks ?
1452 "--reapply-cherry-picks" :
1453 "--no-reapply-cherry-picks");
1454
1455 if (gpg_sign)
1456 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1457
1458 if (options.exec.nr)
1459 imply_merge(&options, "--exec");
1460
1461 if (options.type == REBASE_APPLY) {
1462 if (ignore_whitespace)
1463 strvec_push(&options.git_am_opts,
1464 "--ignore-whitespace");
1465 if (options.committer_date_is_author_date)
1466 strvec_push(&options.git_am_opts,
1467 "--committer-date-is-author-date");
1468 if (options.ignore_date)
1469 strvec_push(&options.git_am_opts, "--ignore-date");
1470 } else {
1471 /* REBASE_MERGE */
1472 if (ignore_whitespace) {
1473 string_list_append(&options.strategy_opts,
1474 "ignore-space-change");
1475 }
1476 }
1477
1478 if (options.strategy_opts.nr && !options.strategy)
1479 options.strategy = "ort";
1480
1481 if (options.strategy) {
1482 options.strategy = xstrdup(options.strategy);
1483 imply_merge(&options, "--strategy");
1484 }
1485
1486 if (options.root && !options.onto_name)
1487 imply_merge(&options, "--root without --onto");
1488
1489 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1490 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1491
1492 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1493 /* all am options except -q are compatible only with --apply */
1494 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1495 if (strcmp(options.git_am_opts.v[i], "-q"))
1496 break;
1497
1498 if (i >= 0 || options.type == REBASE_APPLY) {
1499 if (is_merge(&options))
1500 die(_("apply options and merge options "
1501 "cannot be used together"));
1502 else if (options.rebase_merges == -1 && options.config_rebase_merges == 1)
1503 die(_("apply options are incompatible with rebase.rebaseMerges. Consider adding --no-rebase-merges"));
1504 else if (options.update_refs == -1 && options.config_update_refs == 1)
1505 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1506 else
1507 options.type = REBASE_APPLY;
1508 }
1509 }
1510
1511 if (options.update_refs == 1)
1512 imply_merge(&options, "--update-refs");
1513 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1514 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1515
1516 if (options.rebase_merges == 1)
1517 imply_merge(&options, "--rebase-merges");
1518 options.rebase_merges = (options.rebase_merges >= 0) ? options.rebase_merges :
1519 ((options.config_rebase_merges >= 0) ? options.config_rebase_merges : 0);
1520
1521 if (options.autosquash == 1) {
1522 imply_merge(&options, "--autosquash");
1523 } else if (options.autosquash == -1) {
1524 options.autosquash =
1525 options.config_autosquash &&
1526 (options.flags & REBASE_INTERACTIVE_EXPLICIT);
1527 }
1528
1529 if (options.type == REBASE_UNSPECIFIED) {
1530 if (!strcmp(options.default_backend, "merge"))
1531 options.type = REBASE_MERGE;
1532 else if (!strcmp(options.default_backend, "apply"))
1533 options.type = REBASE_APPLY;
1534 else
1535 die(_("Unknown rebase backend: %s"),
1536 options.default_backend);
1537 }
1538
1539 if (options.type == REBASE_MERGE &&
1540 !options.strategy &&
1541 getenv("GIT_TEST_MERGE_ALGORITHM"))
1542 options.strategy = xstrdup(getenv("GIT_TEST_MERGE_ALGORITHM"));
1543
1544 switch (options.type) {
1545 case REBASE_MERGE:
1546 options.state_dir = merge_dir();
1547 break;
1548 case REBASE_APPLY:
1549 options.state_dir = apply_dir();
1550 break;
1551 default:
1552 BUG("options.type was just set above; should be unreachable.");
1553 }
1554
1555 if (options.empty == EMPTY_UNSPECIFIED) {
1556 if (options.flags & REBASE_INTERACTIVE_EXPLICIT)
1557 options.empty = EMPTY_ASK;
1558 else if (options.exec.nr > 0)
1559 options.empty = EMPTY_KEEP;
1560 else
1561 options.empty = EMPTY_DROP;
1562 }
1563 if (reschedule_failed_exec > 0 && !is_merge(&options))
1564 die(_("--reschedule-failed-exec requires "
1565 "--exec or --interactive"));
1566 if (reschedule_failed_exec >= 0)
1567 options.reschedule_failed_exec = reschedule_failed_exec;
1568
1569 if (options.signoff) {
1570 strvec_push(&options.git_am_opts, "--signoff");
1571 options.flags |= REBASE_FORCE;
1572 }
1573
1574 if (!options.root) {
1575 if (argc < 1) {
1576 struct branch *branch;
1577
1578 branch = branch_get(NULL);
1579 options.upstream_name = branch_get_upstream(branch,
1580 NULL);
1581 if (!options.upstream_name)
1582 error_on_missing_default_upstream();
1583 if (options.fork_point < 0)
1584 options.fork_point = 1;
1585 } else {
1586 options.upstream_name = argv[0];
1587 argc--;
1588 argv++;
1589 if (!strcmp(options.upstream_name, "-"))
1590 options.upstream_name = "@{-1}";
1591 }
1592 options.upstream =
1593 lookup_commit_reference_by_name(options.upstream_name);
1594 if (!options.upstream)
1595 die(_("invalid upstream '%s'"), options.upstream_name);
1596 options.upstream_arg = options.upstream_name;
1597 } else {
1598 if (!options.onto_name) {
1599 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1600 &squash_onto, NULL, NULL) < 0)
1601 die(_("Could not create new root commit"));
1602 options.squash_onto = &squash_onto;
1603 options.onto_name = squash_onto_name =
1604 xstrdup(oid_to_hex(&squash_onto));
1605 } else
1606 options.root_with_onto = 1;
1607
1608 options.upstream_name = NULL;
1609 options.upstream = NULL;
1610 if (argc > 1)
1611 usage_with_options(builtin_rebase_usage,
1612 builtin_rebase_options);
1613 options.upstream_arg = "--root";
1614 }
1615
1616 /*
1617 * If the branch to rebase is given, that is the branch we will rebase
1618 * branch_name -- branch/commit being rebased, or
1619 * HEAD (already detached)
1620 * orig_head -- commit object name of tip of the branch before rebasing
1621 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1622 */
1623 if (argc == 1) {
1624 /* Is it "rebase other branchname" or "rebase other commit"? */
1625 struct object_id branch_oid;
1626 branch_name = argv[0];
1627 options.switch_to = argv[0];
1628
1629 /* Is it a local branch? */
1630 strbuf_reset(&buf);
1631 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1632 if (!read_ref(buf.buf, &branch_oid)) {
1633 die_if_checked_out(buf.buf, 1);
1634 options.head_name = xstrdup(buf.buf);
1635 options.orig_head =
1636 lookup_commit_object(the_repository,
1637 &branch_oid);
1638 /* If not is it a valid ref (branch or commit)? */
1639 } else {
1640 options.orig_head =
1641 lookup_commit_reference_by_name(branch_name);
1642 options.head_name = NULL;
1643 }
1644 if (!options.orig_head)
1645 die(_("no such branch/commit '%s'"), branch_name);
1646 } else if (argc == 0) {
1647 /* Do not need to switch branches, we are already on it. */
1648 options.head_name =
1649 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1650 &flags));
1651 if (!options.head_name)
1652 die(_("No such ref: %s"), "HEAD");
1653 if (flags & REF_ISSYMREF) {
1654 if (!skip_prefix(options.head_name,
1655 "refs/heads/", &branch_name))
1656 branch_name = options.head_name;
1657
1658 } else {
1659 FREE_AND_NULL(options.head_name);
1660 branch_name = "HEAD";
1661 }
1662 options.orig_head = lookup_commit_reference_by_name("HEAD");
1663 if (!options.orig_head)
1664 die(_("Could not resolve HEAD to a commit"));
1665 } else
1666 BUG("unexpected number of arguments left to parse");
1667
1668 /* Make sure the branch to rebase onto is valid. */
1669 if (keep_base) {
1670 strbuf_reset(&buf);
1671 strbuf_addstr(&buf, options.upstream_name);
1672 strbuf_addstr(&buf, "...");
1673 strbuf_addstr(&buf, branch_name);
1674 options.onto_name = keep_base_onto_name = xstrdup(buf.buf);
1675 } else if (!options.onto_name)
1676 options.onto_name = options.upstream_name;
1677 if (strstr(options.onto_name, "...")) {
1678 if (repo_get_oid_mb(the_repository, options.onto_name, &branch_base) < 0) {
1679 if (keep_base)
1680 die(_("'%s': need exactly one merge base with branch"),
1681 options.upstream_name);
1682 else
1683 die(_("'%s': need exactly one merge base"),
1684 options.onto_name);
1685 }
1686 options.onto = lookup_commit_or_die(&branch_base,
1687 options.onto_name);
1688 } else {
1689 options.onto =
1690 lookup_commit_reference_by_name(options.onto_name);
1691 if (!options.onto)
1692 die(_("Does not point to a valid commit '%s'"),
1693 options.onto_name);
1694 fill_branch_base(&options, &branch_base);
1695 }
1696
1697 if (keep_base && options.reapply_cherry_picks)
1698 options.upstream = options.onto;
1699
1700 if (options.fork_point > 0)
1701 options.restrict_revision =
1702 get_fork_point(options.upstream_name, options.orig_head);
1703
1704 if (repo_read_index(the_repository) < 0)
1705 die(_("could not read index"));
1706
1707 if (options.autostash)
1708 create_autostash(the_repository,
1709 state_dir_path("autostash", &options));
1710
1711
1712 if (require_clean_work_tree(the_repository, "rebase",
1713 _("Please commit or stash them."), 1, 1)) {
1714 ret = -1;
1715 goto cleanup;
1716 }
1717
1718 /*
1719 * Now we are rebasing commits upstream..orig_head (or with --root,
1720 * everything leading up to orig_head) on top of onto.
1721 */
1722
1723 /*
1724 * Check if we are already based on onto with linear history,
1725 * in which case we could fast-forward without replacing the commits
1726 * with new commits recreated by replaying their changes.
1727 */
1728 if (allow_preemptive_ff &&
1729 can_fast_forward(options.onto, options.upstream, options.restrict_revision,
1730 options.orig_head, &branch_base)) {
1731 int flag;
1732
1733 if (!(options.flags & REBASE_FORCE)) {
1734 /* Lazily switch to the target branch if needed... */
1735 if (options.switch_to) {
1736 ret = checkout_up_to_date(&options);
1737 if (ret)
1738 goto cleanup;
1739 }
1740
1741 if (!(options.flags & REBASE_NO_QUIET))
1742 ; /* be quiet */
1743 else if (!strcmp(branch_name, "HEAD") &&
1744 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1745 puts(_("HEAD is up to date."));
1746 else
1747 printf(_("Current branch %s is up to date.\n"),
1748 branch_name);
1749 ret = finish_rebase(&options);
1750 goto cleanup;
1751 } else if (!(options.flags & REBASE_NO_QUIET))
1752 ; /* be quiet */
1753 else if (!strcmp(branch_name, "HEAD") &&
1754 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1755 puts(_("HEAD is up to date, rebase forced."));
1756 else
1757 printf(_("Current branch %s is up to date, rebase "
1758 "forced.\n"), branch_name);
1759 }
1760
1761 /* If a hook exists, give it a chance to interrupt*/
1762 if (!ok_to_skip_pre_rebase &&
1763 run_hooks_l("pre-rebase", options.upstream_arg,
1764 argc ? argv[0] : NULL, NULL))
1765 die(_("The pre-rebase hook refused to rebase."));
1766
1767 if (options.flags & REBASE_DIFFSTAT) {
1768 struct diff_options opts;
1769
1770 if (options.flags & REBASE_VERBOSE) {
1771 if (is_null_oid(&branch_base))
1772 printf(_("Changes to %s:\n"),
1773 oid_to_hex(&options.onto->object.oid));
1774 else
1775 printf(_("Changes from %s to %s:\n"),
1776 oid_to_hex(&branch_base),
1777 oid_to_hex(&options.onto->object.oid));
1778 }
1779
1780 /* We want color (if set), but no pager */
1781 repo_diff_setup(the_repository, &opts);
1782 init_diffstat_widths(&opts);
1783 opts.output_format |=
1784 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1785 opts.detect_rename = DIFF_DETECT_RENAME;
1786 diff_setup_done(&opts);
1787 diff_tree_oid(is_null_oid(&branch_base) ?
1788 the_hash_algo->empty_tree : &branch_base,
1789 &options.onto->object.oid, "", &opts);
1790 diffcore_std(&opts);
1791 diff_flush(&opts);
1792 }
1793
1794 if (is_merge(&options))
1795 goto run_rebase;
1796
1797 /* Detach HEAD and reset the tree */
1798 if (options.flags & REBASE_NO_QUIET)
1799 printf(_("First, rewinding head to replay your work on top of "
1800 "it...\n"));
1801
1802 strbuf_addf(&msg, "%s (start): checkout %s",
1803 options.reflog_action, options.onto_name);
1804 ropts.oid = &options.onto->object.oid;
1805 ropts.orig_head = &options.orig_head->object.oid,
1806 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1807 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1808 ropts.head_msg = msg.buf;
1809 ropts.default_reflog_action = options.reflog_action;
1810 if (reset_head(the_repository, &ropts))
1811 die(_("Could not detach HEAD"));
1812 strbuf_release(&msg);
1813
1814 /*
1815 * If the onto is a proper descendant of the tip of the branch, then
1816 * we just fast-forwarded.
1817 */
1818 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1819 printf(_("Fast-forwarded %s to %s.\n"),
1820 branch_name, options.onto_name);
1821 move_to_original_branch(&options);
1822 ret = finish_rebase(&options);
1823 goto cleanup;
1824 }
1825
1826 strbuf_addf(&revisions, "%s..%s",
1827 options.root ? oid_to_hex(&options.onto->object.oid) :
1828 (options.restrict_revision ?
1829 oid_to_hex(&options.restrict_revision->object.oid) :
1830 oid_to_hex(&options.upstream->object.oid)),
1831 oid_to_hex(&options.orig_head->object.oid));
1832
1833 options.revisions = revisions.buf;
1834
1835 run_rebase:
1836 ret = run_specific_rebase(&options);
1837
1838 cleanup:
1839 strbuf_release(&buf);
1840 strbuf_release(&revisions);
1841 free(options.reflog_action);
1842 free(options.head_name);
1843 strvec_clear(&options.git_am_opts);
1844 free(options.gpg_sign_opt);
1845 string_list_clear(&options.exec, 0);
1846 free(options.strategy);
1847 string_list_clear(&options.strategy_opts, 0);
1848 strbuf_release(&options.git_format_patch_opt);
1849 free(squash_onto_name);
1850 free(keep_base_onto_name);
1851 return !!ret;
1852 }