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