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