]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/rebase.c
rebase: use strvec_pushf() for format-patch revisions
[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 = -1;
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 goto cleanup;
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 goto cleanup;
271
272 if (!opts->upstream && opts->squash_onto)
273 write_file(path_squash_onto(), "%s\n",
274 oid_to_hex(opts->squash_onto));
275
276 strvec_pushl(&make_script_args, "", revisions, NULL);
277 if (opts->restrict_revision)
278 strvec_pushf(&make_script_args, "^%s",
279 oid_to_hex(&opts->restrict_revision->object.oid));
280
281 ret = sequencer_make_script(the_repository, &todo_list.buf,
282 make_script_args.nr, make_script_args.v,
283 flags);
284
285 if (ret)
286 error(_("could not generate todo list"));
287 else {
288 discard_index(&the_index);
289 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
290 &todo_list))
291 BUG("unusable todo list");
292
293 ret = complete_action(the_repository, &replay, flags,
294 shortrevisions, opts->onto_name, opts->onto,
295 &opts->orig_head->object.oid, &opts->exec,
296 opts->autosquash, opts->update_refs, &todo_list);
297 }
298
299 cleanup:
300 replay_opts_release(&replay);
301 free(revisions);
302 free(shortrevisions);
303 todo_list_release(&todo_list);
304 strvec_clear(&make_script_args);
305
306 return ret;
307 }
308
309 static int run_sequencer_rebase(struct rebase_options *opts)
310 {
311 unsigned flags = 0;
312 int abbreviate_commands = 0, ret = 0;
313
314 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
315
316 flags |= opts->keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
317 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
318 flags |= opts->rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
319 flags |= opts->rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
320 flags |= opts->root_with_onto ? TODO_LIST_ROOT_WITH_ONTO : 0;
321 flags |= opts->reapply_cherry_picks ? TODO_LIST_REAPPLY_CHERRY_PICKS : 0;
322 flags |= opts->flags & REBASE_NO_QUIET ? TODO_LIST_WARN_SKIPPED_CHERRY_PICKS : 0;
323
324 switch (opts->action) {
325 case ACTION_NONE: {
326 if (!opts->onto && !opts->upstream)
327 die(_("a base commit must be provided with --upstream or --onto"));
328
329 ret = do_interactive_rebase(opts, flags);
330 break;
331 }
332 case ACTION_SKIP: {
333 struct string_list merge_rr = STRING_LIST_INIT_DUP;
334
335 rerere_clear(the_repository, &merge_rr);
336 }
337 /* fallthrough */
338 case ACTION_CONTINUE: {
339 struct replay_opts replay_opts = get_replay_opts(opts);
340
341 ret = sequencer_continue(the_repository, &replay_opts);
342 replay_opts_release(&replay_opts);
343 break;
344 }
345 case ACTION_EDIT_TODO:
346 ret = edit_todo_file(flags);
347 break;
348 case ACTION_SHOW_CURRENT_PATCH: {
349 struct child_process cmd = CHILD_PROCESS_INIT;
350
351 cmd.git_cmd = 1;
352 strvec_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
353 ret = run_command(&cmd);
354
355 break;
356 }
357 default:
358 BUG("invalid command '%d'", opts->action);
359 }
360
361 return ret;
362 }
363
364 static void imply_merge(struct rebase_options *opts, const char *option);
365 static int parse_opt_keep_empty(const struct option *opt, const char *arg,
366 int unset)
367 {
368 struct rebase_options *opts = opt->value;
369
370 BUG_ON_OPT_ARG(arg);
371
372 imply_merge(opts, unset ? "--no-keep-empty" : "--keep-empty");
373 opts->keep_empty = !unset;
374 opts->type = REBASE_MERGE;
375 return 0;
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 if (file_exists(state_dir_path("strategy", opts))) {
486 strbuf_reset(&buf);
487 if (!read_oneliner(&buf, state_dir_path("strategy", opts),
488 READ_ONELINER_WARN_MISSING))
489 return -1;
490 free(opts->strategy);
491 opts->strategy = xstrdup(buf.buf);
492 }
493
494 if (file_exists(state_dir_path("strategy_opts", opts))) {
495 strbuf_reset(&buf);
496 if (!read_oneliner(&buf, state_dir_path("strategy_opts", opts),
497 READ_ONELINER_WARN_MISSING))
498 return -1;
499 free(opts->strategy_opts);
500 opts->strategy_opts = xstrdup(buf.buf);
501 }
502
503 strbuf_release(&buf);
504
505 return 0;
506 }
507
508 static int rebase_write_basic_state(struct rebase_options *opts)
509 {
510 write_file(state_dir_path("head-name", opts), "%s",
511 opts->head_name ? opts->head_name : "detached HEAD");
512 write_file(state_dir_path("onto", opts), "%s",
513 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
514 write_file(state_dir_path("orig-head", opts), "%s",
515 oid_to_hex(&opts->orig_head->object.oid));
516 if (!(opts->flags & REBASE_NO_QUIET))
517 write_file(state_dir_path("quiet", opts), "%s", "");
518 if (opts->flags & REBASE_VERBOSE)
519 write_file(state_dir_path("verbose", opts), "%s", "");
520 if (opts->strategy)
521 write_file(state_dir_path("strategy", opts), "%s",
522 opts->strategy);
523 if (opts->strategy_opts)
524 write_file(state_dir_path("strategy_opts", opts), "%s",
525 opts->strategy_opts);
526 if (opts->allow_rerere_autoupdate > 0)
527 write_file(state_dir_path("allow_rerere_autoupdate", opts),
528 "-%s-rerere-autoupdate",
529 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
530 "" : "-no");
531 if (opts->gpg_sign_opt)
532 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
533 opts->gpg_sign_opt);
534 if (opts->signoff)
535 write_file(state_dir_path("signoff", opts), "--signoff");
536
537 return 0;
538 }
539
540 static int finish_rebase(struct rebase_options *opts)
541 {
542 struct strbuf dir = STRBUF_INIT;
543 int ret = 0;
544
545 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
546 unlink(git_path_auto_merge(the_repository));
547 apply_autostash(state_dir_path("autostash", opts));
548 /*
549 * We ignore errors in 'git maintenance run --auto', since the
550 * user should see them.
551 */
552 run_auto_maintenance(!(opts->flags & (REBASE_NO_QUIET|REBASE_VERBOSE)));
553 if (opts->type == REBASE_MERGE) {
554 struct replay_opts replay = REPLAY_OPTS_INIT;
555
556 replay.action = REPLAY_INTERACTIVE_REBASE;
557 ret = sequencer_remove_state(&replay);
558 replay_opts_release(&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 int status;
610 char *rebased_patches;
611
612 am.git_cmd = 1;
613 strvec_push(&am.args, "am");
614 strvec_pushf(&am.env, GIT_REFLOG_ACTION_ENVIRONMENT "=%s (pick)",
615 opts->reflog_action);
616 if (opts->action == ACTION_CONTINUE) {
617 strvec_push(&am.args, "--resolved");
618 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
619 if (opts->gpg_sign_opt)
620 strvec_push(&am.args, opts->gpg_sign_opt);
621 status = run_command(&am);
622 if (status)
623 return status;
624
625 return move_to_original_branch(opts);
626 }
627 if (opts->action == ACTION_SKIP) {
628 strvec_push(&am.args, "--skip");
629 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
630 status = run_command(&am);
631 if (status)
632 return status;
633
634 return move_to_original_branch(opts);
635 }
636 if (opts->action == ACTION_SHOW_CURRENT_PATCH) {
637 strvec_push(&am.args, "--show-current-patch");
638 return run_command(&am);
639 }
640
641 rebased_patches = xstrdup(git_path("rebased-patches"));
642 format_patch.out = open(rebased_patches,
643 O_WRONLY | O_CREAT | O_TRUNC, 0666);
644 if (format_patch.out < 0) {
645 status = error_errno(_("could not open '%s' for writing"),
646 rebased_patches);
647 free(rebased_patches);
648 strvec_clear(&am.args);
649 return status;
650 }
651
652 format_patch.git_cmd = 1;
653 strvec_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
654 "--full-index", "--cherry-pick", "--right-only",
655 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
656 "--no-cover-letter", "--pretty=mboxrd", "--topo-order",
657 "--no-base", NULL);
658 if (opts->git_format_patch_opt.len)
659 strvec_split(&format_patch.args,
660 opts->git_format_patch_opt.buf);
661 strvec_pushf(&format_patch.args, "%s...%s",
662 oid_to_hex(opts->root ?
663 /* this is now equivalent to !opts->upstream */
664 &opts->onto->object.oid :
665 &opts->upstream->object.oid),
666 oid_to_hex(&opts->orig_head->object.oid));
667 if (opts->restrict_revision)
668 strvec_pushf(&format_patch.args, "^%s",
669 oid_to_hex(&opts->restrict_revision->object.oid));
670
671 status = run_command(&format_patch);
672 if (status) {
673 struct reset_head_opts ropts = { 0 };
674 unlink(rebased_patches);
675 free(rebased_patches);
676 strvec_clear(&am.args);
677
678 ropts.oid = &opts->orig_head->object.oid;
679 ropts.branch = opts->head_name;
680 ropts.default_reflog_action = opts->reflog_action;
681 reset_head(the_repository, &ropts);
682 error(_("\ngit encountered an error while preparing the "
683 "patches to replay\n"
684 "these revisions:\n"
685 "\n %s\n\n"
686 "As a result, git cannot rebase them."),
687 opts->revisions);
688
689 return status;
690 }
691
692 am.in = open(rebased_patches, O_RDONLY);
693 if (am.in < 0) {
694 status = error_errno(_("could not open '%s' for reading"),
695 rebased_patches);
696 free(rebased_patches);
697 strvec_clear(&am.args);
698 return status;
699 }
700
701 strvec_pushv(&am.args, opts->git_am_opts.v);
702 strvec_push(&am.args, "--rebasing");
703 strvec_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
704 strvec_push(&am.args, "--patch-format=mboxrd");
705 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
706 strvec_push(&am.args, "--rerere-autoupdate");
707 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
708 strvec_push(&am.args, "--no-rerere-autoupdate");
709 if (opts->gpg_sign_opt)
710 strvec_push(&am.args, opts->gpg_sign_opt);
711 status = run_command(&am);
712 unlink(rebased_patches);
713 free(rebased_patches);
714
715 if (!status) {
716 return move_to_original_branch(opts);
717 }
718
719 if (is_directory(opts->state_dir))
720 rebase_write_basic_state(opts);
721
722 return status;
723 }
724
725 static int run_specific_rebase(struct rebase_options *opts)
726 {
727 int status;
728
729 if (opts->type == REBASE_MERGE) {
730 /* Run sequencer-based rebase */
731 setenv("GIT_CHERRY_PICK_HELP", resolvemsg, 1);
732 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
733 setenv("GIT_SEQUENCE_EDITOR", ":", 1);
734 opts->autosquash = 0;
735 }
736 if (opts->gpg_sign_opt) {
737 /* remove the leading "-S" */
738 char *tmp = xstrdup(opts->gpg_sign_opt + 2);
739 free(opts->gpg_sign_opt);
740 opts->gpg_sign_opt = tmp;
741 }
742
743 status = run_sequencer_rebase(opts);
744 } else if (opts->type == REBASE_APPLY)
745 status = run_am(opts);
746 else
747 BUG("Unhandled rebase type %d", opts->type);
748
749 if (opts->dont_finish_rebase)
750 ; /* do nothing */
751 else if (opts->type == REBASE_MERGE)
752 ; /* merge backend cleans up after itself */
753 else if (status == 0) {
754 if (!file_exists(state_dir_path("stopped-sha", opts)))
755 finish_rebase(opts);
756 } else if (status == 2) {
757 struct strbuf dir = STRBUF_INIT;
758
759 apply_autostash(state_dir_path("autostash", opts));
760 strbuf_addstr(&dir, opts->state_dir);
761 remove_dir_recursively(&dir, 0);
762 strbuf_release(&dir);
763 die("Nothing to do");
764 }
765
766 return status ? -1 : 0;
767 }
768
769 static int rebase_config(const char *var, const char *value, void *data)
770 {
771 struct rebase_options *opts = data;
772
773 if (!strcmp(var, "rebase.stat")) {
774 if (git_config_bool(var, value))
775 opts->flags |= REBASE_DIFFSTAT;
776 else
777 opts->flags &= ~REBASE_DIFFSTAT;
778 return 0;
779 }
780
781 if (!strcmp(var, "rebase.autosquash")) {
782 opts->config_autosquash = git_config_bool(var, value);
783 return 0;
784 }
785
786 if (!strcmp(var, "commit.gpgsign")) {
787 free(opts->gpg_sign_opt);
788 opts->gpg_sign_opt = git_config_bool(var, value) ?
789 xstrdup("-S") : NULL;
790 return 0;
791 }
792
793 if (!strcmp(var, "rebase.autostash")) {
794 opts->autostash = git_config_bool(var, value);
795 return 0;
796 }
797
798 if (!strcmp(var, "rebase.updaterefs")) {
799 opts->config_update_refs = git_config_bool(var, value);
800 return 0;
801 }
802
803 if (!strcmp(var, "rebase.reschedulefailedexec")) {
804 opts->reschedule_failed_exec = git_config_bool(var, value);
805 return 0;
806 }
807
808 if (!strcmp(var, "rebase.forkpoint")) {
809 opts->fork_point = git_config_bool(var, value) ? -1 : 0;
810 return 0;
811 }
812
813 if (!strcmp(var, "rebase.backend")) {
814 return git_config_string(&opts->default_backend, var, value);
815 }
816
817 return git_default_config(var, value, data);
818 }
819
820 static int checkout_up_to_date(struct rebase_options *options)
821 {
822 struct strbuf buf = STRBUF_INIT;
823 struct reset_head_opts ropts = { 0 };
824 int ret = 0;
825
826 strbuf_addf(&buf, "%s: checkout %s",
827 options->reflog_action, options->switch_to);
828 ropts.oid = &options->orig_head->object.oid;
829 ropts.branch = options->head_name;
830 ropts.flags = RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
831 if (!ropts.branch)
832 ropts.flags |= RESET_HEAD_DETACH;
833 ropts.head_msg = buf.buf;
834 if (reset_head(the_repository, &ropts) < 0)
835 ret = error(_("could not switch to %s"), options->switch_to);
836 strbuf_release(&buf);
837
838 return ret;
839 }
840
841 /*
842 * Determines whether the commits in from..to are linear, i.e. contain
843 * no merge commits. This function *expects* `from` to be an ancestor of
844 * `to`.
845 */
846 static int is_linear_history(struct commit *from, struct commit *to)
847 {
848 while (to && to != from) {
849 parse_commit(to);
850 if (!to->parents)
851 return 1;
852 if (to->parents->next)
853 return 0;
854 to = to->parents->item;
855 }
856 return 1;
857 }
858
859 static int can_fast_forward(struct commit *onto, struct commit *upstream,
860 struct commit *restrict_revision,
861 struct commit *head, struct object_id *branch_base)
862 {
863 struct commit_list *merge_bases = NULL;
864 int res = 0;
865
866 if (is_null_oid(branch_base))
867 goto done; /* fill_branch_base() found multiple merge bases */
868
869 if (!oideq(branch_base, &onto->object.oid))
870 goto done;
871
872 if (restrict_revision && !oideq(&restrict_revision->object.oid, branch_base))
873 goto done;
874
875 if (!upstream)
876 goto done;
877
878 merge_bases = get_merge_bases(upstream, head);
879 if (!merge_bases || merge_bases->next)
880 goto done;
881
882 if (!oideq(&onto->object.oid, &merge_bases->item->object.oid))
883 goto done;
884
885 res = 1;
886
887 done:
888 free_commit_list(merge_bases);
889 return res && is_linear_history(onto, head);
890 }
891
892 static void fill_branch_base(struct rebase_options *options,
893 struct object_id *branch_base)
894 {
895 struct commit_list *merge_bases = NULL;
896
897 merge_bases = get_merge_bases(options->onto, options->orig_head);
898 if (!merge_bases || merge_bases->next)
899 oidcpy(branch_base, null_oid());
900 else
901 oidcpy(branch_base, &merge_bases->item->object.oid);
902
903 free_commit_list(merge_bases);
904 }
905
906 static int parse_opt_am(const struct option *opt, const char *arg, int unset)
907 {
908 struct rebase_options *opts = opt->value;
909
910 BUG_ON_OPT_NEG(unset);
911 BUG_ON_OPT_ARG(arg);
912
913 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_APPLY)
914 die(_("apply options and merge options cannot be used together"));
915
916 opts->type = REBASE_APPLY;
917
918 return 0;
919 }
920
921 /* -i followed by -m is still -i */
922 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
923 {
924 struct rebase_options *opts = opt->value;
925
926 BUG_ON_OPT_NEG(unset);
927 BUG_ON_OPT_ARG(arg);
928
929 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
930 die(_("apply options and merge options cannot be used together"));
931
932 opts->type = REBASE_MERGE;
933
934 return 0;
935 }
936
937 /* -i followed by -r is still explicitly interactive, but -r alone is not */
938 static int parse_opt_interactive(const struct option *opt, const char *arg,
939 int unset)
940 {
941 struct rebase_options *opts = opt->value;
942
943 BUG_ON_OPT_NEG(unset);
944 BUG_ON_OPT_ARG(arg);
945
946 if (opts->type != REBASE_UNSPECIFIED && opts->type != REBASE_MERGE)
947 die(_("apply options and merge options cannot be used together"));
948
949 opts->type = REBASE_MERGE;
950 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
951
952 return 0;
953 }
954
955 static enum empty_type parse_empty_value(const char *value)
956 {
957 if (!strcasecmp(value, "drop"))
958 return EMPTY_DROP;
959 else if (!strcasecmp(value, "keep"))
960 return EMPTY_KEEP;
961 else if (!strcasecmp(value, "ask"))
962 return EMPTY_ASK;
963
964 die(_("unrecognized empty type '%s'; valid values are \"drop\", \"keep\", and \"ask\"."), value);
965 }
966
967 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
968 {
969 struct rebase_options *options = opt->value;
970 enum empty_type value = parse_empty_value(arg);
971
972 BUG_ON_OPT_NEG(unset);
973
974 options->empty = value;
975 return 0;
976 }
977
978 static void NORETURN error_on_missing_default_upstream(void)
979 {
980 struct branch *current_branch = branch_get(NULL);
981
982 printf(_("%s\n"
983 "Please specify which branch you want to rebase against.\n"
984 "See git-rebase(1) for details.\n"
985 "\n"
986 " git rebase '<branch>'\n"
987 "\n"),
988 current_branch ? _("There is no tracking information for "
989 "the current branch.") :
990 _("You are not currently on a branch."));
991
992 if (current_branch) {
993 const char *remote = current_branch->remote_name;
994
995 if (!remote)
996 remote = _("<remote>");
997
998 printf(_("If you wish to set tracking information for this "
999 "branch you can do so with:\n"
1000 "\n"
1001 " git branch --set-upstream-to=%s/<branch> %s\n"
1002 "\n"),
1003 remote, current_branch->name);
1004 }
1005 exit(1);
1006 }
1007
1008 static int check_exec_cmd(const char *cmd)
1009 {
1010 if (strchr(cmd, '\n'))
1011 return error(_("exec commands cannot contain newlines"));
1012
1013 /* Does the command consist purely of whitespace? */
1014 if (!cmd[strspn(cmd, " \t\r\f\v")])
1015 return error(_("empty exec command"));
1016
1017 return 0;
1018 }
1019
1020 int cmd_rebase(int argc, const char **argv, const char *prefix)
1021 {
1022 struct rebase_options options = REBASE_OPTIONS_INIT;
1023 const char *branch_name;
1024 int ret, flags, total_argc, in_progress = 0;
1025 int keep_base = 0;
1026 int ok_to_skip_pre_rebase = 0;
1027 struct strbuf msg = STRBUF_INIT;
1028 struct strbuf revisions = STRBUF_INIT;
1029 struct strbuf buf = STRBUF_INIT;
1030 struct object_id branch_base;
1031 int ignore_whitespace = 0;
1032 const char *gpg_sign = NULL;
1033 const char *rebase_merges = NULL;
1034 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1035 struct object_id squash_onto;
1036 char *squash_onto_name = NULL;
1037 char *keep_base_onto_name = NULL;
1038 int reschedule_failed_exec = -1;
1039 int allow_preemptive_ff = 1;
1040 int preserve_merges_selected = 0;
1041 struct reset_head_opts ropts = { 0 };
1042 struct option builtin_rebase_options[] = {
1043 OPT_STRING(0, "onto", &options.onto_name,
1044 N_("revision"),
1045 N_("rebase onto given branch instead of upstream")),
1046 OPT_BOOL(0, "keep-base", &keep_base,
1047 N_("use the merge-base of upstream and branch as the current base")),
1048 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1049 N_("allow pre-rebase hook to run")),
1050 OPT_NEGBIT('q', "quiet", &options.flags,
1051 N_("be quiet. implies --no-stat"),
1052 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1053 OPT_BIT('v', "verbose", &options.flags,
1054 N_("display a diffstat of what changed upstream"),
1055 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1056 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1057 N_("do not show diffstat of what changed upstream"),
1058 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1059 OPT_BOOL(0, "signoff", &options.signoff,
1060 N_("add a Signed-off-by trailer to each commit")),
1061 OPT_BOOL(0, "committer-date-is-author-date",
1062 &options.committer_date_is_author_date,
1063 N_("make committer date match author date")),
1064 OPT_BOOL(0, "reset-author-date", &options.ignore_date,
1065 N_("ignore author date and use current date")),
1066 OPT_HIDDEN_BOOL(0, "ignore-date", &options.ignore_date,
1067 N_("synonym of --reset-author-date")),
1068 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1069 N_("passed to 'git apply'"), 0),
1070 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
1071 N_("ignore changes in whitespace")),
1072 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1073 N_("action"), N_("passed to 'git apply'"), 0),
1074 OPT_BIT('f', "force-rebase", &options.flags,
1075 N_("cherry-pick all commits, even if unchanged"),
1076 REBASE_FORCE),
1077 OPT_BIT(0, "no-ff", &options.flags,
1078 N_("cherry-pick all commits, even if unchanged"),
1079 REBASE_FORCE),
1080 OPT_CMDMODE(0, "continue", &options.action, N_("continue"),
1081 ACTION_CONTINUE),
1082 OPT_CMDMODE(0, "skip", &options.action,
1083 N_("skip current patch and continue"), ACTION_SKIP),
1084 OPT_CMDMODE(0, "abort", &options.action,
1085 N_("abort and check out the original branch"),
1086 ACTION_ABORT),
1087 OPT_CMDMODE(0, "quit", &options.action,
1088 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1089 OPT_CMDMODE(0, "edit-todo", &options.action, N_("edit the todo list "
1090 "during an interactive rebase"), ACTION_EDIT_TODO),
1091 OPT_CMDMODE(0, "show-current-patch", &options.action,
1092 N_("show the patch file being applied or merged"),
1093 ACTION_SHOW_CURRENT_PATCH),
1094 OPT_CALLBACK_F(0, "apply", &options, NULL,
1095 N_("use apply strategies to rebase"),
1096 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1097 parse_opt_am),
1098 OPT_CALLBACK_F('m', "merge", &options, NULL,
1099 N_("use merging strategies to rebase"),
1100 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1101 parse_opt_merge),
1102 OPT_CALLBACK_F('i', "interactive", &options, NULL,
1103 N_("let the user edit the list of commits to rebase"),
1104 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1105 parse_opt_interactive),
1106 OPT_SET_INT_F('p', "preserve-merges", &preserve_merges_selected,
1107 N_("(REMOVED) was: try to recreate merges "
1108 "instead of ignoring them"),
1109 1, PARSE_OPT_HIDDEN),
1110 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
1111 OPT_CALLBACK_F(0, "empty", &options, "{drop,keep,ask}",
1112 N_("how to handle commits that become empty"),
1113 PARSE_OPT_NONEG, parse_opt_empty),
1114 OPT_CALLBACK_F('k', "keep-empty", &options, NULL,
1115 N_("keep commits which start empty"),
1116 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN,
1117 parse_opt_keep_empty),
1118 OPT_BOOL(0, "autosquash", &options.autosquash,
1119 N_("move commits that begin with "
1120 "squash!/fixup! under -i")),
1121 OPT_BOOL(0, "update-refs", &options.update_refs,
1122 N_("update branches that point to commits "
1123 "that are being rebased")),
1124 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1125 N_("GPG-sign commits"),
1126 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1127 OPT_AUTOSTASH(&options.autostash),
1128 OPT_STRING_LIST('x', "exec", &options.exec, N_("exec"),
1129 N_("add exec lines after each commit of the "
1130 "editable list")),
1131 OPT_BOOL_F(0, "allow-empty-message",
1132 &options.allow_empty_message,
1133 N_("allow rebasing commits with empty messages"),
1134 PARSE_OPT_HIDDEN),
1135 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1136 N_("mode"),
1137 N_("try to rebase merges instead of skipping them"),
1138 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1139 OPT_BOOL(0, "fork-point", &options.fork_point,
1140 N_("use 'merge-base --fork-point' to refine upstream")),
1141 OPT_STRING('s', "strategy", &options.strategy,
1142 N_("strategy"), N_("use the given merge strategy")),
1143 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1144 N_("option"),
1145 N_("pass the argument through to the merge "
1146 "strategy")),
1147 OPT_BOOL(0, "root", &options.root,
1148 N_("rebase all reachable commits up to the root(s)")),
1149 OPT_BOOL(0, "reschedule-failed-exec",
1150 &reschedule_failed_exec,
1151 N_("automatically re-schedule any `exec` that fails")),
1152 OPT_BOOL(0, "reapply-cherry-picks", &options.reapply_cherry_picks,
1153 N_("apply all changes, even those already present upstream")),
1154 OPT_END(),
1155 };
1156 int i;
1157
1158 if (argc == 2 && !strcmp(argv[1], "-h"))
1159 usage_with_options(builtin_rebase_usage,
1160 builtin_rebase_options);
1161
1162 prepare_repo_settings(the_repository);
1163 the_repository->settings.command_requires_full_index = 0;
1164
1165 git_config(rebase_config, &options);
1166 /* options.gpg_sign_opt will be either "-S" or NULL */
1167 gpg_sign = options.gpg_sign_opt ? "" : NULL;
1168 FREE_AND_NULL(options.gpg_sign_opt);
1169
1170 strbuf_reset(&buf);
1171 strbuf_addf(&buf, "%s/applying", apply_dir());
1172 if(file_exists(buf.buf))
1173 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1174
1175 if (is_directory(apply_dir())) {
1176 options.type = REBASE_APPLY;
1177 options.state_dir = apply_dir();
1178 } else if (is_directory(merge_dir())) {
1179 strbuf_reset(&buf);
1180 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1181 if (!(options.action == ACTION_ABORT) && is_directory(buf.buf)) {
1182 die(_("`rebase --preserve-merges` (-p) is no longer supported.\n"
1183 "Use `git rebase --abort` to terminate current rebase.\n"
1184 "Or downgrade to v2.33, or earlier, to complete the rebase."));
1185 } else {
1186 strbuf_reset(&buf);
1187 strbuf_addf(&buf, "%s/interactive", merge_dir());
1188 options.type = REBASE_MERGE;
1189 if (file_exists(buf.buf))
1190 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1191 }
1192 options.state_dir = merge_dir();
1193 }
1194
1195 if (options.type != REBASE_UNSPECIFIED)
1196 in_progress = 1;
1197
1198 total_argc = argc;
1199 argc = parse_options(argc, argv, prefix,
1200 builtin_rebase_options,
1201 builtin_rebase_usage, 0);
1202
1203 if (preserve_merges_selected)
1204 die(_("--preserve-merges was replaced by --rebase-merges\n"
1205 "Note: Your `pull.rebase` configuration may also be set to 'preserve',\n"
1206 "which is no longer supported; use 'merges' instead"));
1207
1208 if (options.action != ACTION_NONE && total_argc != 2) {
1209 usage_with_options(builtin_rebase_usage,
1210 builtin_rebase_options);
1211 }
1212
1213 if (argc > 2)
1214 usage_with_options(builtin_rebase_usage,
1215 builtin_rebase_options);
1216
1217 if (keep_base) {
1218 if (options.onto_name)
1219 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--onto");
1220 if (options.root)
1221 die(_("options '%s' and '%s' cannot be used together"), "--keep-base", "--root");
1222 /*
1223 * --keep-base defaults to --no-fork-point to keep the
1224 * base the same.
1225 */
1226 if (options.fork_point < 0)
1227 options.fork_point = 0;
1228 }
1229 if (options.root && options.fork_point > 0)
1230 die(_("options '%s' and '%s' cannot be used together"), "--root", "--fork-point");
1231
1232 if (options.action != ACTION_NONE && !in_progress)
1233 die(_("No rebase in progress?"));
1234
1235 if (options.action == ACTION_EDIT_TODO && !is_merge(&options))
1236 die(_("The --edit-todo action can only be used during "
1237 "interactive rebase."));
1238
1239 if (trace2_is_enabled()) {
1240 if (is_merge(&options))
1241 trace2_cmd_mode("interactive");
1242 else if (options.exec.nr)
1243 trace2_cmd_mode("interactive-exec");
1244 else
1245 trace2_cmd_mode(action_names[options.action]);
1246 }
1247
1248 options.reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1249 options.reflog_action =
1250 xstrdup(options.reflog_action ? options.reflog_action : "rebase");
1251
1252 switch (options.action) {
1253 case ACTION_CONTINUE: {
1254 struct object_id head;
1255 struct lock_file lock_file = LOCK_INIT;
1256 int fd;
1257
1258 /* Sanity check */
1259 if (get_oid("HEAD", &head))
1260 die(_("Cannot read HEAD"));
1261
1262 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
1263 if (repo_read_index(the_repository) < 0)
1264 die(_("could not read index"));
1265 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1266 NULL);
1267 if (0 <= fd)
1268 repo_update_index_if_able(the_repository, &lock_file);
1269 rollback_lock_file(&lock_file);
1270
1271 if (has_unstaged_changes(the_repository, 1)) {
1272 puts(_("You must edit all merge conflicts and then\n"
1273 "mark them as resolved using git add"));
1274 exit(1);
1275 }
1276 if (read_basic_state(&options))
1277 exit(1);
1278 goto run_rebase;
1279 }
1280 case ACTION_SKIP: {
1281 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1282
1283 rerere_clear(the_repository, &merge_rr);
1284 string_list_clear(&merge_rr, 1);
1285 ropts.flags = RESET_HEAD_HARD;
1286 if (reset_head(the_repository, &ropts) < 0)
1287 die(_("could not discard worktree changes"));
1288 remove_branch_state(the_repository, 0);
1289 if (read_basic_state(&options))
1290 exit(1);
1291 goto run_rebase;
1292 }
1293 case ACTION_ABORT: {
1294 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1295 struct strbuf head_msg = STRBUF_INIT;
1296
1297 rerere_clear(the_repository, &merge_rr);
1298 string_list_clear(&merge_rr, 1);
1299
1300 if (read_basic_state(&options))
1301 exit(1);
1302
1303 strbuf_addf(&head_msg, "%s (abort): returning to %s",
1304 options.reflog_action,
1305 options.head_name ? options.head_name
1306 : oid_to_hex(&options.orig_head->object.oid));
1307 ropts.oid = &options.orig_head->object.oid;
1308 ropts.head_msg = head_msg.buf;
1309 ropts.branch = options.head_name;
1310 ropts.flags = RESET_HEAD_HARD;
1311 if (reset_head(the_repository, &ropts) < 0)
1312 die(_("could not move back to %s"),
1313 oid_to_hex(&options.orig_head->object.oid));
1314 strbuf_release(&head_msg);
1315 remove_branch_state(the_repository, 0);
1316 ret = finish_rebase(&options);
1317 goto cleanup;
1318 }
1319 case ACTION_QUIT: {
1320 save_autostash(state_dir_path("autostash", &options));
1321 if (options.type == REBASE_MERGE) {
1322 struct replay_opts replay = REPLAY_OPTS_INIT;
1323
1324 replay.action = REPLAY_INTERACTIVE_REBASE;
1325 ret = sequencer_remove_state(&replay);
1326 replay_opts_release(&replay);
1327 } else {
1328 strbuf_reset(&buf);
1329 strbuf_addstr(&buf, options.state_dir);
1330 ret = remove_dir_recursively(&buf, 0);
1331 if (ret)
1332 error(_("could not remove '%s'"),
1333 options.state_dir);
1334 }
1335 goto cleanup;
1336 }
1337 case ACTION_EDIT_TODO:
1338 options.dont_finish_rebase = 1;
1339 goto run_rebase;
1340 case ACTION_SHOW_CURRENT_PATCH:
1341 options.dont_finish_rebase = 1;
1342 goto run_rebase;
1343 case ACTION_NONE:
1344 break;
1345 default:
1346 BUG("action: %d", options.action);
1347 }
1348
1349 /* Make sure no rebase is in progress */
1350 if (in_progress) {
1351 const char *last_slash = strrchr(options.state_dir, '/');
1352 const char *state_dir_base =
1353 last_slash ? last_slash + 1 : options.state_dir;
1354 const char *cmd_live_rebase =
1355 "git rebase (--continue | --abort | --skip)";
1356 strbuf_reset(&buf);
1357 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1358 die(_("It seems that there is already a %s directory, and\n"
1359 "I wonder if you are in the middle of another rebase. "
1360 "If that is the\n"
1361 "case, please try\n\t%s\n"
1362 "If that is not the case, please\n\t%s\n"
1363 "and run me again. I am stopping in case you still "
1364 "have something\n"
1365 "valuable there.\n"),
1366 state_dir_base, cmd_live_rebase, buf.buf);
1367 }
1368
1369 if ((options.flags & REBASE_INTERACTIVE_EXPLICIT) ||
1370 (options.action != ACTION_NONE) ||
1371 (options.exec.nr > 0) ||
1372 (options.autosquash == -1 && options.config_autosquash == 1) ||
1373 options.autosquash == 1) {
1374 allow_preemptive_ff = 0;
1375 }
1376 if (options.committer_date_is_author_date || options.ignore_date)
1377 options.flags |= REBASE_FORCE;
1378
1379 for (i = 0; i < options.git_am_opts.nr; i++) {
1380 const char *option = options.git_am_opts.v[i], *p;
1381 if (!strcmp(option, "--whitespace=fix") ||
1382 !strcmp(option, "--whitespace=strip"))
1383 allow_preemptive_ff = 0;
1384 else if (skip_prefix(option, "-C", &p)) {
1385 while (*p)
1386 if (!isdigit(*(p++)))
1387 die(_("switch `C' expects a "
1388 "numerical value"));
1389 } else if (skip_prefix(option, "--whitespace=", &p)) {
1390 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1391 strcmp(p, "error") && strcmp(p, "error-all"))
1392 die("Invalid whitespace option: '%s'", p);
1393 }
1394 }
1395
1396 for (i = 0; i < options.exec.nr; i++)
1397 if (check_exec_cmd(options.exec.items[i].string))
1398 exit(1);
1399
1400 if (!(options.flags & REBASE_NO_QUIET))
1401 strvec_push(&options.git_am_opts, "-q");
1402
1403 if (options.empty != EMPTY_UNSPECIFIED)
1404 imply_merge(&options, "--empty");
1405
1406 if (options.reapply_cherry_picks < 0)
1407 /*
1408 * We default to --no-reapply-cherry-picks unless
1409 * --keep-base is given; when --keep-base is given, we want
1410 * to default to --reapply-cherry-picks.
1411 */
1412 options.reapply_cherry_picks = keep_base;
1413 else if (!keep_base)
1414 /*
1415 * The apply backend always searches for and drops cherry
1416 * picks. This is often not wanted with --keep-base, so
1417 * --keep-base allows --reapply-cherry-picks to be
1418 * simulated by altering the upstream such that
1419 * cherry-picks cannot be detected and thus all commits are
1420 * reapplied. Thus, --[no-]reapply-cherry-picks is
1421 * supported when --keep-base is specified, but not when
1422 * --keep-base is left out.
1423 */
1424 imply_merge(&options, options.reapply_cherry_picks ?
1425 "--reapply-cherry-picks" :
1426 "--no-reapply-cherry-picks");
1427
1428 if (gpg_sign)
1429 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1430
1431 if (options.exec.nr)
1432 imply_merge(&options, "--exec");
1433
1434 if (rebase_merges) {
1435 if (!*rebase_merges)
1436 ; /* default mode; do nothing */
1437 else if (!strcmp("rebase-cousins", rebase_merges))
1438 options.rebase_cousins = 1;
1439 else if (strcmp("no-rebase-cousins", rebase_merges))
1440 die(_("Unknown mode: %s"), rebase_merges);
1441 options.rebase_merges = 1;
1442 imply_merge(&options, "--rebase-merges");
1443 }
1444
1445 if (options.type == REBASE_APPLY) {
1446 if (ignore_whitespace)
1447 strvec_push(&options.git_am_opts,
1448 "--ignore-whitespace");
1449 if (options.committer_date_is_author_date)
1450 strvec_push(&options.git_am_opts,
1451 "--committer-date-is-author-date");
1452 if (options.ignore_date)
1453 strvec_push(&options.git_am_opts, "--ignore-date");
1454 } else {
1455 /* REBASE_MERGE */
1456 if (ignore_whitespace) {
1457 string_list_append(&strategy_options,
1458 "ignore-space-change");
1459 }
1460 }
1461
1462 if (strategy_options.nr) {
1463 int i;
1464
1465 if (!options.strategy)
1466 options.strategy = "ort";
1467
1468 strbuf_reset(&buf);
1469 for (i = 0; i < strategy_options.nr; i++)
1470 strbuf_addf(&buf, " --%s",
1471 strategy_options.items[i].string);
1472 options.strategy_opts = xstrdup(buf.buf);
1473 }
1474
1475 if (options.strategy) {
1476 options.strategy = xstrdup(options.strategy);
1477 switch (options.type) {
1478 case REBASE_APPLY:
1479 die(_("--strategy requires --merge or --interactive"));
1480 case REBASE_MERGE:
1481 /* compatible */
1482 break;
1483 case REBASE_UNSPECIFIED:
1484 options.type = REBASE_MERGE;
1485 break;
1486 default:
1487 BUG("unhandled rebase type (%d)", options.type);
1488 }
1489 }
1490
1491 if (options.type == REBASE_MERGE)
1492 imply_merge(&options, "--merge");
1493
1494 if (options.root && !options.onto_name)
1495 imply_merge(&options, "--root without --onto");
1496
1497 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1498 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1499
1500 if (options.git_am_opts.nr || options.type == REBASE_APPLY) {
1501 /* all am options except -q are compatible only with --apply */
1502 for (i = options.git_am_opts.nr - 1; i >= 0; i--)
1503 if (strcmp(options.git_am_opts.v[i], "-q"))
1504 break;
1505
1506 if (i >= 0 || options.type == REBASE_APPLY) {
1507 if (is_merge(&options))
1508 die(_("apply options and merge options "
1509 "cannot be used together"));
1510 else if (options.autosquash == -1 && options.config_autosquash == 1)
1511 die(_("apply options are incompatible with rebase.autosquash. Consider adding --no-autosquash"));
1512 else if (options.update_refs == -1 && options.config_update_refs == 1)
1513 die(_("apply options are incompatible with rebase.updateRefs. Consider adding --no-update-refs"));
1514 else
1515 options.type = REBASE_APPLY;
1516 }
1517 }
1518
1519 if (options.update_refs == 1)
1520 imply_merge(&options, "--update-refs");
1521 options.update_refs = (options.update_refs >= 0) ? options.update_refs :
1522 ((options.config_update_refs >= 0) ? options.config_update_refs : 0);
1523
1524 if (options.autosquash == 1)
1525 imply_merge(&options, "--autosquash");
1526 options.autosquash = (options.autosquash >= 0) ? options.autosquash :
1527 ((options.config_autosquash >= 0) ? options.config_autosquash : 0);
1528
1529 if (options.type == REBASE_UNSPECIFIED) {
1530 if (!strcmp(options.default_backend, "merge"))
1531 imply_merge(&options, "--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 (get_oid_mb(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 diff_setup(&opts);
1782 opts.stat_width = -1; /* use full terminal width */
1783 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1784 opts.output_format |=
1785 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1786 opts.detect_rename = DIFF_DETECT_RENAME;
1787 diff_setup_done(&opts);
1788 diff_tree_oid(is_null_oid(&branch_base) ?
1789 the_hash_algo->empty_tree : &branch_base,
1790 &options.onto->object.oid, "", &opts);
1791 diffcore_std(&opts);
1792 diff_flush(&opts);
1793 }
1794
1795 if (is_merge(&options))
1796 goto run_rebase;
1797
1798 /* Detach HEAD and reset the tree */
1799 if (options.flags & REBASE_NO_QUIET)
1800 printf(_("First, rewinding head to replay your work on top of "
1801 "it...\n"));
1802
1803 strbuf_addf(&msg, "%s (start): checkout %s",
1804 options.reflog_action, options.onto_name);
1805 ropts.oid = &options.onto->object.oid;
1806 ropts.orig_head = &options.orig_head->object.oid,
1807 ropts.flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
1808 RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
1809 ropts.head_msg = msg.buf;
1810 ropts.default_reflog_action = options.reflog_action;
1811 if (reset_head(the_repository, &ropts))
1812 die(_("Could not detach HEAD"));
1813 strbuf_release(&msg);
1814
1815 /*
1816 * If the onto is a proper descendant of the tip of the branch, then
1817 * we just fast-forwarded.
1818 */
1819 if (oideq(&branch_base, &options.orig_head->object.oid)) {
1820 printf(_("Fast-forwarded %s to %s.\n"),
1821 branch_name, options.onto_name);
1822 move_to_original_branch(&options);
1823 ret = finish_rebase(&options);
1824 goto cleanup;
1825 }
1826
1827 strbuf_addf(&revisions, "%s..%s",
1828 options.root ? oid_to_hex(&options.onto->object.oid) :
1829 (options.restrict_revision ?
1830 oid_to_hex(&options.restrict_revision->object.oid) :
1831 oid_to_hex(&options.upstream->object.oid)),
1832 oid_to_hex(&options.orig_head->object.oid));
1833
1834 options.revisions = revisions.buf;
1835
1836 run_rebase:
1837 ret = run_specific_rebase(&options);
1838
1839 cleanup:
1840 strbuf_release(&buf);
1841 strbuf_release(&revisions);
1842 free(options.reflog_action);
1843 free(options.head_name);
1844 strvec_clear(&options.git_am_opts);
1845 free(options.gpg_sign_opt);
1846 string_list_clear(&options.exec, 0);
1847 free(options.strategy);
1848 free(options.strategy_opts);
1849 strbuf_release(&options.git_format_patch_opt);
1850 free(squash_onto_name);
1851 free(keep_base_onto_name);
1852 string_list_clear(&strategy_options, 0);
1853 return !!ret;
1854 }