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