Merge branch 'km/init-doc-typofix'
[git] / builtin / rebase.c
1 /*
2  * "git rebase" builtin command
3  *
4  * Copyright (c) 2018 Pratik Karki
5  */
6
7 #include "builtin.h"
8 #include "run-command.h"
9 #include "exec-cmd.h"
10 #include "argv-array.h"
11 #include "dir.h"
12 #include "packfile.h"
13 #include "refs.h"
14 #include "quote.h"
15 #include "config.h"
16 #include "cache-tree.h"
17 #include "unpack-trees.h"
18 #include "lockfile.h"
19 #include "parse-options.h"
20 #include "commit.h"
21 #include "diff.h"
22 #include "wt-status.h"
23 #include "revision.h"
24 #include "commit-reach.h"
25 #include "rerere.h"
26 #include "branch.h"
27
28 static char const * const builtin_rebase_usage[] = {
29         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
30                 "[<upstream>] [<branch>]"),
31         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
32                 "--root [<branch>]"),
33         N_("git rebase --continue | --abort | --skip | --edit-todo"),
34         NULL
35 };
36
37 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
38 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
39
40 enum rebase_type {
41         REBASE_UNSPECIFIED = -1,
42         REBASE_AM,
43         REBASE_MERGE,
44         REBASE_INTERACTIVE,
45         REBASE_PRESERVE_MERGES
46 };
47
48 static int use_builtin_rebase(void)
49 {
50         struct child_process cp = CHILD_PROCESS_INIT;
51         struct strbuf out = STRBUF_INIT;
52         int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
53
54         if (env != -1)
55                 return env;
56
57         argv_array_pushl(&cp.args,
58                          "config", "--bool", "rebase.usebuiltin", NULL);
59         cp.git_cmd = 1;
60         if (capture_command(&cp, &out, 6)) {
61                 strbuf_release(&out);
62                 return 1;
63         }
64
65         strbuf_trim(&out);
66         ret = !strcmp("true", out.buf);
67         strbuf_release(&out);
68         return ret;
69 }
70
71 struct rebase_options {
72         enum rebase_type type;
73         const char *state_dir;
74         struct commit *upstream;
75         const char *upstream_name;
76         const char *upstream_arg;
77         char *head_name;
78         struct object_id orig_head;
79         struct commit *onto;
80         const char *onto_name;
81         const char *revisions;
82         const char *switch_to;
83         int root;
84         struct object_id *squash_onto;
85         struct commit *restrict_revision;
86         int dont_finish_rebase;
87         enum {
88                 REBASE_NO_QUIET = 1<<0,
89                 REBASE_VERBOSE = 1<<1,
90                 REBASE_DIFFSTAT = 1<<2,
91                 REBASE_FORCE = 1<<3,
92                 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
93         } flags;
94         struct argv_array git_am_opts;
95         const char *action;
96         int signoff;
97         int allow_rerere_autoupdate;
98         int keep_empty;
99         int autosquash;
100         char *gpg_sign_opt;
101         int autostash;
102         char *cmd;
103         int allow_empty_message;
104         int rebase_merges, rebase_cousins;
105         char *strategy, *strategy_opts;
106         struct strbuf git_format_patch_opt;
107         int reschedule_failed_exec;
108 };
109
110 static int is_interactive(struct rebase_options *opts)
111 {
112         return opts->type == REBASE_INTERACTIVE ||
113                 opts->type == REBASE_PRESERVE_MERGES;
114 }
115
116 static void imply_interactive(struct rebase_options *opts, const char *option)
117 {
118         switch (opts->type) {
119         case REBASE_AM:
120                 die(_("%s requires an interactive rebase"), option);
121                 break;
122         case REBASE_INTERACTIVE:
123         case REBASE_PRESERVE_MERGES:
124                 break;
125         case REBASE_MERGE:
126                 /* we now implement --merge via --interactive */
127         default:
128                 opts->type = REBASE_INTERACTIVE; /* implied */
129                 break;
130         }
131 }
132
133 /* Returns the filename prefixed by the state_dir */
134 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
135 {
136         static struct strbuf path = STRBUF_INIT;
137         static size_t prefix_len;
138
139         if (!prefix_len) {
140                 strbuf_addf(&path, "%s/", opts->state_dir);
141                 prefix_len = path.len;
142         }
143
144         strbuf_setlen(&path, prefix_len);
145         strbuf_addstr(&path, filename);
146         return path.buf;
147 }
148
149 /* Read one file, then strip line endings */
150 static int read_one(const char *path, struct strbuf *buf)
151 {
152         if (strbuf_read_file(buf, path, 0) < 0)
153                 return error_errno(_("could not read '%s'"), path);
154         strbuf_trim_trailing_newline(buf);
155         return 0;
156 }
157
158 /* Initialize the rebase options from the state directory. */
159 static int read_basic_state(struct rebase_options *opts)
160 {
161         struct strbuf head_name = STRBUF_INIT;
162         struct strbuf buf = STRBUF_INIT;
163         struct object_id oid;
164
165         if (read_one(state_dir_path("head-name", opts), &head_name) ||
166             read_one(state_dir_path("onto", opts), &buf))
167                 return -1;
168         opts->head_name = starts_with(head_name.buf, "refs/") ?
169                 xstrdup(head_name.buf) : NULL;
170         strbuf_release(&head_name);
171         if (get_oid(buf.buf, &oid))
172                 return error(_("could not get 'onto': '%s'"), buf.buf);
173         opts->onto = lookup_commit_or_die(&oid, buf.buf);
174
175         /*
176          * We always write to orig-head, but interactive rebase used to write to
177          * head. Fall back to reading from head to cover for the case that the
178          * user upgraded git with an ongoing interactive rebase.
179          */
180         strbuf_reset(&buf);
181         if (file_exists(state_dir_path("orig-head", opts))) {
182                 if (read_one(state_dir_path("orig-head", opts), &buf))
183                         return -1;
184         } else if (read_one(state_dir_path("head", opts), &buf))
185                 return -1;
186         if (get_oid(buf.buf, &opts->orig_head))
187                 return error(_("invalid orig-head: '%s'"), buf.buf);
188
189         if (file_exists(state_dir_path("quiet", opts)))
190                 opts->flags &= ~REBASE_NO_QUIET;
191         else
192                 opts->flags |= REBASE_NO_QUIET;
193
194         if (file_exists(state_dir_path("verbose", opts)))
195                 opts->flags |= REBASE_VERBOSE;
196
197         if (file_exists(state_dir_path("signoff", opts))) {
198                 opts->signoff = 1;
199                 opts->flags |= REBASE_FORCE;
200         }
201
202         if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
203                 strbuf_reset(&buf);
204                 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
205                             &buf))
206                         return -1;
207                 if (!strcmp(buf.buf, "--rerere-autoupdate"))
208                         opts->allow_rerere_autoupdate = 1;
209                 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
210                         opts->allow_rerere_autoupdate = 0;
211                 else
212                         warning(_("ignoring invalid allow_rerere_autoupdate: "
213                                   "'%s'"), buf.buf);
214         } else
215                 opts->allow_rerere_autoupdate = -1;
216
217         if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
218                 strbuf_reset(&buf);
219                 if (read_one(state_dir_path("gpg_sign_opt", opts),
220                             &buf))
221                         return -1;
222                 free(opts->gpg_sign_opt);
223                 opts->gpg_sign_opt = xstrdup(buf.buf);
224         }
225
226         if (file_exists(state_dir_path("strategy", opts))) {
227                 strbuf_reset(&buf);
228                 if (read_one(state_dir_path("strategy", opts), &buf))
229                         return -1;
230                 free(opts->strategy);
231                 opts->strategy = xstrdup(buf.buf);
232         }
233
234         if (file_exists(state_dir_path("strategy_opts", opts))) {
235                 strbuf_reset(&buf);
236                 if (read_one(state_dir_path("strategy_opts", opts), &buf))
237                         return -1;
238                 free(opts->strategy_opts);
239                 opts->strategy_opts = xstrdup(buf.buf);
240         }
241
242         strbuf_release(&buf);
243
244         return 0;
245 }
246
247 static int apply_autostash(struct rebase_options *opts)
248 {
249         const char *path = state_dir_path("autostash", opts);
250         struct strbuf autostash = STRBUF_INIT;
251         struct child_process stash_apply = CHILD_PROCESS_INIT;
252
253         if (!file_exists(path))
254                 return 0;
255
256         if (read_one(path, &autostash))
257                 return error(_("Could not read '%s'"), path);
258         /* Ensure that the hash is not mistaken for a number */
259         strbuf_addstr(&autostash, "^0");
260         argv_array_pushl(&stash_apply.args,
261                          "stash", "apply", autostash.buf, NULL);
262         stash_apply.git_cmd = 1;
263         stash_apply.no_stderr = stash_apply.no_stdout =
264                 stash_apply.no_stdin = 1;
265         if (!run_command(&stash_apply))
266                 printf(_("Applied autostash.\n"));
267         else {
268                 struct argv_array args = ARGV_ARRAY_INIT;
269                 int res = 0;
270
271                 argv_array_pushl(&args,
272                                  "stash", "store", "-m", "autostash", "-q",
273                                  autostash.buf, NULL);
274                 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
275                         res = error(_("Cannot store %s"), autostash.buf);
276                 argv_array_clear(&args);
277                 strbuf_release(&autostash);
278                 if (res)
279                         return res;
280
281                 fprintf(stderr,
282                         _("Applying autostash resulted in conflicts.\n"
283                           "Your changes are safe in the stash.\n"
284                           "You can run \"git stash pop\" or \"git stash drop\" "
285                           "at any time.\n"));
286         }
287
288         strbuf_release(&autostash);
289         return 0;
290 }
291
292 static int finish_rebase(struct rebase_options *opts)
293 {
294         struct strbuf dir = STRBUF_INIT;
295         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
296
297         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
298         apply_autostash(opts);
299         close_all_packs(the_repository->objects);
300         /*
301          * We ignore errors in 'gc --auto', since the
302          * user should see them.
303          */
304         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
305         strbuf_addstr(&dir, opts->state_dir);
306         remove_dir_recursively(&dir, 0);
307         strbuf_release(&dir);
308
309         return 0;
310 }
311
312 static struct commit *peel_committish(const char *name)
313 {
314         struct object *obj;
315         struct object_id oid;
316
317         if (get_oid(name, &oid))
318                 return NULL;
319         obj = parse_object(the_repository, &oid);
320         return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
321 }
322
323 static void add_var(struct strbuf *buf, const char *name, const char *value)
324 {
325         if (!value)
326                 strbuf_addf(buf, "unset %s; ", name);
327         else {
328                 strbuf_addf(buf, "%s=", name);
329                 sq_quote_buf(buf, value);
330                 strbuf_addstr(buf, "; ");
331         }
332 }
333
334 static const char *resolvemsg =
335 N_("Resolve all conflicts manually, mark them as resolved with\n"
336 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
337 "You can instead skip this commit: run \"git rebase --skip\".\n"
338 "To abort and get back to the state before \"git rebase\", run "
339 "\"git rebase --abort\".");
340
341 static int run_specific_rebase(struct rebase_options *opts)
342 {
343         const char *argv[] = { NULL, NULL };
344         struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
345         int status;
346         const char *backend, *backend_func;
347
348         if (opts->type == REBASE_INTERACTIVE) {
349                 /* Run builtin interactive rebase */
350                 struct child_process child = CHILD_PROCESS_INIT;
351
352                 argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
353                                  resolvemsg);
354                 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
355                         argv_array_push(&child.env_array,
356                                         "GIT_SEQUENCE_EDITOR=:");
357                         opts->autosquash = 0;
358                 }
359
360                 child.git_cmd = 1;
361                 argv_array_push(&child.args, "rebase--interactive");
362
363                 if (opts->action)
364                         argv_array_pushf(&child.args, "--%s", opts->action);
365                 if (opts->keep_empty)
366                         argv_array_push(&child.args, "--keep-empty");
367                 if (opts->rebase_merges)
368                         argv_array_push(&child.args, "--rebase-merges");
369                 if (opts->rebase_cousins)
370                         argv_array_push(&child.args, "--rebase-cousins");
371                 if (opts->autosquash)
372                         argv_array_push(&child.args, "--autosquash");
373                 if (opts->flags & REBASE_VERBOSE)
374                         argv_array_push(&child.args, "--verbose");
375                 if (opts->flags & REBASE_FORCE)
376                         argv_array_push(&child.args, "--no-ff");
377                 if (opts->restrict_revision)
378                         argv_array_pushf(&child.args,
379                                          "--restrict-revision=^%s",
380                                          oid_to_hex(&opts->restrict_revision->object.oid));
381                 if (opts->upstream)
382                         argv_array_pushf(&child.args, "--upstream=%s",
383                                          oid_to_hex(&opts->upstream->object.oid));
384                 if (opts->onto)
385                         argv_array_pushf(&child.args, "--onto=%s",
386                                          oid_to_hex(&opts->onto->object.oid));
387                 if (opts->squash_onto)
388                         argv_array_pushf(&child.args, "--squash-onto=%s",
389                                          oid_to_hex(opts->squash_onto));
390                 if (opts->onto_name)
391                         argv_array_pushf(&child.args, "--onto-name=%s",
392                                          opts->onto_name);
393                 argv_array_pushf(&child.args, "--head-name=%s",
394                                  opts->head_name ?
395                                  opts->head_name : "detached HEAD");
396                 if (opts->strategy)
397                         argv_array_pushf(&child.args, "--strategy=%s",
398                                          opts->strategy);
399                 if (opts->strategy_opts)
400                         argv_array_pushf(&child.args, "--strategy-opts=%s",
401                                          opts->strategy_opts);
402                 if (opts->switch_to)
403                         argv_array_pushf(&child.args, "--switch-to=%s",
404                                          opts->switch_to);
405                 if (opts->cmd)
406                         argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
407                 if (opts->allow_empty_message)
408                         argv_array_push(&child.args, "--allow-empty-message");
409                 if (opts->allow_rerere_autoupdate > 0)
410                         argv_array_push(&child.args, "--rerere-autoupdate");
411                 else if (opts->allow_rerere_autoupdate == 0)
412                         argv_array_push(&child.args, "--no-rerere-autoupdate");
413                 if (opts->gpg_sign_opt)
414                         argv_array_push(&child.args, opts->gpg_sign_opt);
415                 if (opts->signoff)
416                         argv_array_push(&child.args, "--signoff");
417                 if (opts->reschedule_failed_exec)
418                         argv_array_push(&child.args, "--reschedule-failed-exec");
419
420                 status = run_command(&child);
421                 goto finished_rebase;
422         }
423
424         add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
425         add_var(&script_snippet, "state_dir", opts->state_dir);
426
427         add_var(&script_snippet, "upstream_name", opts->upstream_name);
428         add_var(&script_snippet, "upstream", opts->upstream ?
429                 oid_to_hex(&opts->upstream->object.oid) : NULL);
430         add_var(&script_snippet, "head_name",
431                 opts->head_name ? opts->head_name : "detached HEAD");
432         add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
433         add_var(&script_snippet, "onto", opts->onto ?
434                 oid_to_hex(&opts->onto->object.oid) : NULL);
435         add_var(&script_snippet, "onto_name", opts->onto_name);
436         add_var(&script_snippet, "revisions", opts->revisions);
437         add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
438                 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
439         add_var(&script_snippet, "GIT_QUIET",
440                 opts->flags & REBASE_NO_QUIET ? "" : "t");
441         sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
442         add_var(&script_snippet, "git_am_opt", buf.buf);
443         strbuf_release(&buf);
444         add_var(&script_snippet, "verbose",
445                 opts->flags & REBASE_VERBOSE ? "t" : "");
446         add_var(&script_snippet, "diffstat",
447                 opts->flags & REBASE_DIFFSTAT ? "t" : "");
448         add_var(&script_snippet, "force_rebase",
449                 opts->flags & REBASE_FORCE ? "t" : "");
450         if (opts->switch_to)
451                 add_var(&script_snippet, "switch_to", opts->switch_to);
452         add_var(&script_snippet, "action", opts->action ? opts->action : "");
453         add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
454         add_var(&script_snippet, "allow_rerere_autoupdate",
455                 opts->allow_rerere_autoupdate < 0 ? "" :
456                 opts->allow_rerere_autoupdate ?
457                 "--rerere-autoupdate" : "--no-rerere-autoupdate");
458         add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
459         add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
460         add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
461         add_var(&script_snippet, "cmd", opts->cmd);
462         add_var(&script_snippet, "allow_empty_message",
463                 opts->allow_empty_message ?  "--allow-empty-message" : "");
464         add_var(&script_snippet, "rebase_merges",
465                 opts->rebase_merges ? "t" : "");
466         add_var(&script_snippet, "rebase_cousins",
467                 opts->rebase_cousins ? "t" : "");
468         add_var(&script_snippet, "strategy", opts->strategy);
469         add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
470         add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
471         add_var(&script_snippet, "squash_onto",
472                 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
473         add_var(&script_snippet, "git_format_patch_opt",
474                 opts->git_format_patch_opt.buf);
475
476         if (is_interactive(opts) &&
477             !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
478                 strbuf_addstr(&script_snippet,
479                               "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
480                 opts->autosquash = 0;
481         }
482
483         switch (opts->type) {
484         case REBASE_AM:
485                 backend = "git-rebase--am";
486                 backend_func = "git_rebase__am";
487                 break;
488         case REBASE_PRESERVE_MERGES:
489                 backend = "git-rebase--preserve-merges";
490                 backend_func = "git_rebase__preserve_merges";
491                 break;
492         default:
493                 BUG("Unhandled rebase type %d", opts->type);
494                 break;
495         }
496
497         strbuf_addf(&script_snippet,
498                     ". git-sh-setup && . git-rebase--common &&"
499                     " . %s && %s", backend, backend_func);
500         argv[0] = script_snippet.buf;
501
502         status = run_command_v_opt(argv, RUN_USING_SHELL);
503 finished_rebase:
504         if (opts->dont_finish_rebase)
505                 ; /* do nothing */
506         else if (opts->type == REBASE_INTERACTIVE)
507                 ; /* interactive rebase cleans up after itself */
508         else if (status == 0) {
509                 if (!file_exists(state_dir_path("stopped-sha", opts)))
510                         finish_rebase(opts);
511         } else if (status == 2) {
512                 struct strbuf dir = STRBUF_INIT;
513
514                 apply_autostash(opts);
515                 strbuf_addstr(&dir, opts->state_dir);
516                 remove_dir_recursively(&dir, 0);
517                 strbuf_release(&dir);
518                 die("Nothing to do");
519         }
520
521         strbuf_release(&script_snippet);
522
523         return status ? -1 : 0;
524 }
525
526 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
527
528 #define RESET_HEAD_DETACH (1<<0)
529 #define RESET_HEAD_HARD (1<<1)
530 #define RESET_HEAD_RUN_POST_CHECKOUT_HOOK (1<<2)
531
532 static int reset_head(struct object_id *oid, const char *action,
533                       const char *switch_to_branch, unsigned flags,
534                       const char *reflog_orig_head, const char *reflog_head)
535 {
536         unsigned detach_head = flags & RESET_HEAD_DETACH;
537         unsigned reset_hard = flags & RESET_HEAD_HARD;
538         unsigned run_hook = flags & RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
539         struct object_id head_oid;
540         struct tree_desc desc[2] = { { NULL }, { NULL } };
541         struct lock_file lock = LOCK_INIT;
542         struct unpack_trees_options unpack_tree_opts;
543         struct tree *tree;
544         const char *reflog_action;
545         struct strbuf msg = STRBUF_INIT;
546         size_t prefix_len;
547         struct object_id *orig = NULL, oid_orig,
548                 *old_orig = NULL, oid_old_orig;
549         int ret = 0, nr = 0;
550
551         if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
552                 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
553
554         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
555                 ret = -1;
556                 goto leave_reset_head;
557         }
558
559         if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
560                 ret = error(_("could not determine HEAD revision"));
561                 goto leave_reset_head;
562         }
563
564         if (!oid)
565                 oid = &head_oid;
566
567         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
568         setup_unpack_trees_porcelain(&unpack_tree_opts, action);
569         unpack_tree_opts.head_idx = 1;
570         unpack_tree_opts.src_index = the_repository->index;
571         unpack_tree_opts.dst_index = the_repository->index;
572         unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
573         unpack_tree_opts.update = 1;
574         unpack_tree_opts.merge = 1;
575         if (!detach_head)
576                 unpack_tree_opts.reset = 1;
577
578         if (read_index_unmerged(the_repository->index) < 0) {
579                 ret = error(_("could not read index"));
580                 goto leave_reset_head;
581         }
582
583         if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
584                 ret = error(_("failed to find tree of %s"),
585                             oid_to_hex(&head_oid));
586                 goto leave_reset_head;
587         }
588
589         if (!fill_tree_descriptor(&desc[nr++], oid)) {
590                 ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
591                 goto leave_reset_head;
592         }
593
594         if (unpack_trees(nr, desc, &unpack_tree_opts)) {
595                 ret = -1;
596                 goto leave_reset_head;
597         }
598
599         tree = parse_tree_indirect(oid);
600         prime_cache_tree(the_repository, the_repository->index, tree);
601
602         if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
603                 ret = error(_("could not write index"));
604                 goto leave_reset_head;
605         }
606
607         reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
608         strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
609         prefix_len = msg.len;
610
611         if (!get_oid("ORIG_HEAD", &oid_old_orig))
612                 old_orig = &oid_old_orig;
613         if (!get_oid("HEAD", &oid_orig)) {
614                 orig = &oid_orig;
615                 if (!reflog_orig_head) {
616                         strbuf_addstr(&msg, "updating ORIG_HEAD");
617                         reflog_orig_head = msg.buf;
618                 }
619                 update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
620                            UPDATE_REFS_MSG_ON_ERR);
621         } else if (old_orig)
622                 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
623         if (!reflog_head) {
624                 strbuf_setlen(&msg, prefix_len);
625                 strbuf_addstr(&msg, "updating HEAD");
626                 reflog_head = msg.buf;
627         }
628         if (!switch_to_branch)
629                 ret = update_ref(reflog_head, "HEAD", oid, orig,
630                                  detach_head ? REF_NO_DEREF : 0,
631                                  UPDATE_REFS_MSG_ON_ERR);
632         else {
633                 ret = create_symref("HEAD", switch_to_branch, msg.buf);
634                 if (!ret)
635                         ret = update_ref(reflog_head, "HEAD", oid, NULL, 0,
636                                          UPDATE_REFS_MSG_ON_ERR);
637         }
638         if (run_hook)
639                 run_hook_le(NULL, "post-checkout",
640                             oid_to_hex(orig ? orig : &null_oid),
641                             oid_to_hex(oid), "1", NULL);
642
643 leave_reset_head:
644         strbuf_release(&msg);
645         rollback_lock_file(&lock);
646         while (nr)
647                 free((void *)desc[--nr].buffer);
648         return ret;
649 }
650
651 static int rebase_config(const char *var, const char *value, void *data)
652 {
653         struct rebase_options *opts = data;
654
655         if (!strcmp(var, "rebase.stat")) {
656                 if (git_config_bool(var, value))
657                         opts->flags |= REBASE_DIFFSTAT;
658                 else
659                         opts->flags &= !REBASE_DIFFSTAT;
660                 return 0;
661         }
662
663         if (!strcmp(var, "rebase.autosquash")) {
664                 opts->autosquash = git_config_bool(var, value);
665                 return 0;
666         }
667
668         if (!strcmp(var, "commit.gpgsign")) {
669                 free(opts->gpg_sign_opt);
670                 opts->gpg_sign_opt = git_config_bool(var, value) ?
671                         xstrdup("-S") : NULL;
672                 return 0;
673         }
674
675         if (!strcmp(var, "rebase.autostash")) {
676                 opts->autostash = git_config_bool(var, value);
677                 return 0;
678         }
679
680         if (!strcmp(var, "rebase.reschedulefailedexec")) {
681                 opts->reschedule_failed_exec = git_config_bool(var, value);
682                 return 0;
683         }
684
685         return git_default_config(var, value, data);
686 }
687
688 /*
689  * Determines whether the commits in from..to are linear, i.e. contain
690  * no merge commits. This function *expects* `from` to be an ancestor of
691  * `to`.
692  */
693 static int is_linear_history(struct commit *from, struct commit *to)
694 {
695         while (to && to != from) {
696                 parse_commit(to);
697                 if (!to->parents)
698                         return 1;
699                 if (to->parents->next)
700                         return 0;
701                 to = to->parents->item;
702         }
703         return 1;
704 }
705
706 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
707                             struct object_id *merge_base)
708 {
709         struct commit *head = lookup_commit(the_repository, head_oid);
710         struct commit_list *merge_bases;
711         int res;
712
713         if (!head)
714                 return 0;
715
716         merge_bases = get_merge_bases(onto, head);
717         if (merge_bases && !merge_bases->next) {
718                 oidcpy(merge_base, &merge_bases->item->object.oid);
719                 res = oideq(merge_base, &onto->object.oid);
720         } else {
721                 oidcpy(merge_base, &null_oid);
722                 res = 0;
723         }
724         free_commit_list(merge_bases);
725         return res && is_linear_history(onto, head);
726 }
727
728 /* -i followed by -m is still -i */
729 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
730 {
731         struct rebase_options *opts = opt->value;
732
733         BUG_ON_OPT_NEG(unset);
734         BUG_ON_OPT_ARG(arg);
735
736         if (!is_interactive(opts))
737                 opts->type = REBASE_MERGE;
738
739         return 0;
740 }
741
742 /* -i followed by -p is still explicitly interactive, but -p alone is not */
743 static int parse_opt_interactive(const struct option *opt, const char *arg,
744                                  int unset)
745 {
746         struct rebase_options *opts = opt->value;
747
748         BUG_ON_OPT_NEG(unset);
749         BUG_ON_OPT_ARG(arg);
750
751         opts->type = REBASE_INTERACTIVE;
752         opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
753
754         return 0;
755 }
756
757 struct opt_y {
758         struct string_list *list;
759         struct rebase_options *options;
760 };
761
762 static int parse_opt_y(const struct option *opt, const char *arg, int unset)
763 {
764         struct opt_y *o = opt->value;
765
766         if (unset || !arg)
767                 return -1;
768
769         o->options->reschedule_failed_exec = 1;
770         string_list_append(o->list, arg);
771         return 0;
772 }
773
774 static void NORETURN error_on_missing_default_upstream(void)
775 {
776         struct branch *current_branch = branch_get(NULL);
777
778         printf(_("%s\n"
779                  "Please specify which branch you want to rebase against.\n"
780                  "See git-rebase(1) for details.\n"
781                  "\n"
782                  "    git rebase '<branch>'\n"
783                  "\n"),
784                 current_branch ? _("There is no tracking information for "
785                         "the current branch.") :
786                         _("You are not currently on a branch."));
787
788         if (current_branch) {
789                 const char *remote = current_branch->remote_name;
790
791                 if (!remote)
792                         remote = _("<remote>");
793
794                 printf(_("If you wish to set tracking information for this "
795                          "branch you can do so with:\n"
796                          "\n"
797                          "    git branch --set-upstream-to=%s/<branch> %s\n"
798                          "\n"),
799                        remote, current_branch->name);
800         }
801         exit(1);
802 }
803
804 static void set_reflog_action(struct rebase_options *options)
805 {
806         const char *env;
807         struct strbuf buf = STRBUF_INIT;
808
809         if (!is_interactive(options))
810                 return;
811
812         env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
813         if (env && strcmp("rebase", env))
814                 return; /* only override it if it is "rebase" */
815
816         strbuf_addf(&buf, "rebase -i (%s)", options->action);
817         setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
818         strbuf_release(&buf);
819 }
820
821 int cmd_rebase(int argc, const char **argv, const char *prefix)
822 {
823         struct rebase_options options = {
824                 .type = REBASE_UNSPECIFIED,
825                 .flags = REBASE_NO_QUIET,
826                 .git_am_opts = ARGV_ARRAY_INIT,
827                 .allow_rerere_autoupdate  = -1,
828                 .allow_empty_message = 1,
829                 .git_format_patch_opt = STRBUF_INIT,
830         };
831         const char *branch_name;
832         int ret, flags, total_argc, in_progress = 0;
833         int ok_to_skip_pre_rebase = 0;
834         struct strbuf msg = STRBUF_INIT;
835         struct strbuf revisions = STRBUF_INIT;
836         struct strbuf buf = STRBUF_INIT;
837         struct object_id merge_base;
838         enum {
839                 NO_ACTION,
840                 ACTION_CONTINUE,
841                 ACTION_SKIP,
842                 ACTION_ABORT,
843                 ACTION_QUIT,
844                 ACTION_EDIT_TODO,
845                 ACTION_SHOW_CURRENT_PATCH,
846         } action = NO_ACTION;
847         const char *gpg_sign = NULL;
848         struct string_list exec = STRING_LIST_INIT_NODUP;
849         const char *rebase_merges = NULL;
850         int fork_point = -1;
851         struct string_list strategy_options = STRING_LIST_INIT_NODUP;
852         struct object_id squash_onto;
853         char *squash_onto_name = NULL;
854         struct opt_y opt_y = { .list = &exec, .options = &options };
855         struct option builtin_rebase_options[] = {
856                 OPT_STRING(0, "onto", &options.onto_name,
857                            N_("revision"),
858                            N_("rebase onto given branch instead of upstream")),
859                 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
860                          N_("allow pre-rebase hook to run")),
861                 OPT_NEGBIT('q', "quiet", &options.flags,
862                            N_("be quiet. implies --no-stat"),
863                            REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
864                 OPT_BIT('v', "verbose", &options.flags,
865                         N_("display a diffstat of what changed upstream"),
866                         REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
867                 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
868                         N_("do not show diffstat of what changed upstream"),
869                         PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
870                 OPT_BOOL(0, "signoff", &options.signoff,
871                          N_("add a Signed-off-by: line to each commit")),
872                 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
873                                   NULL, N_("passed to 'git am'"),
874                                   PARSE_OPT_NOARG),
875                 OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
876                                   &options.git_am_opts, NULL,
877                                   N_("passed to 'git am'"), PARSE_OPT_NOARG),
878                 OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
879                                   N_("passed to 'git am'"), PARSE_OPT_NOARG),
880                 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
881                                   N_("passed to 'git apply'"), 0),
882                 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
883                                   N_("action"), N_("passed to 'git apply'"), 0),
884                 OPT_BIT('f', "force-rebase", &options.flags,
885                         N_("cherry-pick all commits, even if unchanged"),
886                         REBASE_FORCE),
887                 OPT_BIT(0, "no-ff", &options.flags,
888                         N_("cherry-pick all commits, even if unchanged"),
889                         REBASE_FORCE),
890                 OPT_CMDMODE(0, "continue", &action, N_("continue"),
891                             ACTION_CONTINUE),
892                 OPT_CMDMODE(0, "skip", &action,
893                             N_("skip current patch and continue"), ACTION_SKIP),
894                 OPT_CMDMODE(0, "abort", &action,
895                             N_("abort and check out the original branch"),
896                             ACTION_ABORT),
897                 OPT_CMDMODE(0, "quit", &action,
898                             N_("abort but keep HEAD where it is"), ACTION_QUIT),
899                 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
900                             "during an interactive rebase"), ACTION_EDIT_TODO),
901                 OPT_CMDMODE(0, "show-current-patch", &action,
902                             N_("show the patch file being applied or merged"),
903                             ACTION_SHOW_CURRENT_PATCH),
904                 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
905                         N_("use merging strategies to rebase"),
906                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
907                         parse_opt_merge },
908                 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
909                         N_("let the user edit the list of commits to rebase"),
910                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
911                         parse_opt_interactive },
912                 OPT_SET_INT('p', "preserve-merges", &options.type,
913                             N_("try to recreate merges instead of ignoring "
914                                "them"), REBASE_PRESERVE_MERGES),
915                 OPT_BOOL(0, "rerere-autoupdate",
916                          &options.allow_rerere_autoupdate,
917                          N_("allow rerere to update index with resolved "
918                             "conflict")),
919                 OPT_BOOL('k', "keep-empty", &options.keep_empty,
920                          N_("preserve empty commits during rebase")),
921                 OPT_BOOL(0, "autosquash", &options.autosquash,
922                          N_("move commits that begin with "
923                             "squash!/fixup! under -i")),
924                 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
925                         N_("GPG-sign commits"),
926                         PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
927                 OPT_BOOL(0, "autostash", &options.autostash,
928                          N_("automatically stash/stash pop before and after")),
929                 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
930                                 N_("add exec lines after each commit of the "
931                                    "editable list")),
932                 { OPTION_CALLBACK, 'y', NULL, &opt_y, N_("<cmd>"),
933                         N_("same as --reschedule-failed-exec -x <cmd>"),
934                         PARSE_OPT_NONEG, parse_opt_y },
935                 OPT_BOOL(0, "allow-empty-message",
936                          &options.allow_empty_message,
937                          N_("allow rebasing commits with empty messages")),
938                 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
939                         N_("mode"),
940                         N_("try to rebase merges instead of skipping them"),
941                         PARSE_OPT_OPTARG, NULL, (intptr_t)""},
942                 OPT_BOOL(0, "fork-point", &fork_point,
943                          N_("use 'merge-base --fork-point' to refine upstream")),
944                 OPT_STRING('s', "strategy", &options.strategy,
945                            N_("strategy"), N_("use the given merge strategy")),
946                 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
947                                 N_("option"),
948                                 N_("pass the argument through to the merge "
949                                    "strategy")),
950                 OPT_BOOL(0, "root", &options.root,
951                          N_("rebase all reachable commits up to the root(s)")),
952                 OPT_BOOL(0, "reschedule-failed-exec",
953                          &options.reschedule_failed_exec,
954                          N_("automatically re-schedule any `exec` that fails")),
955                 OPT_END(),
956         };
957         int i;
958
959         /*
960          * NEEDSWORK: Once the builtin rebase has been tested enough
961          * and git-legacy-rebase.sh is retired to contrib/, this preamble
962          * can be removed.
963          */
964
965         if (!use_builtin_rebase()) {
966                 const char *path = mkpath("%s/git-legacy-rebase",
967                                           git_exec_path());
968
969                 if (sane_execvp(path, (char **)argv) < 0)
970                         die_errno(_("could not exec %s"), path);
971                 else
972                         BUG("sane_execvp() returned???");
973         }
974
975         if (argc == 2 && !strcmp(argv[1], "-h"))
976                 usage_with_options(builtin_rebase_usage,
977                                    builtin_rebase_options);
978
979         prefix = setup_git_directory();
980         trace_repo_setup(prefix);
981         setup_work_tree();
982
983         git_config(rebase_config, &options);
984
985         strbuf_reset(&buf);
986         strbuf_addf(&buf, "%s/applying", apply_dir());
987         if(file_exists(buf.buf))
988                 die(_("It looks like 'git am' is in progress. Cannot rebase."));
989
990         if (is_directory(apply_dir())) {
991                 options.type = REBASE_AM;
992                 options.state_dir = apply_dir();
993         } else if (is_directory(merge_dir())) {
994                 strbuf_reset(&buf);
995                 strbuf_addf(&buf, "%s/rewritten", merge_dir());
996                 if (is_directory(buf.buf)) {
997                         options.type = REBASE_PRESERVE_MERGES;
998                         options.flags |= REBASE_INTERACTIVE_EXPLICIT;
999                 } else {
1000                         strbuf_reset(&buf);
1001                         strbuf_addf(&buf, "%s/interactive", merge_dir());
1002                         if(file_exists(buf.buf)) {
1003                                 options.type = REBASE_INTERACTIVE;
1004                                 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1005                         } else
1006                                 options.type = REBASE_MERGE;
1007                 }
1008                 options.state_dir = merge_dir();
1009         }
1010
1011         if (options.type != REBASE_UNSPECIFIED)
1012                 in_progress = 1;
1013
1014         total_argc = argc;
1015         argc = parse_options(argc, argv, prefix,
1016                              builtin_rebase_options,
1017                              builtin_rebase_usage, 0);
1018
1019         if (action != NO_ACTION && total_argc != 2) {
1020                 usage_with_options(builtin_rebase_usage,
1021                                    builtin_rebase_options);
1022         }
1023
1024         if (argc > 2)
1025                 usage_with_options(builtin_rebase_usage,
1026                                    builtin_rebase_options);
1027
1028         if (action != NO_ACTION && !in_progress)
1029                 die(_("No rebase in progress?"));
1030         setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1031
1032         if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1033                 die(_("The --edit-todo action can only be used during "
1034                       "interactive rebase."));
1035
1036         switch (action) {
1037         case ACTION_CONTINUE: {
1038                 struct object_id head;
1039                 struct lock_file lock_file = LOCK_INIT;
1040                 int fd;
1041
1042                 options.action = "continue";
1043                 set_reflog_action(&options);
1044
1045                 /* Sanity check */
1046                 if (get_oid("HEAD", &head))
1047                         die(_("Cannot read HEAD"));
1048
1049                 fd = hold_locked_index(&lock_file, 0);
1050                 if (read_index(the_repository->index) < 0)
1051                         die(_("could not read index"));
1052                 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1053                               NULL);
1054                 if (0 <= fd)
1055                         update_index_if_able(the_repository->index,
1056                                              &lock_file);
1057                 rollback_lock_file(&lock_file);
1058
1059                 if (has_unstaged_changes(the_repository, 1)) {
1060                         puts(_("You must edit all merge conflicts and then\n"
1061                                "mark them as resolved using git add"));
1062                         exit(1);
1063                 }
1064                 if (read_basic_state(&options))
1065                         exit(1);
1066                 goto run_rebase;
1067         }
1068         case ACTION_SKIP: {
1069                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1070
1071                 options.action = "skip";
1072                 set_reflog_action(&options);
1073
1074                 rerere_clear(the_repository, &merge_rr);
1075                 string_list_clear(&merge_rr, 1);
1076
1077                 if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1078                                NULL, NULL) < 0)
1079                         die(_("could not discard worktree changes"));
1080                 remove_branch_state(the_repository);
1081                 if (read_basic_state(&options))
1082                         exit(1);
1083                 goto run_rebase;
1084         }
1085         case ACTION_ABORT: {
1086                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1087                 options.action = "abort";
1088                 set_reflog_action(&options);
1089
1090                 rerere_clear(the_repository, &merge_rr);
1091                 string_list_clear(&merge_rr, 1);
1092
1093                 if (read_basic_state(&options))
1094                         exit(1);
1095                 if (reset_head(&options.orig_head, "reset",
1096                                options.head_name, RESET_HEAD_HARD,
1097                                NULL, NULL) < 0)
1098                         die(_("could not move back to %s"),
1099                             oid_to_hex(&options.orig_head));
1100                 remove_branch_state(the_repository);
1101                 ret = finish_rebase(&options);
1102                 goto cleanup;
1103         }
1104         case ACTION_QUIT: {
1105                 strbuf_reset(&buf);
1106                 strbuf_addstr(&buf, options.state_dir);
1107                 ret = !!remove_dir_recursively(&buf, 0);
1108                 if (ret)
1109                         die(_("could not remove '%s'"), options.state_dir);
1110                 goto cleanup;
1111         }
1112         case ACTION_EDIT_TODO:
1113                 options.action = "edit-todo";
1114                 options.dont_finish_rebase = 1;
1115                 goto run_rebase;
1116         case ACTION_SHOW_CURRENT_PATCH:
1117                 options.action = "show-current-patch";
1118                 options.dont_finish_rebase = 1;
1119                 goto run_rebase;
1120         case NO_ACTION:
1121                 break;
1122         default:
1123                 BUG("action: %d", action);
1124         }
1125
1126         /* Make sure no rebase is in progress */
1127         if (in_progress) {
1128                 const char *last_slash = strrchr(options.state_dir, '/');
1129                 const char *state_dir_base =
1130                         last_slash ? last_slash + 1 : options.state_dir;
1131                 const char *cmd_live_rebase =
1132                         "git rebase (--continue | --abort | --skip)";
1133                 strbuf_reset(&buf);
1134                 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1135                 die(_("It seems that there is already a %s directory, and\n"
1136                       "I wonder if you are in the middle of another rebase.  "
1137                       "If that is the\n"
1138                       "case, please try\n\t%s\n"
1139                       "If that is not the case, please\n\t%s\n"
1140                       "and run me again.  I am stopping in case you still "
1141                       "have something\n"
1142                       "valuable there.\n"),
1143                     state_dir_base, cmd_live_rebase, buf.buf);
1144         }
1145
1146         for (i = 0; i < options.git_am_opts.argc; i++) {
1147                 const char *option = options.git_am_opts.argv[i], *p;
1148                 if (!strcmp(option, "--committer-date-is-author-date") ||
1149                     !strcmp(option, "--ignore-date") ||
1150                     !strcmp(option, "--whitespace=fix") ||
1151                     !strcmp(option, "--whitespace=strip"))
1152                         options.flags |= REBASE_FORCE;
1153                 else if (skip_prefix(option, "-C", &p)) {
1154                         while (*p)
1155                                 if (!isdigit(*(p++)))
1156                                         die(_("switch `C' expects a "
1157                                               "numerical value"));
1158                 } else if (skip_prefix(option, "--whitespace=", &p)) {
1159                         if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1160                             strcmp(p, "error") && strcmp(p, "error-all"))
1161                                 die("Invalid whitespace option: '%s'", p);
1162                 }
1163         }
1164
1165         if (!(options.flags & REBASE_NO_QUIET))
1166                 argv_array_push(&options.git_am_opts, "-q");
1167
1168         if (options.keep_empty)
1169                 imply_interactive(&options, "--keep-empty");
1170
1171         if (gpg_sign) {
1172                 free(options.gpg_sign_opt);
1173                 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1174         }
1175
1176         if (exec.nr) {
1177                 int i;
1178
1179                 imply_interactive(&options, "--exec");
1180
1181                 strbuf_reset(&buf);
1182                 for (i = 0; i < exec.nr; i++)
1183                         strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1184                 options.cmd = xstrdup(buf.buf);
1185         }
1186
1187         if (rebase_merges) {
1188                 if (!*rebase_merges)
1189                         ; /* default mode; do nothing */
1190                 else if (!strcmp("rebase-cousins", rebase_merges))
1191                         options.rebase_cousins = 1;
1192                 else if (strcmp("no-rebase-cousins", rebase_merges))
1193                         die(_("Unknown mode: %s"), rebase_merges);
1194                 options.rebase_merges = 1;
1195                 imply_interactive(&options, "--rebase-merges");
1196         }
1197
1198         if (strategy_options.nr) {
1199                 int i;
1200
1201                 if (!options.strategy)
1202                         options.strategy = "recursive";
1203
1204                 strbuf_reset(&buf);
1205                 for (i = 0; i < strategy_options.nr; i++)
1206                         strbuf_addf(&buf, " --%s",
1207                                     strategy_options.items[i].string);
1208                 options.strategy_opts = xstrdup(buf.buf);
1209         }
1210
1211         if (options.strategy) {
1212                 options.strategy = xstrdup(options.strategy);
1213                 switch (options.type) {
1214                 case REBASE_AM:
1215                         die(_("--strategy requires --merge or --interactive"));
1216                 case REBASE_MERGE:
1217                 case REBASE_INTERACTIVE:
1218                 case REBASE_PRESERVE_MERGES:
1219                         /* compatible */
1220                         break;
1221                 case REBASE_UNSPECIFIED:
1222                         options.type = REBASE_MERGE;
1223                         break;
1224                 default:
1225                         BUG("unhandled rebase type (%d)", options.type);
1226                 }
1227         }
1228
1229         if (options.type == REBASE_MERGE)
1230                 imply_interactive(&options, "--merge");
1231
1232         if (options.root && !options.onto_name)
1233                 imply_interactive(&options, "--root without --onto");
1234
1235         if (isatty(2) && options.flags & REBASE_NO_QUIET)
1236                 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1237
1238         switch (options.type) {
1239         case REBASE_MERGE:
1240         case REBASE_INTERACTIVE:
1241         case REBASE_PRESERVE_MERGES:
1242                 options.state_dir = merge_dir();
1243                 break;
1244         case REBASE_AM:
1245                 options.state_dir = apply_dir();
1246                 break;
1247         default:
1248                 /* the default rebase backend is `--am` */
1249                 options.type = REBASE_AM;
1250                 options.state_dir = apply_dir();
1251                 break;
1252         }
1253
1254         if (options.reschedule_failed_exec && !is_interactive(&options))
1255                 die(_("--reschedule-failed-exec requires an interactive rebase"));
1256
1257         if (options.git_am_opts.argc) {
1258                 /* all am options except -q are compatible only with --am */
1259                 for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1260                         if (strcmp(options.git_am_opts.argv[i], "-q"))
1261                                 break;
1262
1263                 if (is_interactive(&options) && i >= 0)
1264                         die(_("cannot combine am options with either "
1265                               "interactive or merge options"));
1266         }
1267
1268         if (options.signoff) {
1269                 if (options.type == REBASE_PRESERVE_MERGES)
1270                         die("cannot combine '--signoff' with "
1271                             "'--preserve-merges'");
1272                 argv_array_push(&options.git_am_opts, "--signoff");
1273                 options.flags |= REBASE_FORCE;
1274         }
1275
1276         if (options.type == REBASE_PRESERVE_MERGES) {
1277                 /*
1278                  * Note: incompatibility with --signoff handled in signoff block above
1279                  * Note: incompatibility with --interactive is just a strong warning;
1280                  *       git-rebase.txt caveats with "unless you know what you are doing"
1281                  */
1282                 if (options.rebase_merges)
1283                         die(_("cannot combine '--preserve-merges' with "
1284                               "'--rebase-merges'"));
1285
1286                 if (options.reschedule_failed_exec)
1287                         die(_("error: cannot combine '--preserve-merges' with "
1288                               "'--reschedule-failed-exec'"));
1289         }
1290
1291         if (options.rebase_merges) {
1292                 if (strategy_options.nr)
1293                         die(_("cannot combine '--rebase-merges' with "
1294                               "'--strategy-option'"));
1295                 if (options.strategy)
1296                         die(_("cannot combine '--rebase-merges' with "
1297                               "'--strategy'"));
1298         }
1299
1300         if (!options.root) {
1301                 if (argc < 1) {
1302                         struct branch *branch;
1303
1304                         branch = branch_get(NULL);
1305                         options.upstream_name = branch_get_upstream(branch,
1306                                                                     NULL);
1307                         if (!options.upstream_name)
1308                                 error_on_missing_default_upstream();
1309                         if (fork_point < 0)
1310                                 fork_point = 1;
1311                 } else {
1312                         options.upstream_name = argv[0];
1313                         argc--;
1314                         argv++;
1315                         if (!strcmp(options.upstream_name, "-"))
1316                                 options.upstream_name = "@{-1}";
1317                 }
1318                 options.upstream = peel_committish(options.upstream_name);
1319                 if (!options.upstream)
1320                         die(_("invalid upstream '%s'"), options.upstream_name);
1321                 options.upstream_arg = options.upstream_name;
1322         } else {
1323                 if (!options.onto_name) {
1324                         if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1325                                         &squash_onto, NULL, NULL) < 0)
1326                                 die(_("Could not create new root commit"));
1327                         options.squash_onto = &squash_onto;
1328                         options.onto_name = squash_onto_name =
1329                                 xstrdup(oid_to_hex(&squash_onto));
1330                 }
1331                 options.upstream_name = NULL;
1332                 options.upstream = NULL;
1333                 if (argc > 1)
1334                         usage_with_options(builtin_rebase_usage,
1335                                            builtin_rebase_options);
1336                 options.upstream_arg = "--root";
1337         }
1338
1339         /* Make sure the branch to rebase onto is valid. */
1340         if (!options.onto_name)
1341                 options.onto_name = options.upstream_name;
1342         if (strstr(options.onto_name, "...")) {
1343                 if (get_oid_mb(options.onto_name, &merge_base) < 0)
1344                         die(_("'%s': need exactly one merge base"),
1345                             options.onto_name);
1346                 options.onto = lookup_commit_or_die(&merge_base,
1347                                                     options.onto_name);
1348         } else {
1349                 options.onto = peel_committish(options.onto_name);
1350                 if (!options.onto)
1351                         die(_("Does not point to a valid commit '%s'"),
1352                                 options.onto_name);
1353         }
1354
1355         /*
1356          * If the branch to rebase is given, that is the branch we will rebase
1357          * branch_name -- branch/commit being rebased, or
1358          *                HEAD (already detached)
1359          * orig_head -- commit object name of tip of the branch before rebasing
1360          * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1361          */
1362         if (argc == 1) {
1363                 /* Is it "rebase other branchname" or "rebase other commit"? */
1364                 branch_name = argv[0];
1365                 options.switch_to = argv[0];
1366
1367                 /* Is it a local branch? */
1368                 strbuf_reset(&buf);
1369                 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1370                 if (!read_ref(buf.buf, &options.orig_head))
1371                         options.head_name = xstrdup(buf.buf);
1372                 /* If not is it a valid ref (branch or commit)? */
1373                 else if (!get_oid(branch_name, &options.orig_head))
1374                         options.head_name = NULL;
1375                 else
1376                         die(_("fatal: no such branch/commit '%s'"),
1377                             branch_name);
1378         } else if (argc == 0) {
1379                 /* Do not need to switch branches, we are already on it. */
1380                 options.head_name =
1381                         xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1382                                          &flags));
1383                 if (!options.head_name)
1384                         die(_("No such ref: %s"), "HEAD");
1385                 if (flags & REF_ISSYMREF) {
1386                         if (!skip_prefix(options.head_name,
1387                                          "refs/heads/", &branch_name))
1388                                 branch_name = options.head_name;
1389
1390                 } else {
1391                         free(options.head_name);
1392                         options.head_name = NULL;
1393                         branch_name = "HEAD";
1394                 }
1395                 if (get_oid("HEAD", &options.orig_head))
1396                         die(_("Could not resolve HEAD to a revision"));
1397         } else
1398                 BUG("unexpected number of arguments left to parse");
1399
1400         if (fork_point > 0) {
1401                 struct commit *head =
1402                         lookup_commit_reference(the_repository,
1403                                                 &options.orig_head);
1404                 options.restrict_revision =
1405                         get_fork_point(options.upstream_name, head);
1406         }
1407
1408         if (read_index(the_repository->index) < 0)
1409                 die(_("could not read index"));
1410
1411         if (options.autostash) {
1412                 struct lock_file lock_file = LOCK_INIT;
1413                 int fd;
1414
1415                 fd = hold_locked_index(&lock_file, 0);
1416                 refresh_cache(REFRESH_QUIET);
1417                 if (0 <= fd)
1418                         update_index_if_able(&the_index, &lock_file);
1419                 rollback_lock_file(&lock_file);
1420
1421                 if (has_unstaged_changes(the_repository, 1) ||
1422                     has_uncommitted_changes(the_repository, 1)) {
1423                         const char *autostash =
1424                                 state_dir_path("autostash", &options);
1425                         struct child_process stash = CHILD_PROCESS_INIT;
1426                         struct object_id oid;
1427                         struct commit *head =
1428                                 lookup_commit_reference(the_repository,
1429                                                         &options.orig_head);
1430
1431                         argv_array_pushl(&stash.args,
1432                                          "stash", "create", "autostash", NULL);
1433                         stash.git_cmd = 1;
1434                         stash.no_stdin = 1;
1435                         strbuf_reset(&buf);
1436                         if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1437                                 die(_("Cannot autostash"));
1438                         strbuf_trim_trailing_newline(&buf);
1439                         if (get_oid(buf.buf, &oid))
1440                                 die(_("Unexpected stash response: '%s'"),
1441                                     buf.buf);
1442                         strbuf_reset(&buf);
1443                         strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1444
1445                         if (safe_create_leading_directories_const(autostash))
1446                                 die(_("Could not create directory for '%s'"),
1447                                     options.state_dir);
1448                         write_file(autostash, "%s", oid_to_hex(&oid));
1449                         printf(_("Created autostash: %s\n"), buf.buf);
1450                         if (reset_head(&head->object.oid, "reset --hard",
1451                                        NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
1452                                 die(_("could not reset --hard"));
1453                         printf(_("HEAD is now at %s"),
1454                                find_unique_abbrev(&head->object.oid,
1455                                                   DEFAULT_ABBREV));
1456                         strbuf_reset(&buf);
1457                         pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1458                         if (buf.len > 0)
1459                                 printf(" %s", buf.buf);
1460                         putchar('\n');
1461
1462                         if (discard_index(the_repository->index) < 0 ||
1463                                 read_index(the_repository->index) < 0)
1464                                 die(_("could not read index"));
1465                 }
1466         }
1467
1468         if (require_clean_work_tree(the_repository, "rebase",
1469                                     _("Please commit or stash them."), 1, 1)) {
1470                 ret = 1;
1471                 goto cleanup;
1472         }
1473
1474         /*
1475          * Now we are rebasing commits upstream..orig_head (or with --root,
1476          * everything leading up to orig_head) on top of onto.
1477          */
1478
1479         /*
1480          * Check if we are already based on onto with linear history,
1481          * but this should be done only when upstream and onto are the same
1482          * and if this is not an interactive rebase.
1483          */
1484         if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1485             !is_interactive(&options) && !options.restrict_revision &&
1486             options.upstream &&
1487             !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1488                 int flag;
1489
1490                 if (!(options.flags & REBASE_FORCE)) {
1491                         /* Lazily switch to the target branch if needed... */
1492                         if (options.switch_to) {
1493                                 struct object_id oid;
1494
1495                                 if (get_oid(options.switch_to, &oid) < 0) {
1496                                         ret = !!error(_("could not parse '%s'"),
1497                                                       options.switch_to);
1498                                         goto cleanup;
1499                                 }
1500
1501                                 strbuf_reset(&buf);
1502                                 strbuf_addf(&buf, "%s: checkout %s",
1503                                             getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
1504                                             options.switch_to);
1505                                 if (reset_head(&oid, "checkout",
1506                                                options.head_name,
1507                                                RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
1508                                                NULL, buf.buf) < 0) {
1509                                         ret = !!error(_("could not switch to "
1510                                                         "%s"),
1511                                                       options.switch_to);
1512                                         goto cleanup;
1513                                 }
1514                         }
1515
1516                         if (!(options.flags & REBASE_NO_QUIET))
1517                                 ; /* be quiet */
1518                         else if (!strcmp(branch_name, "HEAD") &&
1519                                  resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1520                                 puts(_("HEAD is up to date."));
1521                         else
1522                                 printf(_("Current branch %s is up to date.\n"),
1523                                        branch_name);
1524                         ret = !!finish_rebase(&options);
1525                         goto cleanup;
1526                 } else if (!(options.flags & REBASE_NO_QUIET))
1527                         ; /* be quiet */
1528                 else if (!strcmp(branch_name, "HEAD") &&
1529                          resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1530                         puts(_("HEAD is up to date, rebase forced."));
1531                 else
1532                         printf(_("Current branch %s is up to date, rebase "
1533                                  "forced.\n"), branch_name);
1534         }
1535
1536         /* If a hook exists, give it a chance to interrupt*/
1537         if (!ok_to_skip_pre_rebase &&
1538             run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1539                         argc ? argv[0] : NULL, NULL))
1540                 die(_("The pre-rebase hook refused to rebase."));
1541
1542         if (options.flags & REBASE_DIFFSTAT) {
1543                 struct diff_options opts;
1544
1545                 if (options.flags & REBASE_VERBOSE) {
1546                         if (is_null_oid(&merge_base))
1547                                 printf(_("Changes to %s:\n"),
1548                                        oid_to_hex(&options.onto->object.oid));
1549                         else
1550                                 printf(_("Changes from %s to %s:\n"),
1551                                        oid_to_hex(&merge_base),
1552                                        oid_to_hex(&options.onto->object.oid));
1553                 }
1554
1555                 /* We want color (if set), but no pager */
1556                 diff_setup(&opts);
1557                 opts.stat_width = -1; /* use full terminal width */
1558                 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1559                 opts.output_format |=
1560                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1561                 opts.detect_rename = DIFF_DETECT_RENAME;
1562                 diff_setup_done(&opts);
1563                 diff_tree_oid(is_null_oid(&merge_base) ?
1564                               the_hash_algo->empty_tree : &merge_base,
1565                               &options.onto->object.oid, "", &opts);
1566                 diffcore_std(&opts);
1567                 diff_flush(&opts);
1568         }
1569
1570         if (is_interactive(&options))
1571                 goto run_rebase;
1572
1573         /* Detach HEAD and reset the tree */
1574         if (options.flags & REBASE_NO_QUIET)
1575                 printf(_("First, rewinding head to replay your work on top of "
1576                          "it...\n"));
1577
1578         strbuf_addf(&msg, "%s: checkout %s",
1579                     getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1580         if (reset_head(&options.onto->object.oid, "checkout", NULL,
1581                        RESET_HEAD_DETACH | RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
1582                        NULL, msg.buf))
1583                 die(_("Could not detach HEAD"));
1584         strbuf_release(&msg);
1585
1586         /*
1587          * If the onto is a proper descendant of the tip of the branch, then
1588          * we just fast-forwarded.
1589          */
1590         strbuf_reset(&msg);
1591         if (!oidcmp(&merge_base, &options.orig_head)) {
1592                 printf(_("Fast-forwarded %s to %s.\n"),
1593                         branch_name, options.onto_name);
1594                 strbuf_addf(&msg, "rebase finished: %s onto %s",
1595                         options.head_name ? options.head_name : "detached HEAD",
1596                         oid_to_hex(&options.onto->object.oid));
1597                 reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1598                            "HEAD", msg.buf);
1599                 strbuf_release(&msg);
1600                 ret = !!finish_rebase(&options);
1601                 goto cleanup;
1602         }
1603
1604         strbuf_addf(&revisions, "%s..%s",
1605                     options.root ? oid_to_hex(&options.onto->object.oid) :
1606                     (options.restrict_revision ?
1607                      oid_to_hex(&options.restrict_revision->object.oid) :
1608                      oid_to_hex(&options.upstream->object.oid)),
1609                     oid_to_hex(&options.orig_head));
1610
1611         options.revisions = revisions.buf;
1612
1613 run_rebase:
1614         ret = !!run_specific_rebase(&options);
1615
1616 cleanup:
1617         strbuf_release(&revisions);
1618         free(options.head_name);
1619         free(options.gpg_sign_opt);
1620         free(options.cmd);
1621         free(squash_onto_name);
1622         return ret;
1623 }