builtin rebase: support --force-rebase
[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
25 static char const * const builtin_rebase_usage[] = {
26         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
27                 "[<upstream>] [<branch>]"),
28         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
29                 "--root [<branch>]"),
30         N_("git rebase --continue | --abort | --skip | --edit-todo"),
31         NULL
32 };
33
34 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
35 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
36
37 enum rebase_type {
38         REBASE_UNSPECIFIED = -1,
39         REBASE_AM,
40         REBASE_MERGE,
41         REBASE_INTERACTIVE,
42         REBASE_PRESERVE_MERGES
43 };
44
45 static int use_builtin_rebase(void)
46 {
47         struct child_process cp = CHILD_PROCESS_INIT;
48         struct strbuf out = STRBUF_INIT;
49         int ret;
50
51         argv_array_pushl(&cp.args,
52                          "config", "--bool", "rebase.usebuiltin", NULL);
53         cp.git_cmd = 1;
54         if (capture_command(&cp, &out, 6)) {
55                 strbuf_release(&out);
56                 return 0;
57         }
58
59         strbuf_trim(&out);
60         ret = !strcmp("true", out.buf);
61         strbuf_release(&out);
62         return ret;
63 }
64
65 static int apply_autostash(void)
66 {
67         warning("TODO");
68         return 0;
69 }
70
71 struct rebase_options {
72         enum rebase_type type;
73         const char *state_dir;
74         struct commit *upstream;
75         const char *upstream_name;
76         const char *upstream_arg;
77         char *head_name;
78         struct object_id orig_head;
79         struct commit *onto;
80         const char *onto_name;
81         const char *revisions;
82         int root;
83         struct commit *restrict_revision;
84         int dont_finish_rebase;
85         enum {
86                 REBASE_NO_QUIET = 1<<0,
87                 REBASE_VERBOSE = 1<<1,
88                 REBASE_DIFFSTAT = 1<<2,
89                 REBASE_FORCE = 1<<3,
90         } flags;
91         struct strbuf git_am_opt;
92 };
93
94 static int is_interactive(struct rebase_options *opts)
95 {
96         return opts->type == REBASE_INTERACTIVE ||
97                 opts->type == REBASE_PRESERVE_MERGES;
98 }
99
100 /* Returns the filename prefixed by the state_dir */
101 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
102 {
103         static struct strbuf path = STRBUF_INIT;
104         static size_t prefix_len;
105
106         if (!prefix_len) {
107                 strbuf_addf(&path, "%s/", opts->state_dir);
108                 prefix_len = path.len;
109         }
110
111         strbuf_setlen(&path, prefix_len);
112         strbuf_addstr(&path, filename);
113         return path.buf;
114 }
115
116 static int finish_rebase(struct rebase_options *opts)
117 {
118         struct strbuf dir = STRBUF_INIT;
119         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
120
121         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
122         apply_autostash();
123         close_all_packs(the_repository->objects);
124         /*
125          * We ignore errors in 'gc --auto', since the
126          * user should see them.
127          */
128         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
129         strbuf_addstr(&dir, opts->state_dir);
130         remove_dir_recursively(&dir, 0);
131         strbuf_release(&dir);
132
133         return 0;
134 }
135
136 static struct commit *peel_committish(const char *name)
137 {
138         struct object *obj;
139         struct object_id oid;
140
141         if (get_oid(name, &oid))
142                 return NULL;
143         obj = parse_object(the_repository, &oid);
144         return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
145 }
146
147 static void add_var(struct strbuf *buf, const char *name, const char *value)
148 {
149         if (!value)
150                 strbuf_addf(buf, "unset %s; ", name);
151         else {
152                 strbuf_addf(buf, "%s=", name);
153                 sq_quote_buf(buf, value);
154                 strbuf_addstr(buf, "; ");
155         }
156 }
157
158 static int run_specific_rebase(struct rebase_options *opts)
159 {
160         const char *argv[] = { NULL, NULL };
161         struct strbuf script_snippet = STRBUF_INIT;
162         int status;
163         const char *backend, *backend_func;
164
165         add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
166         add_var(&script_snippet, "state_dir", opts->state_dir);
167
168         add_var(&script_snippet, "upstream_name", opts->upstream_name);
169         add_var(&script_snippet, "upstream",
170                                  oid_to_hex(&opts->upstream->object.oid));
171         add_var(&script_snippet, "head_name", opts->head_name);
172         add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
173         add_var(&script_snippet, "onto", oid_to_hex(&opts->onto->object.oid));
174         add_var(&script_snippet, "onto_name", opts->onto_name);
175         add_var(&script_snippet, "revisions", opts->revisions);
176         add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
177                 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
178         add_var(&script_snippet, "GIT_QUIET",
179                 opts->flags & REBASE_NO_QUIET ? "" : "t");
180         add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
181         add_var(&script_snippet, "verbose",
182                 opts->flags & REBASE_VERBOSE ? "t" : "");
183         add_var(&script_snippet, "diffstat",
184                 opts->flags & REBASE_DIFFSTAT ? "t" : "");
185         add_var(&script_snippet, "force_rebase",
186                 opts->flags & REBASE_FORCE ? "t" : "");
187
188         switch (opts->type) {
189         case REBASE_AM:
190                 backend = "git-rebase--am";
191                 backend_func = "git_rebase__am";
192                 break;
193         case REBASE_INTERACTIVE:
194                 backend = "git-rebase--interactive";
195                 backend_func = "git_rebase__interactive";
196                 break;
197         case REBASE_MERGE:
198                 backend = "git-rebase--merge";
199                 backend_func = "git_rebase__merge";
200                 break;
201         case REBASE_PRESERVE_MERGES:
202                 backend = "git-rebase--preserve-merges";
203                 backend_func = "git_rebase__preserve_merges";
204                 break;
205         default:
206                 BUG("Unhandled rebase type %d", opts->type);
207                 break;
208         }
209
210         strbuf_addf(&script_snippet,
211                     ". git-sh-setup && . git-rebase--common &&"
212                     " . %s && %s", backend, backend_func);
213         argv[0] = script_snippet.buf;
214
215         status = run_command_v_opt(argv, RUN_USING_SHELL);
216         if (opts->dont_finish_rebase)
217                 ; /* do nothing */
218         else if (status == 0) {
219                 if (!file_exists(state_dir_path("stopped-sha", opts)))
220                         finish_rebase(opts);
221         } else if (status == 2) {
222                 struct strbuf dir = STRBUF_INIT;
223
224                 apply_autostash();
225                 strbuf_addstr(&dir, opts->state_dir);
226                 remove_dir_recursively(&dir, 0);
227                 strbuf_release(&dir);
228                 die("Nothing to do");
229         }
230
231         strbuf_release(&script_snippet);
232
233         return status ? -1 : 0;
234 }
235
236 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
237
238 static int reset_head(struct object_id *oid, const char *action,
239                       const char *switch_to_branch, int detach_head)
240 {
241         struct object_id head_oid;
242         struct tree_desc desc;
243         struct lock_file lock = LOCK_INIT;
244         struct unpack_trees_options unpack_tree_opts;
245         struct tree *tree;
246         const char *reflog_action;
247         struct strbuf msg = STRBUF_INIT;
248         size_t prefix_len;
249         struct object_id *orig = NULL, oid_orig,
250                 *old_orig = NULL, oid_old_orig;
251         int ret = 0;
252
253         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
254                 return -1;
255
256         if (!oid) {
257                 if (get_oid("HEAD", &head_oid)) {
258                         rollback_lock_file(&lock);
259                         return error(_("could not determine HEAD revision"));
260                 }
261                 oid = &head_oid;
262         }
263
264         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
265         setup_unpack_trees_porcelain(&unpack_tree_opts, action);
266         unpack_tree_opts.head_idx = 1;
267         unpack_tree_opts.src_index = the_repository->index;
268         unpack_tree_opts.dst_index = the_repository->index;
269         unpack_tree_opts.fn = oneway_merge;
270         unpack_tree_opts.update = 1;
271         unpack_tree_opts.merge = 1;
272         if (!detach_head)
273                 unpack_tree_opts.reset = 1;
274
275         if (read_index_unmerged(the_repository->index) < 0) {
276                 rollback_lock_file(&lock);
277                 return error(_("could not read index"));
278         }
279
280         if (!fill_tree_descriptor(&desc, oid)) {
281                 error(_("failed to find tree of %s"), oid_to_hex(oid));
282                 rollback_lock_file(&lock);
283                 free((void *)desc.buffer);
284                 return -1;
285         }
286
287         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
288                 rollback_lock_file(&lock);
289                 free((void *)desc.buffer);
290                 return -1;
291         }
292
293         tree = parse_tree_indirect(oid);
294         prime_cache_tree(the_repository->index, tree);
295
296         if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
297                 ret = error(_("could not write index"));
298         free((void *)desc.buffer);
299
300         if (ret)
301                 return ret;
302
303         reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
304         strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
305         prefix_len = msg.len;
306
307         if (!get_oid("ORIG_HEAD", &oid_old_orig))
308                 old_orig = &oid_old_orig;
309         if (!get_oid("HEAD", &oid_orig)) {
310                 orig = &oid_orig;
311                 strbuf_addstr(&msg, "updating ORIG_HEAD");
312                 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
313                            UPDATE_REFS_MSG_ON_ERR);
314         } else if (old_orig)
315                 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
316         strbuf_setlen(&msg, prefix_len);
317         strbuf_addstr(&msg, "updating HEAD");
318         if (!switch_to_branch)
319                 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
320                                  UPDATE_REFS_MSG_ON_ERR);
321         else {
322                 ret = create_symref("HEAD", switch_to_branch, msg.buf);
323                 if (!ret)
324                         ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
325                                          UPDATE_REFS_MSG_ON_ERR);
326         }
327
328         strbuf_release(&msg);
329         return ret;
330 }
331
332 static int rebase_config(const char *var, const char *value, void *data)
333 {
334         struct rebase_options *opts = data;
335
336         if (!strcmp(var, "rebase.stat")) {
337                 if (git_config_bool(var, value))
338                         opts->flags |= REBASE_DIFFSTAT;
339                 else
340                         opts->flags &= !REBASE_DIFFSTAT;
341                 return 0;
342         }
343
344         return git_default_config(var, value, data);
345 }
346
347 /*
348  * Determines whether the commits in from..to are linear, i.e. contain
349  * no merge commits. This function *expects* `from` to be an ancestor of
350  * `to`.
351  */
352 static int is_linear_history(struct commit *from, struct commit *to)
353 {
354         while (to && to != from) {
355                 parse_commit(to);
356                 if (!to->parents)
357                         return 1;
358                 if (to->parents->next)
359                         return 0;
360                 to = to->parents->item;
361         }
362         return 1;
363 }
364
365 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
366                             struct object_id *merge_base)
367 {
368         struct commit *head = lookup_commit(the_repository, head_oid);
369         struct commit_list *merge_bases;
370         int res;
371
372         if (!head)
373                 return 0;
374
375         merge_bases = get_merge_bases(onto, head);
376         if (merge_bases && !merge_bases->next) {
377                 oidcpy(merge_base, &merge_bases->item->object.oid);
378                 res = !oidcmp(merge_base, &onto->object.oid);
379         } else {
380                 oidcpy(merge_base, &null_oid);
381                 res = 0;
382         }
383         free_commit_list(merge_bases);
384         return res && is_linear_history(onto, head);
385 }
386
387 int cmd_rebase(int argc, const char **argv, const char *prefix)
388 {
389         struct rebase_options options = {
390                 .type = REBASE_UNSPECIFIED,
391                 .flags = REBASE_NO_QUIET,
392                 .git_am_opt = STRBUF_INIT,
393         };
394         const char *branch_name;
395         int ret, flags;
396         int ok_to_skip_pre_rebase = 0;
397         struct strbuf msg = STRBUF_INIT;
398         struct strbuf revisions = STRBUF_INIT;
399         struct object_id merge_base;
400         struct option builtin_rebase_options[] = {
401                 OPT_STRING(0, "onto", &options.onto_name,
402                            N_("revision"),
403                            N_("rebase onto given branch instead of upstream")),
404                 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
405                          N_("allow pre-rebase hook to run")),
406                 OPT_NEGBIT('q', "quiet", &options.flags,
407                            N_("be quiet. implies --no-stat"),
408                            REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
409                 OPT_BIT('v', "verbose", &options.flags,
410                         N_("display a diffstat of what changed upstream"),
411                         REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
412                 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
413                         N_("do not show diffstat of what changed upstream"),
414                         PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
415                 OPT_BIT('f', "force-rebase", &options.flags,
416                         N_("cherry-pick all commits, even if unchanged"),
417                         REBASE_FORCE),
418                 OPT_BIT(0, "no-ff", &options.flags,
419                         N_("cherry-pick all commits, even if unchanged"),
420                         REBASE_FORCE),
421                 OPT_END(),
422         };
423
424         /*
425          * NEEDSWORK: Once the builtin rebase has been tested enough
426          * and git-legacy-rebase.sh is retired to contrib/, this preamble
427          * can be removed.
428          */
429
430         if (!use_builtin_rebase()) {
431                 const char *path = mkpath("%s/git-legacy-rebase",
432                                           git_exec_path());
433
434                 if (sane_execvp(path, (char **)argv) < 0)
435                         die_errno(_("could not exec %s"), path);
436                 else
437                         BUG("sane_execvp() returned???");
438         }
439
440         if (argc == 2 && !strcmp(argv[1], "-h"))
441                 usage_with_options(builtin_rebase_usage,
442                                    builtin_rebase_options);
443
444         prefix = setup_git_directory();
445         trace_repo_setup(prefix);
446         setup_work_tree();
447
448         git_config(rebase_config, &options);
449
450         argc = parse_options(argc, argv, prefix,
451                              builtin_rebase_options,
452                              builtin_rebase_usage, 0);
453
454         if (argc > 2)
455                 usage_with_options(builtin_rebase_usage,
456                                    builtin_rebase_options);
457
458         if (!(options.flags & REBASE_NO_QUIET))
459                 strbuf_addstr(&options.git_am_opt, " -q");
460
461         switch (options.type) {
462         case REBASE_MERGE:
463         case REBASE_INTERACTIVE:
464         case REBASE_PRESERVE_MERGES:
465                 options.state_dir = merge_dir();
466                 break;
467         case REBASE_AM:
468                 options.state_dir = apply_dir();
469                 break;
470         default:
471                 /* the default rebase backend is `--am` */
472                 options.type = REBASE_AM;
473                 options.state_dir = apply_dir();
474                 break;
475         }
476
477         if (!options.root) {
478                 if (argc < 1)
479                         die("TODO: handle @{upstream}");
480                 else {
481                         options.upstream_name = argv[0];
482                         argc--;
483                         argv++;
484                         if (!strcmp(options.upstream_name, "-"))
485                                 options.upstream_name = "@{-1}";
486                 }
487                 options.upstream = peel_committish(options.upstream_name);
488                 if (!options.upstream)
489                         die(_("invalid upstream '%s'"), options.upstream_name);
490                 options.upstream_arg = options.upstream_name;
491         } else
492                 die("TODO: upstream for --root");
493
494         /* Make sure the branch to rebase onto is valid. */
495         if (!options.onto_name)
496                 options.onto_name = options.upstream_name;
497         if (strstr(options.onto_name, "...")) {
498                 if (get_oid_mb(options.onto_name, &merge_base) < 0)
499                         die(_("'%s': need exactly one merge base"),
500                             options.onto_name);
501                 options.onto = lookup_commit_or_die(&merge_base,
502                                                     options.onto_name);
503         } else {
504                 options.onto = peel_committish(options.onto_name);
505                 if (!options.onto)
506                         die(_("Does not point to a valid commit '%s'"),
507                                 options.onto_name);
508         }
509
510         /*
511          * If the branch to rebase is given, that is the branch we will rebase
512          * branch_name -- branch/commit being rebased, or
513          *                HEAD (already detached)
514          * orig_head -- commit object name of tip of the branch before rebasing
515          * head_name -- refs/heads/<that-branch> or "detached HEAD"
516          */
517         if (argc > 0)
518                  die("TODO: handle switch_to");
519         else {
520                 /* Do not need to switch branches, we are already on it. */
521                 options.head_name =
522                         xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
523                                          &flags));
524                 if (!options.head_name)
525                         die(_("No such ref: %s"), "HEAD");
526                 if (flags & REF_ISSYMREF) {
527                         if (!skip_prefix(options.head_name,
528                                          "refs/heads/", &branch_name))
529                                 branch_name = options.head_name;
530
531                 } else {
532                         options.head_name = xstrdup("detached HEAD");
533                         branch_name = "HEAD";
534                 }
535                 if (get_oid("HEAD", &options.orig_head))
536                         die(_("Could not resolve HEAD to a revision"));
537         }
538
539         if (read_index(the_repository->index) < 0)
540                 die(_("could not read index"));
541
542         if (require_clean_work_tree("rebase",
543                                     _("Please commit or stash them."), 1, 1)) {
544                 ret = 1;
545                 goto cleanup;
546         }
547
548         /*
549          * Now we are rebasing commits upstream..orig_head (or with --root,
550          * everything leading up to orig_head) on top of onto.
551          */
552
553         /*
554          * Check if we are already based on onto with linear history,
555          * but this should be done only when upstream and onto are the same
556          * and if this is not an interactive rebase.
557          */
558         if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
559             !is_interactive(&options) && !options.restrict_revision &&
560             !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
561                 int flag;
562
563                 if (!(options.flags & REBASE_FORCE)) {
564                         if (!(options.flags & REBASE_NO_QUIET))
565                                 ; /* be quiet */
566                         else if (!strcmp(branch_name, "HEAD") &&
567                                  resolve_ref_unsafe("HEAD", 0, NULL, &flag))
568                                 puts(_("HEAD is up to date."));
569                         else
570                                 printf(_("Current branch %s is up to date.\n"),
571                                        branch_name);
572                         ret = !!finish_rebase(&options);
573                         goto cleanup;
574                 } else if (!(options.flags & REBASE_NO_QUIET))
575                         ; /* be quiet */
576                 else if (!strcmp(branch_name, "HEAD") &&
577                          resolve_ref_unsafe("HEAD", 0, NULL, &flag))
578                         puts(_("HEAD is up to date, rebase forced."));
579                 else
580                         printf(_("Current branch %s is up to date, rebase "
581                                  "forced.\n"), branch_name);
582         }
583
584         /* If a hook exists, give it a chance to interrupt*/
585         if (!ok_to_skip_pre_rebase &&
586             run_hook_le(NULL, "pre-rebase", options.upstream_arg,
587                         argc ? argv[0] : NULL, NULL))
588                 die(_("The pre-rebase hook refused to rebase."));
589
590         if (options.flags & REBASE_DIFFSTAT) {
591                 struct diff_options opts;
592
593                 if (options.flags & REBASE_VERBOSE)
594                         printf(_("Changes from %s to %s:\n"),
595                                 oid_to_hex(&merge_base),
596                                 oid_to_hex(&options.onto->object.oid));
597
598                 /* We want color (if set), but no pager */
599                 diff_setup(&opts);
600                 opts.stat_width = -1; /* use full terminal width */
601                 opts.stat_graph_width = -1; /* respect statGraphWidth config */
602                 opts.output_format |=
603                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
604                 opts.detect_rename = DIFF_DETECT_RENAME;
605                 diff_setup_done(&opts);
606                 diff_tree_oid(&merge_base, &options.onto->object.oid,
607                               "", &opts);
608                 diffcore_std(&opts);
609                 diff_flush(&opts);
610         }
611
612         /* Detach HEAD and reset the tree */
613         if (options.flags & REBASE_NO_QUIET)
614                 printf(_("First, rewinding head to replay your work on top of "
615                          "it...\n"));
616
617         strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
618         if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
619                 die(_("Could not detach HEAD"));
620         strbuf_release(&msg);
621
622         strbuf_addf(&revisions, "%s..%s",
623                     options.root ? oid_to_hex(&options.onto->object.oid) :
624                     (options.restrict_revision ?
625                      oid_to_hex(&options.restrict_revision->object.oid) :
626                      oid_to_hex(&options.upstream->object.oid)),
627                     oid_to_hex(&options.orig_head));
628
629         options.revisions = revisions.buf;
630
631         ret = !!run_specific_rebase(&options);
632
633 cleanup:
634         strbuf_release(&revisions);
635         free(options.head_name);
636         return ret;
637 }