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