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