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