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