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