builtin rebase: support `--autostash` option
[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 0;
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 commit *restrict_revision;
80         int dont_finish_rebase;
81         enum {
82                 REBASE_NO_QUIET = 1<<0,
83                 REBASE_VERBOSE = 1<<1,
84                 REBASE_DIFFSTAT = 1<<2,
85                 REBASE_FORCE = 1<<3,
86                 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
87         } flags;
88         struct strbuf git_am_opt;
89         const char *action;
90         int signoff;
91         int allow_rerere_autoupdate;
92         int keep_empty;
93         int autosquash;
94         char *gpg_sign_opt;
95         int autostash;
96 };
97
98 static int is_interactive(struct rebase_options *opts)
99 {
100         return opts->type == REBASE_INTERACTIVE ||
101                 opts->type == REBASE_PRESERVE_MERGES;
102 }
103
104 static void imply_interactive(struct rebase_options *opts, const char *option)
105 {
106         switch (opts->type) {
107         case REBASE_AM:
108                 die(_("%s requires an interactive rebase"), option);
109                 break;
110         case REBASE_INTERACTIVE:
111         case REBASE_PRESERVE_MERGES:
112                 break;
113         case REBASE_MERGE:
114                 /* we silently *upgrade* --merge to --interactive if needed */
115         default:
116                 opts->type = REBASE_INTERACTIVE; /* implied */
117                 break;
118         }
119 }
120
121 /* Returns the filename prefixed by the state_dir */
122 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
123 {
124         static struct strbuf path = STRBUF_INIT;
125         static size_t prefix_len;
126
127         if (!prefix_len) {
128                 strbuf_addf(&path, "%s/", opts->state_dir);
129                 prefix_len = path.len;
130         }
131
132         strbuf_setlen(&path, prefix_len);
133         strbuf_addstr(&path, filename);
134         return path.buf;
135 }
136
137 /* Read one file, then strip line endings */
138 static int read_one(const char *path, struct strbuf *buf)
139 {
140         if (strbuf_read_file(buf, path, 0) < 0)
141                 return error_errno(_("could not read '%s'"), path);
142         strbuf_trim_trailing_newline(buf);
143         return 0;
144 }
145
146 /* Initialize the rebase options from the state directory. */
147 static int read_basic_state(struct rebase_options *opts)
148 {
149         struct strbuf head_name = STRBUF_INIT;
150         struct strbuf buf = STRBUF_INIT;
151         struct object_id oid;
152
153         if (read_one(state_dir_path("head-name", opts), &head_name) ||
154             read_one(state_dir_path("onto", opts), &buf))
155                 return -1;
156         opts->head_name = starts_with(head_name.buf, "refs/") ?
157                 xstrdup(head_name.buf) : NULL;
158         strbuf_release(&head_name);
159         if (get_oid(buf.buf, &oid))
160                 return error(_("could not get 'onto': '%s'"), buf.buf);
161         opts->onto = lookup_commit_or_die(&oid, buf.buf);
162
163         /*
164          * We always write to orig-head, but interactive rebase used to write to
165          * head. Fall back to reading from head to cover for the case that the
166          * user upgraded git with an ongoing interactive rebase.
167          */
168         strbuf_reset(&buf);
169         if (file_exists(state_dir_path("orig-head", opts))) {
170                 if (read_one(state_dir_path("orig-head", opts), &buf))
171                         return -1;
172         } else if (read_one(state_dir_path("head", opts), &buf))
173                 return -1;
174         if (get_oid(buf.buf, &opts->orig_head))
175                 return error(_("invalid orig-head: '%s'"), buf.buf);
176
177         strbuf_reset(&buf);
178         if (read_one(state_dir_path("quiet", opts), &buf))
179                 return -1;
180         if (buf.len)
181                 opts->flags &= ~REBASE_NO_QUIET;
182         else
183                 opts->flags |= REBASE_NO_QUIET;
184
185         if (file_exists(state_dir_path("verbose", opts)))
186                 opts->flags |= REBASE_VERBOSE;
187
188         if (file_exists(state_dir_path("signoff", opts))) {
189                 opts->signoff = 1;
190                 opts->flags |= REBASE_FORCE;
191         }
192
193         if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
194                 strbuf_reset(&buf);
195                 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
196                             &buf))
197                         return -1;
198                 if (!strcmp(buf.buf, "--rerere-autoupdate"))
199                         opts->allow_rerere_autoupdate = 1;
200                 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
201                         opts->allow_rerere_autoupdate = 0;
202                 else
203                         warning(_("ignoring invalid allow_rerere_autoupdate: "
204                                   "'%s'"), buf.buf);
205         } else
206                 opts->allow_rerere_autoupdate = -1;
207
208         if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
209                 strbuf_reset(&buf);
210                 if (read_one(state_dir_path("gpg_sign_opt", opts),
211                             &buf))
212                         return -1;
213                 free(opts->gpg_sign_opt);
214                 opts->gpg_sign_opt = xstrdup(buf.buf);
215         }
216
217         strbuf_release(&buf);
218
219         return 0;
220 }
221
222 static int apply_autostash(struct rebase_options *opts)
223 {
224         const char *path = state_dir_path("autostash", opts);
225         struct strbuf autostash = STRBUF_INIT;
226         struct child_process stash_apply = CHILD_PROCESS_INIT;
227
228         if (!file_exists(path))
229                 return 0;
230
231         if (read_one(state_dir_path("autostash", opts), &autostash))
232                 return error(_("Could not read '%s'"), path);
233         argv_array_pushl(&stash_apply.args,
234                          "stash", "apply", autostash.buf, NULL);
235         stash_apply.git_cmd = 1;
236         stash_apply.no_stderr = stash_apply.no_stdout =
237                 stash_apply.no_stdin = 1;
238         if (!run_command(&stash_apply))
239                 printf(_("Applied autostash.\n"));
240         else {
241                 struct argv_array args = ARGV_ARRAY_INIT;
242                 int res = 0;
243
244                 argv_array_pushl(&args,
245                                  "stash", "store", "-m", "autostash", "-q",
246                                  autostash.buf, NULL);
247                 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
248                         res = error(_("Cannot store %s"), autostash.buf);
249                 argv_array_clear(&args);
250                 strbuf_release(&autostash);
251                 if (res)
252                         return res;
253
254                 fprintf(stderr,
255                         _("Applying autostash resulted in conflicts.\n"
256                           "Your changes are safe in the stash.\n"
257                           "You can run \"git stash pop\" or \"git stash drop\" "
258                           "at any time.\n"));
259         }
260
261         strbuf_release(&autostash);
262         return 0;
263 }
264
265 static int finish_rebase(struct rebase_options *opts)
266 {
267         struct strbuf dir = STRBUF_INIT;
268         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
269
270         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
271         apply_autostash(opts);
272         close_all_packs(the_repository->objects);
273         /*
274          * We ignore errors in 'gc --auto', since the
275          * user should see them.
276          */
277         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
278         strbuf_addstr(&dir, opts->state_dir);
279         remove_dir_recursively(&dir, 0);
280         strbuf_release(&dir);
281
282         return 0;
283 }
284
285 static struct commit *peel_committish(const char *name)
286 {
287         struct object *obj;
288         struct object_id oid;
289
290         if (get_oid(name, &oid))
291                 return NULL;
292         obj = parse_object(the_repository, &oid);
293         return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
294 }
295
296 static void add_var(struct strbuf *buf, const char *name, const char *value)
297 {
298         if (!value)
299                 strbuf_addf(buf, "unset %s; ", name);
300         else {
301                 strbuf_addf(buf, "%s=", name);
302                 sq_quote_buf(buf, value);
303                 strbuf_addstr(buf, "; ");
304         }
305 }
306
307 static int run_specific_rebase(struct rebase_options *opts)
308 {
309         const char *argv[] = { NULL, NULL };
310         struct strbuf script_snippet = STRBUF_INIT;
311         int status;
312         const char *backend, *backend_func;
313
314         add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
315         add_var(&script_snippet, "state_dir", opts->state_dir);
316
317         add_var(&script_snippet, "upstream_name", opts->upstream_name);
318         add_var(&script_snippet, "upstream", opts->upstream ?
319                 oid_to_hex(&opts->upstream->object.oid) : NULL);
320         add_var(&script_snippet, "head_name",
321                 opts->head_name ? opts->head_name : "detached HEAD");
322         add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
323         add_var(&script_snippet, "onto", opts->onto ?
324                 oid_to_hex(&opts->onto->object.oid) : NULL);
325         add_var(&script_snippet, "onto_name", opts->onto_name);
326         add_var(&script_snippet, "revisions", opts->revisions);
327         add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
328                 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
329         add_var(&script_snippet, "GIT_QUIET",
330                 opts->flags & REBASE_NO_QUIET ? "" : "t");
331         add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
332         add_var(&script_snippet, "verbose",
333                 opts->flags & REBASE_VERBOSE ? "t" : "");
334         add_var(&script_snippet, "diffstat",
335                 opts->flags & REBASE_DIFFSTAT ? "t" : "");
336         add_var(&script_snippet, "force_rebase",
337                 opts->flags & REBASE_FORCE ? "t" : "");
338         if (opts->switch_to)
339                 add_var(&script_snippet, "switch_to", opts->switch_to);
340         add_var(&script_snippet, "action", opts->action ? opts->action : "");
341         add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
342         add_var(&script_snippet, "allow_rerere_autoupdate",
343                 opts->allow_rerere_autoupdate < 0 ? "" :
344                 opts->allow_rerere_autoupdate ?
345                 "--rerere-autoupdate" : "--no-rerere-autoupdate");
346         add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
347         add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
348         add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
349
350         switch (opts->type) {
351         case REBASE_AM:
352                 backend = "git-rebase--am";
353                 backend_func = "git_rebase__am";
354                 break;
355         case REBASE_INTERACTIVE:
356                 backend = "git-rebase--interactive";
357                 backend_func = "git_rebase__interactive";
358                 break;
359         case REBASE_MERGE:
360                 backend = "git-rebase--merge";
361                 backend_func = "git_rebase__merge";
362                 break;
363         case REBASE_PRESERVE_MERGES:
364                 backend = "git-rebase--preserve-merges";
365                 backend_func = "git_rebase__preserve_merges";
366                 break;
367         default:
368                 BUG("Unhandled rebase type %d", opts->type);
369                 break;
370         }
371
372         strbuf_addf(&script_snippet,
373                     ". git-sh-setup && . git-rebase--common &&"
374                     " . %s && %s", backend, backend_func);
375         argv[0] = script_snippet.buf;
376
377         status = run_command_v_opt(argv, RUN_USING_SHELL);
378         if (opts->dont_finish_rebase)
379                 ; /* do nothing */
380         else if (status == 0) {
381                 if (!file_exists(state_dir_path("stopped-sha", opts)))
382                         finish_rebase(opts);
383         } else if (status == 2) {
384                 struct strbuf dir = STRBUF_INIT;
385
386                 apply_autostash(opts);
387                 strbuf_addstr(&dir, opts->state_dir);
388                 remove_dir_recursively(&dir, 0);
389                 strbuf_release(&dir);
390                 die("Nothing to do");
391         }
392
393         strbuf_release(&script_snippet);
394
395         return status ? -1 : 0;
396 }
397
398 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
399
400 static int reset_head(struct object_id *oid, const char *action,
401                       const char *switch_to_branch, int detach_head)
402 {
403         struct object_id head_oid;
404         struct tree_desc desc;
405         struct lock_file lock = LOCK_INIT;
406         struct unpack_trees_options unpack_tree_opts;
407         struct tree *tree;
408         const char *reflog_action;
409         struct strbuf msg = STRBUF_INIT;
410         size_t prefix_len;
411         struct object_id *orig = NULL, oid_orig,
412                 *old_orig = NULL, oid_old_orig;
413         int ret = 0;
414
415         if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
416                 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
417
418         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
419                 return -1;
420
421         if (!oid) {
422                 if (get_oid("HEAD", &head_oid)) {
423                         rollback_lock_file(&lock);
424                         return error(_("could not determine HEAD revision"));
425                 }
426                 oid = &head_oid;
427         }
428
429         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
430         setup_unpack_trees_porcelain(&unpack_tree_opts, action);
431         unpack_tree_opts.head_idx = 1;
432         unpack_tree_opts.src_index = the_repository->index;
433         unpack_tree_opts.dst_index = the_repository->index;
434         unpack_tree_opts.fn = oneway_merge;
435         unpack_tree_opts.update = 1;
436         unpack_tree_opts.merge = 1;
437         if (!detach_head)
438                 unpack_tree_opts.reset = 1;
439
440         if (read_index_unmerged(the_repository->index) < 0) {
441                 rollback_lock_file(&lock);
442                 return error(_("could not read index"));
443         }
444
445         if (!fill_tree_descriptor(&desc, oid)) {
446                 error(_("failed to find tree of %s"), oid_to_hex(oid));
447                 rollback_lock_file(&lock);
448                 free((void *)desc.buffer);
449                 return -1;
450         }
451
452         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
453                 rollback_lock_file(&lock);
454                 free((void *)desc.buffer);
455                 return -1;
456         }
457
458         tree = parse_tree_indirect(oid);
459         prime_cache_tree(the_repository->index, tree);
460
461         if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
462                 ret = error(_("could not write index"));
463         free((void *)desc.buffer);
464
465         if (ret)
466                 return ret;
467
468         reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
469         strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
470         prefix_len = msg.len;
471
472         if (!get_oid("ORIG_HEAD", &oid_old_orig))
473                 old_orig = &oid_old_orig;
474         if (!get_oid("HEAD", &oid_orig)) {
475                 orig = &oid_orig;
476                 strbuf_addstr(&msg, "updating ORIG_HEAD");
477                 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
478                            UPDATE_REFS_MSG_ON_ERR);
479         } else if (old_orig)
480                 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
481         strbuf_setlen(&msg, prefix_len);
482         strbuf_addstr(&msg, "updating HEAD");
483         if (!switch_to_branch)
484                 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
485                                  UPDATE_REFS_MSG_ON_ERR);
486         else {
487                 ret = create_symref("HEAD", switch_to_branch, msg.buf);
488                 if (!ret)
489                         ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
490                                          UPDATE_REFS_MSG_ON_ERR);
491         }
492
493         strbuf_release(&msg);
494         return ret;
495 }
496
497 static int rebase_config(const char *var, const char *value, void *data)
498 {
499         struct rebase_options *opts = data;
500
501         if (!strcmp(var, "rebase.stat")) {
502                 if (git_config_bool(var, value))
503                         opts->flags |= REBASE_DIFFSTAT;
504                 else
505                         opts->flags &= !REBASE_DIFFSTAT;
506                 return 0;
507         }
508
509         if (!strcmp(var, "rebase.autosquash")) {
510                 opts->autosquash = git_config_bool(var, value);
511                 return 0;
512         }
513
514         if (!strcmp(var, "commit.gpgsign")) {
515                 free(opts->gpg_sign_opt);
516                 opts->gpg_sign_opt = git_config_bool(var, value) ?
517                         xstrdup("-S") : NULL;
518                 return 0;
519         }
520
521         if (!strcmp(var, "rebase.autostash")) {
522                 opts->autostash = git_config_bool(var, value);
523                 return 0;
524         }
525
526         return git_default_config(var, value, data);
527 }
528
529 /*
530  * Determines whether the commits in from..to are linear, i.e. contain
531  * no merge commits. This function *expects* `from` to be an ancestor of
532  * `to`.
533  */
534 static int is_linear_history(struct commit *from, struct commit *to)
535 {
536         while (to && to != from) {
537                 parse_commit(to);
538                 if (!to->parents)
539                         return 1;
540                 if (to->parents->next)
541                         return 0;
542                 to = to->parents->item;
543         }
544         return 1;
545 }
546
547 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
548                             struct object_id *merge_base)
549 {
550         struct commit *head = lookup_commit(the_repository, head_oid);
551         struct commit_list *merge_bases;
552         int res;
553
554         if (!head)
555                 return 0;
556
557         merge_bases = get_merge_bases(onto, head);
558         if (merge_bases && !merge_bases->next) {
559                 oidcpy(merge_base, &merge_bases->item->object.oid);
560                 res = !oidcmp(merge_base, &onto->object.oid);
561         } else {
562                 oidcpy(merge_base, &null_oid);
563                 res = 0;
564         }
565         free_commit_list(merge_bases);
566         return res && is_linear_history(onto, head);
567 }
568
569 /* -i followed by -m is still -i */
570 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
571 {
572         struct rebase_options *opts = opt->value;
573
574         if (!is_interactive(opts))
575                 opts->type = REBASE_MERGE;
576
577         return 0;
578 }
579
580 /* -i followed by -p is still explicitly interactive, but -p alone is not */
581 static int parse_opt_interactive(const struct option *opt, const char *arg,
582                                  int unset)
583 {
584         struct rebase_options *opts = opt->value;
585
586         opts->type = REBASE_INTERACTIVE;
587         opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
588
589         return 0;
590 }
591
592 int cmd_rebase(int argc, const char **argv, const char *prefix)
593 {
594         struct rebase_options options = {
595                 .type = REBASE_UNSPECIFIED,
596                 .flags = REBASE_NO_QUIET,
597                 .git_am_opt = STRBUF_INIT,
598                 .allow_rerere_autoupdate  = -1,
599         };
600         const char *branch_name;
601         int ret, flags, total_argc, in_progress = 0;
602         int ok_to_skip_pre_rebase = 0;
603         struct strbuf msg = STRBUF_INIT;
604         struct strbuf revisions = STRBUF_INIT;
605         struct strbuf buf = STRBUF_INIT;
606         struct object_id merge_base;
607         enum {
608                 NO_ACTION,
609                 ACTION_CONTINUE,
610                 ACTION_SKIP,
611                 ACTION_ABORT,
612                 ACTION_QUIT,
613                 ACTION_EDIT_TODO,
614                 ACTION_SHOW_CURRENT_PATCH,
615         } action = NO_ACTION;
616         int committer_date_is_author_date = 0;
617         int ignore_date = 0;
618         int ignore_whitespace = 0;
619         const char *gpg_sign = NULL;
620         int opt_c = -1;
621         struct string_list whitespace = STRING_LIST_INIT_NODUP;
622         struct option builtin_rebase_options[] = {
623                 OPT_STRING(0, "onto", &options.onto_name,
624                            N_("revision"),
625                            N_("rebase onto given branch instead of upstream")),
626                 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
627                          N_("allow pre-rebase hook to run")),
628                 OPT_NEGBIT('q', "quiet", &options.flags,
629                            N_("be quiet. implies --no-stat"),
630                            REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
631                 OPT_BIT('v', "verbose", &options.flags,
632                         N_("display a diffstat of what changed upstream"),
633                         REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
634                 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
635                         N_("do not show diffstat of what changed upstream"),
636                         PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
637                 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
638                          N_("passed to 'git apply'")),
639                 OPT_BOOL(0, "signoff", &options.signoff,
640                          N_("add a Signed-off-by: line to each commit")),
641                 OPT_BOOL(0, "committer-date-is-author-date",
642                          &committer_date_is_author_date,
643                          N_("passed to 'git am'")),
644                 OPT_BOOL(0, "ignore-date", &ignore_date,
645                          N_("passed to 'git am'")),
646                 OPT_BIT('f', "force-rebase", &options.flags,
647                         N_("cherry-pick all commits, even if unchanged"),
648                         REBASE_FORCE),
649                 OPT_BIT(0, "no-ff", &options.flags,
650                         N_("cherry-pick all commits, even if unchanged"),
651                         REBASE_FORCE),
652                 OPT_CMDMODE(0, "continue", &action, N_("continue"),
653                             ACTION_CONTINUE),
654                 OPT_CMDMODE(0, "skip", &action,
655                             N_("skip current patch and continue"), ACTION_SKIP),
656                 OPT_CMDMODE(0, "abort", &action,
657                             N_("abort and check out the original branch"),
658                             ACTION_ABORT),
659                 OPT_CMDMODE(0, "quit", &action,
660                             N_("abort but keep HEAD where it is"), ACTION_QUIT),
661                 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
662                             "during an interactive rebase"), ACTION_EDIT_TODO),
663                 OPT_CMDMODE(0, "show-current-patch", &action,
664                             N_("show the patch file being applied or merged"),
665                             ACTION_SHOW_CURRENT_PATCH),
666                 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
667                         N_("use merging strategies to rebase"),
668                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
669                         parse_opt_merge },
670                 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
671                         N_("let the user edit the list of commits to rebase"),
672                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
673                         parse_opt_interactive },
674                 OPT_SET_INT('p', "preserve-merges", &options.type,
675                             N_("try to recreate merges instead of ignoring "
676                                "them"), REBASE_PRESERVE_MERGES),
677                 OPT_BOOL(0, "rerere-autoupdate",
678                          &options.allow_rerere_autoupdate,
679                          N_("allow rerere to update index  with resolved "
680                             "conflict")),
681                 OPT_BOOL('k', "keep-empty", &options.keep_empty,
682                          N_("preserve empty commits during rebase")),
683                 OPT_BOOL(0, "autosquash", &options.autosquash,
684                          N_("move commits that begin with "
685                             "squash!/fixup! under -i")),
686                 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
687                         N_("GPG-sign commits"),
688                         PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
689                 OPT_STRING_LIST(0, "whitespace", &whitespace,
690                                 N_("whitespace"), N_("passed to 'git apply'")),
691                 OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
692                             REBASE_AM),
693                 OPT_BOOL(0, "autostash", &options.autostash,
694                          N_("automatically stash/stash pop before and after")),
695                 OPT_END(),
696         };
697
698         /*
699          * NEEDSWORK: Once the builtin rebase has been tested enough
700          * and git-legacy-rebase.sh is retired to contrib/, this preamble
701          * can be removed.
702          */
703
704         if (!use_builtin_rebase()) {
705                 const char *path = mkpath("%s/git-legacy-rebase",
706                                           git_exec_path());
707
708                 if (sane_execvp(path, (char **)argv) < 0)
709                         die_errno(_("could not exec %s"), path);
710                 else
711                         BUG("sane_execvp() returned???");
712         }
713
714         if (argc == 2 && !strcmp(argv[1], "-h"))
715                 usage_with_options(builtin_rebase_usage,
716                                    builtin_rebase_options);
717
718         prefix = setup_git_directory();
719         trace_repo_setup(prefix);
720         setup_work_tree();
721
722         git_config(rebase_config, &options);
723
724         strbuf_reset(&buf);
725         strbuf_addf(&buf, "%s/applying", apply_dir());
726         if(file_exists(buf.buf))
727                 die(_("It looks like 'git am' is in progress. Cannot rebase."));
728
729         if (is_directory(apply_dir())) {
730                 options.type = REBASE_AM;
731                 options.state_dir = apply_dir();
732         } else if (is_directory(merge_dir())) {
733                 strbuf_reset(&buf);
734                 strbuf_addf(&buf, "%s/rewritten", merge_dir());
735                 if (is_directory(buf.buf)) {
736                         options.type = REBASE_PRESERVE_MERGES;
737                         options.flags |= REBASE_INTERACTIVE_EXPLICIT;
738                 } else {
739                         strbuf_reset(&buf);
740                         strbuf_addf(&buf, "%s/interactive", merge_dir());
741                         if(file_exists(buf.buf)) {
742                                 options.type = REBASE_INTERACTIVE;
743                                 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
744                         } else
745                                 options.type = REBASE_MERGE;
746                 }
747                 options.state_dir = merge_dir();
748         }
749
750         if (options.type != REBASE_UNSPECIFIED)
751                 in_progress = 1;
752
753         total_argc = argc;
754         argc = parse_options(argc, argv, prefix,
755                              builtin_rebase_options,
756                              builtin_rebase_usage, 0);
757
758         if (action != NO_ACTION && total_argc != 2) {
759                 usage_with_options(builtin_rebase_usage,
760                                    builtin_rebase_options);
761         }
762
763         if (argc > 2)
764                 usage_with_options(builtin_rebase_usage,
765                                    builtin_rebase_options);
766
767         if (action != NO_ACTION && !in_progress)
768                 die(_("No rebase in progress?"));
769
770         if (action == ACTION_EDIT_TODO && !is_interactive(&options))
771                 die(_("The --edit-todo action can only be used during "
772                       "interactive rebase."));
773
774         switch (action) {
775         case ACTION_CONTINUE: {
776                 struct object_id head;
777                 struct lock_file lock_file = LOCK_INIT;
778                 int fd;
779
780                 options.action = "continue";
781
782                 /* Sanity check */
783                 if (get_oid("HEAD", &head))
784                         die(_("Cannot read HEAD"));
785
786                 fd = hold_locked_index(&lock_file, 0);
787                 if (read_index(the_repository->index) < 0)
788                         die(_("could not read index"));
789                 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
790                               NULL);
791                 if (0 <= fd)
792                         update_index_if_able(the_repository->index,
793                                              &lock_file);
794                 rollback_lock_file(&lock_file);
795
796                 if (has_unstaged_changes(1)) {
797                         puts(_("You must edit all merge conflicts and then\n"
798                                "mark them as resolved using git add"));
799                         exit(1);
800                 }
801                 if (read_basic_state(&options))
802                         exit(1);
803                 goto run_rebase;
804         }
805         case ACTION_SKIP: {
806                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
807
808                 options.action = "skip";
809
810                 rerere_clear(&merge_rr);
811                 string_list_clear(&merge_rr, 1);
812
813                 if (reset_head(NULL, "reset", NULL, 0) < 0)
814                         die(_("could not discard worktree changes"));
815                 if (read_basic_state(&options))
816                         exit(1);
817                 goto run_rebase;
818         }
819         case ACTION_ABORT: {
820                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
821                 options.action = "abort";
822
823                 rerere_clear(&merge_rr);
824                 string_list_clear(&merge_rr, 1);
825
826                 if (read_basic_state(&options))
827                         exit(1);
828                 if (reset_head(&options.orig_head, "reset",
829                                options.head_name, 0) < 0)
830                         die(_("could not move back to %s"),
831                             oid_to_hex(&options.orig_head));
832                 ret = finish_rebase(&options);
833                 goto cleanup;
834         }
835         case ACTION_QUIT: {
836                 strbuf_reset(&buf);
837                 strbuf_addstr(&buf, options.state_dir);
838                 ret = !!remove_dir_recursively(&buf, 0);
839                 if (ret)
840                         die(_("could not remove '%s'"), options.state_dir);
841                 goto cleanup;
842         }
843         case ACTION_EDIT_TODO:
844                 options.action = "edit-todo";
845                 options.dont_finish_rebase = 1;
846                 goto run_rebase;
847         case ACTION_SHOW_CURRENT_PATCH:
848                 options.action = "show-current-patch";
849                 options.dont_finish_rebase = 1;
850                 goto run_rebase;
851         case NO_ACTION:
852                 break;
853         default:
854                 BUG("action: %d", action);
855         }
856
857         /* Make sure no rebase is in progress */
858         if (in_progress) {
859                 const char *last_slash = strrchr(options.state_dir, '/');
860                 const char *state_dir_base =
861                         last_slash ? last_slash + 1 : options.state_dir;
862                 const char *cmd_live_rebase =
863                         "git rebase (--continue | --abort | --skip)";
864                 strbuf_reset(&buf);
865                 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
866                 die(_("It seems that there is already a %s directory, and\n"
867                       "I wonder if you are in the middle of another rebase.  "
868                       "If that is the\n"
869                       "case, please try\n\t%s\n"
870                       "If that is not the case, please\n\t%s\n"
871                       "and run me again.  I am stopping in case you still "
872                       "have something\n"
873                       "valuable there.\n"),
874                     state_dir_base, cmd_live_rebase, buf.buf);
875         }
876
877         if (!(options.flags & REBASE_NO_QUIET))
878                 strbuf_addstr(&options.git_am_opt, " -q");
879
880         if (committer_date_is_author_date) {
881                 strbuf_addstr(&options.git_am_opt,
882                               " --committer-date-is-author-date");
883                 options.flags |= REBASE_FORCE;
884         }
885
886         if (ignore_whitespace)
887                 strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
888
889         if (ignore_date) {
890                 strbuf_addstr(&options.git_am_opt, " --ignore-date");
891                 options.flags |= REBASE_FORCE;
892         }
893
894         if (options.keep_empty)
895                 imply_interactive(&options, "--keep-empty");
896
897         if (gpg_sign) {
898                 free(options.gpg_sign_opt);
899                 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
900         }
901
902         if (opt_c >= 0)
903                 strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
904
905         if (whitespace.nr) {
906                 int i;
907
908                 for (i = 0; i < whitespace.nr; i++) {
909                         const char *item = whitespace.items[i].string;
910
911                         strbuf_addf(&options.git_am_opt, " --whitespace=%s",
912                                     item);
913
914                         if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
915                                 options.flags |= REBASE_FORCE;
916                 }
917         }
918
919         switch (options.type) {
920         case REBASE_MERGE:
921         case REBASE_INTERACTIVE:
922         case REBASE_PRESERVE_MERGES:
923                 options.state_dir = merge_dir();
924                 break;
925         case REBASE_AM:
926                 options.state_dir = apply_dir();
927                 break;
928         default:
929                 /* the default rebase backend is `--am` */
930                 options.type = REBASE_AM;
931                 options.state_dir = apply_dir();
932                 break;
933         }
934
935         if (options.signoff) {
936                 if (options.type == REBASE_PRESERVE_MERGES)
937                         die("cannot combine '--signoff' with "
938                             "'--preserve-merges'");
939                 strbuf_addstr(&options.git_am_opt, " --signoff");
940                 options.flags |= REBASE_FORCE;
941         }
942
943         if (!options.root) {
944                 if (argc < 1)
945                         die("TODO: handle @{upstream}");
946                 else {
947                         options.upstream_name = argv[0];
948                         argc--;
949                         argv++;
950                         if (!strcmp(options.upstream_name, "-"))
951                                 options.upstream_name = "@{-1}";
952                 }
953                 options.upstream = peel_committish(options.upstream_name);
954                 if (!options.upstream)
955                         die(_("invalid upstream '%s'"), options.upstream_name);
956                 options.upstream_arg = options.upstream_name;
957         } else
958                 die("TODO: upstream for --root");
959
960         /* Make sure the branch to rebase onto is valid. */
961         if (!options.onto_name)
962                 options.onto_name = options.upstream_name;
963         if (strstr(options.onto_name, "...")) {
964                 if (get_oid_mb(options.onto_name, &merge_base) < 0)
965                         die(_("'%s': need exactly one merge base"),
966                             options.onto_name);
967                 options.onto = lookup_commit_or_die(&merge_base,
968                                                     options.onto_name);
969         } else {
970                 options.onto = peel_committish(options.onto_name);
971                 if (!options.onto)
972                         die(_("Does not point to a valid commit '%s'"),
973                                 options.onto_name);
974         }
975
976         /*
977          * If the branch to rebase is given, that is the branch we will rebase
978          * branch_name -- branch/commit being rebased, or
979          *                HEAD (already detached)
980          * orig_head -- commit object name of tip of the branch before rebasing
981          * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
982          */
983         if (argc == 1) {
984                 /* Is it "rebase other branchname" or "rebase other commit"? */
985                 branch_name = argv[0];
986                 options.switch_to = argv[0];
987
988                 /* Is it a local branch? */
989                 strbuf_reset(&buf);
990                 strbuf_addf(&buf, "refs/heads/%s", branch_name);
991                 if (!read_ref(buf.buf, &options.orig_head))
992                         options.head_name = xstrdup(buf.buf);
993                 /* If not is it a valid ref (branch or commit)? */
994                 else if (!get_oid(branch_name, &options.orig_head))
995                         options.head_name = NULL;
996                 else
997                         die(_("fatal: no such branch/commit '%s'"),
998                             branch_name);
999         } else if (argc == 0) {
1000                 /* Do not need to switch branches, we are already on it. */
1001                 options.head_name =
1002                         xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1003                                          &flags));
1004                 if (!options.head_name)
1005                         die(_("No such ref: %s"), "HEAD");
1006                 if (flags & REF_ISSYMREF) {
1007                         if (!skip_prefix(options.head_name,
1008                                          "refs/heads/", &branch_name))
1009                                 branch_name = options.head_name;
1010
1011                 } else {
1012                         free(options.head_name);
1013                         options.head_name = NULL;
1014                         branch_name = "HEAD";
1015                 }
1016                 if (get_oid("HEAD", &options.orig_head))
1017                         die(_("Could not resolve HEAD to a revision"));
1018         } else
1019                 BUG("unexpected number of arguments left to parse");
1020
1021         if (read_index(the_repository->index) < 0)
1022                 die(_("could not read index"));
1023
1024         if (options.autostash) {
1025                 struct lock_file lock_file = LOCK_INIT;
1026                 int fd;
1027
1028                 fd = hold_locked_index(&lock_file, 0);
1029                 refresh_cache(REFRESH_QUIET);
1030                 if (0 <= fd)
1031                         update_index_if_able(&the_index, &lock_file);
1032                 rollback_lock_file(&lock_file);
1033
1034                 if (has_unstaged_changes(0) || has_uncommitted_changes(0)) {
1035                         const char *autostash =
1036                                 state_dir_path("autostash", &options);
1037                         struct child_process stash = CHILD_PROCESS_INIT;
1038                         struct object_id oid;
1039                         struct commit *head =
1040                                 lookup_commit_reference(the_repository,
1041                                                         &options.orig_head);
1042
1043                         argv_array_pushl(&stash.args,
1044                                          "stash", "create", "autostash", NULL);
1045                         stash.git_cmd = 1;
1046                         stash.no_stdin = 1;
1047                         strbuf_reset(&buf);
1048                         if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1049                                 die(_("Cannot autostash"));
1050                         strbuf_trim_trailing_newline(&buf);
1051                         if (get_oid(buf.buf, &oid))
1052                                 die(_("Unexpected stash response: '%s'"),
1053                                     buf.buf);
1054                         strbuf_reset(&buf);
1055                         strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1056
1057                         if (safe_create_leading_directories_const(autostash))
1058                                 die(_("Could not create directory for '%s'"),
1059                                     options.state_dir);
1060                         write_file(autostash, "%s", buf.buf);
1061                         printf(_("Created autostash: %s\n"), buf.buf);
1062                         if (reset_head(&head->object.oid, "reset --hard",
1063                                        NULL, 0) < 0)
1064                                 die(_("could not reset --hard"));
1065                         printf(_("HEAD is now at %s"),
1066                                find_unique_abbrev(&head->object.oid,
1067                                                   DEFAULT_ABBREV));
1068                         strbuf_reset(&buf);
1069                         pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1070                         if (buf.len > 0)
1071                                 printf(" %s", buf.buf);
1072                         putchar('\n');
1073
1074                         if (discard_index(the_repository->index) < 0 ||
1075                                 read_index(the_repository->index) < 0)
1076                                 die(_("could not read index"));
1077                 }
1078         }
1079
1080         if (require_clean_work_tree("rebase",
1081                                     _("Please commit or stash them."), 1, 1)) {
1082                 ret = 1;
1083                 goto cleanup;
1084         }
1085
1086         /*
1087          * Now we are rebasing commits upstream..orig_head (or with --root,
1088          * everything leading up to orig_head) on top of onto.
1089          */
1090
1091         /*
1092          * Check if we are already based on onto with linear history,
1093          * but this should be done only when upstream and onto are the same
1094          * and if this is not an interactive rebase.
1095          */
1096         if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1097             !is_interactive(&options) && !options.restrict_revision &&
1098             !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1099                 int flag;
1100
1101                 if (!(options.flags & REBASE_FORCE)) {
1102                         /* Lazily switch to the target branch if needed... */
1103                         if (options.switch_to) {
1104                                 struct object_id oid;
1105
1106                                 if (get_oid(options.switch_to, &oid) < 0) {
1107                                         ret = !!error(_("could not parse '%s'"),
1108                                                       options.switch_to);
1109                                         goto cleanup;
1110                                 }
1111
1112                                 strbuf_reset(&buf);
1113                                 strbuf_addf(&buf, "rebase: checkout %s",
1114                                             options.switch_to);
1115                                 if (reset_head(&oid, "checkout",
1116                                                options.head_name, 0) < 0) {
1117                                         ret = !!error(_("could not switch to "
1118                                                         "%s"),
1119                                                       options.switch_to);
1120                                         goto cleanup;
1121                                 }
1122                         }
1123
1124                         if (!(options.flags & REBASE_NO_QUIET))
1125                                 ; /* be quiet */
1126                         else if (!strcmp(branch_name, "HEAD") &&
1127                                  resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1128                                 puts(_("HEAD is up to date."));
1129                         else
1130                                 printf(_("Current branch %s is up to date.\n"),
1131                                        branch_name);
1132                         ret = !!finish_rebase(&options);
1133                         goto cleanup;
1134                 } else if (!(options.flags & REBASE_NO_QUIET))
1135                         ; /* be quiet */
1136                 else if (!strcmp(branch_name, "HEAD") &&
1137                          resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1138                         puts(_("HEAD is up to date, rebase forced."));
1139                 else
1140                         printf(_("Current branch %s is up to date, rebase "
1141                                  "forced.\n"), branch_name);
1142         }
1143
1144         /* If a hook exists, give it a chance to interrupt*/
1145         if (!ok_to_skip_pre_rebase &&
1146             run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1147                         argc ? argv[0] : NULL, NULL))
1148                 die(_("The pre-rebase hook refused to rebase."));
1149
1150         if (options.flags & REBASE_DIFFSTAT) {
1151                 struct diff_options opts;
1152
1153                 if (options.flags & REBASE_VERBOSE)
1154                         printf(_("Changes from %s to %s:\n"),
1155                                 oid_to_hex(&merge_base),
1156                                 oid_to_hex(&options.onto->object.oid));
1157
1158                 /* We want color (if set), but no pager */
1159                 diff_setup(&opts);
1160                 opts.stat_width = -1; /* use full terminal width */
1161                 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1162                 opts.output_format |=
1163                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1164                 opts.detect_rename = DIFF_DETECT_RENAME;
1165                 diff_setup_done(&opts);
1166                 diff_tree_oid(&merge_base, &options.onto->object.oid,
1167                               "", &opts);
1168                 diffcore_std(&opts);
1169                 diff_flush(&opts);
1170         }
1171
1172         if (is_interactive(&options))
1173                 goto run_rebase;
1174
1175         /* Detach HEAD and reset the tree */
1176         if (options.flags & REBASE_NO_QUIET)
1177                 printf(_("First, rewinding head to replay your work on top of "
1178                          "it...\n"));
1179
1180         strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1181         if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
1182                 die(_("Could not detach HEAD"));
1183         strbuf_release(&msg);
1184
1185         strbuf_addf(&revisions, "%s..%s",
1186                     options.root ? oid_to_hex(&options.onto->object.oid) :
1187                     (options.restrict_revision ?
1188                      oid_to_hex(&options.restrict_revision->object.oid) :
1189                      oid_to_hex(&options.upstream->object.oid)),
1190                     oid_to_hex(&options.orig_head));
1191
1192         options.revisions = revisions.buf;
1193
1194 run_rebase:
1195         ret = !!run_specific_rebase(&options);
1196
1197 cleanup:
1198         strbuf_release(&revisions);
1199         free(options.head_name);
1200         free(options.gpg_sign_opt);
1201         return ret;
1202 }