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