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