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