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