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