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