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