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