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