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