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