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