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