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