2 * "git rebase" builtin command
4 * Copyright (c) 2018 Pratik Karki
8 #include "run-command.h"
10 #include "argv-array.h"
16 #include "cache-tree.h"
17 #include "unpack-trees.h"
19 #include "parse-options.h"
22 #include "wt-status.h"
24 #include "commit-reach.h"
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>] "
31 N_("git rebase --continue | --abort | --skip | --edit-todo"),
35 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
36 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
39 REBASE_UNSPECIFIED = -1,
43 REBASE_PRESERVE_MERGES
46 static int use_builtin_rebase(void)
48 struct child_process cp = CHILD_PROCESS_INIT;
49 struct strbuf out = STRBUF_INIT;
52 argv_array_pushl(&cp.args,
53 "config", "--bool", "rebase.usebuiltin", NULL);
55 if (capture_command(&cp, &out, 6)) {
61 ret = !strcmp("true", out.buf);
66 static int apply_autostash(void)
72 struct rebase_options {
73 enum rebase_type type;
74 const char *state_dir;
75 struct commit *upstream;
76 const char *upstream_name;
77 const char *upstream_arg;
79 struct object_id orig_head;
81 const char *onto_name;
82 const char *revisions;
83 const char *switch_to;
85 struct commit *restrict_revision;
86 int dont_finish_rebase;
88 REBASE_NO_QUIET = 1<<0,
89 REBASE_VERBOSE = 1<<1,
90 REBASE_DIFFSTAT = 1<<2,
92 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
94 struct strbuf git_am_opt;
97 static int is_interactive(struct rebase_options *opts)
99 return opts->type == REBASE_INTERACTIVE ||
100 opts->type == REBASE_PRESERVE_MERGES;
103 /* Returns the filename prefixed by the state_dir */
104 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
106 static struct strbuf path = STRBUF_INIT;
107 static size_t prefix_len;
110 strbuf_addf(&path, "%s/", opts->state_dir);
111 prefix_len = path.len;
114 strbuf_setlen(&path, prefix_len);
115 strbuf_addstr(&path, filename);
119 static int finish_rebase(struct rebase_options *opts)
121 struct strbuf dir = STRBUF_INIT;
122 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
124 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
126 close_all_packs(the_repository->objects);
128 * We ignore errors in 'gc --auto', since the
129 * user should see them.
131 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
132 strbuf_addstr(&dir, opts->state_dir);
133 remove_dir_recursively(&dir, 0);
134 strbuf_release(&dir);
139 static struct commit *peel_committish(const char *name)
142 struct object_id oid;
144 if (get_oid(name, &oid))
146 obj = parse_object(the_repository, &oid);
147 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
150 static void add_var(struct strbuf *buf, const char *name, const char *value)
153 strbuf_addf(buf, "unset %s; ", name);
155 strbuf_addf(buf, "%s=", name);
156 sq_quote_buf(buf, value);
157 strbuf_addstr(buf, "; ");
161 static int run_specific_rebase(struct rebase_options *opts)
163 const char *argv[] = { NULL, NULL };
164 struct strbuf script_snippet = STRBUF_INIT;
166 const char *backend, *backend_func;
168 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
169 add_var(&script_snippet, "state_dir", opts->state_dir);
171 add_var(&script_snippet, "upstream_name", opts->upstream_name);
172 add_var(&script_snippet, "upstream",
173 oid_to_hex(&opts->upstream->object.oid));
174 add_var(&script_snippet, "head_name",
175 opts->head_name ? opts->head_name : "detached HEAD");
176 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
177 add_var(&script_snippet, "onto", oid_to_hex(&opts->onto->object.oid));
178 add_var(&script_snippet, "onto_name", opts->onto_name);
179 add_var(&script_snippet, "revisions", opts->revisions);
180 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
181 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
182 add_var(&script_snippet, "GIT_QUIET",
183 opts->flags & REBASE_NO_QUIET ? "" : "t");
184 add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
185 add_var(&script_snippet, "verbose",
186 opts->flags & REBASE_VERBOSE ? "t" : "");
187 add_var(&script_snippet, "diffstat",
188 opts->flags & REBASE_DIFFSTAT ? "t" : "");
189 add_var(&script_snippet, "force_rebase",
190 opts->flags & REBASE_FORCE ? "t" : "");
192 add_var(&script_snippet, "switch_to", opts->switch_to);
194 switch (opts->type) {
196 backend = "git-rebase--am";
197 backend_func = "git_rebase__am";
199 case REBASE_INTERACTIVE:
200 backend = "git-rebase--interactive";
201 backend_func = "git_rebase__interactive";
204 backend = "git-rebase--merge";
205 backend_func = "git_rebase__merge";
207 case REBASE_PRESERVE_MERGES:
208 backend = "git-rebase--preserve-merges";
209 backend_func = "git_rebase__preserve_merges";
212 BUG("Unhandled rebase type %d", opts->type);
216 strbuf_addf(&script_snippet,
217 ". git-sh-setup && . git-rebase--common &&"
218 " . %s && %s", backend, backend_func);
219 argv[0] = script_snippet.buf;
221 status = run_command_v_opt(argv, RUN_USING_SHELL);
222 if (opts->dont_finish_rebase)
224 else if (status == 0) {
225 if (!file_exists(state_dir_path("stopped-sha", opts)))
227 } else if (status == 2) {
228 struct strbuf dir = STRBUF_INIT;
231 strbuf_addstr(&dir, opts->state_dir);
232 remove_dir_recursively(&dir, 0);
233 strbuf_release(&dir);
234 die("Nothing to do");
237 strbuf_release(&script_snippet);
239 return status ? -1 : 0;
242 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
244 static int reset_head(struct object_id *oid, const char *action,
245 const char *switch_to_branch, int detach_head)
247 struct object_id head_oid;
248 struct tree_desc desc;
249 struct lock_file lock = LOCK_INIT;
250 struct unpack_trees_options unpack_tree_opts;
252 const char *reflog_action;
253 struct strbuf msg = STRBUF_INIT;
255 struct object_id *orig = NULL, oid_orig,
256 *old_orig = NULL, oid_old_orig;
259 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
260 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
262 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
266 if (get_oid("HEAD", &head_oid)) {
267 rollback_lock_file(&lock);
268 return error(_("could not determine HEAD revision"));
273 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
274 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
275 unpack_tree_opts.head_idx = 1;
276 unpack_tree_opts.src_index = the_repository->index;
277 unpack_tree_opts.dst_index = the_repository->index;
278 unpack_tree_opts.fn = oneway_merge;
279 unpack_tree_opts.update = 1;
280 unpack_tree_opts.merge = 1;
282 unpack_tree_opts.reset = 1;
284 if (read_index_unmerged(the_repository->index) < 0) {
285 rollback_lock_file(&lock);
286 return error(_("could not read index"));
289 if (!fill_tree_descriptor(&desc, oid)) {
290 error(_("failed to find tree of %s"), oid_to_hex(oid));
291 rollback_lock_file(&lock);
292 free((void *)desc.buffer);
296 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
297 rollback_lock_file(&lock);
298 free((void *)desc.buffer);
302 tree = parse_tree_indirect(oid);
303 prime_cache_tree(the_repository->index, tree);
305 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
306 ret = error(_("could not write index"));
307 free((void *)desc.buffer);
312 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
313 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
314 prefix_len = msg.len;
316 if (!get_oid("ORIG_HEAD", &oid_old_orig))
317 old_orig = &oid_old_orig;
318 if (!get_oid("HEAD", &oid_orig)) {
320 strbuf_addstr(&msg, "updating ORIG_HEAD");
321 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
322 UPDATE_REFS_MSG_ON_ERR);
324 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
325 strbuf_setlen(&msg, prefix_len);
326 strbuf_addstr(&msg, "updating HEAD");
327 if (!switch_to_branch)
328 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
329 UPDATE_REFS_MSG_ON_ERR);
331 ret = create_symref("HEAD", switch_to_branch, msg.buf);
333 ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
334 UPDATE_REFS_MSG_ON_ERR);
337 strbuf_release(&msg);
341 static int rebase_config(const char *var, const char *value, void *data)
343 struct rebase_options *opts = data;
345 if (!strcmp(var, "rebase.stat")) {
346 if (git_config_bool(var, value))
347 opts->flags |= REBASE_DIFFSTAT;
349 opts->flags &= !REBASE_DIFFSTAT;
353 return git_default_config(var, value, data);
357 * Determines whether the commits in from..to are linear, i.e. contain
358 * no merge commits. This function *expects* `from` to be an ancestor of
361 static int is_linear_history(struct commit *from, struct commit *to)
363 while (to && to != from) {
367 if (to->parents->next)
369 to = to->parents->item;
374 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
375 struct object_id *merge_base)
377 struct commit *head = lookup_commit(the_repository, head_oid);
378 struct commit_list *merge_bases;
384 merge_bases = get_merge_bases(onto, head);
385 if (merge_bases && !merge_bases->next) {
386 oidcpy(merge_base, &merge_bases->item->object.oid);
387 res = !oidcmp(merge_base, &onto->object.oid);
389 oidcpy(merge_base, &null_oid);
392 free_commit_list(merge_bases);
393 return res && is_linear_history(onto, head);
396 int cmd_rebase(int argc, const char **argv, const char *prefix)
398 struct rebase_options options = {
399 .type = REBASE_UNSPECIFIED,
400 .flags = REBASE_NO_QUIET,
401 .git_am_opt = STRBUF_INIT,
403 const char *branch_name;
404 int ret, flags, in_progress = 0;
405 int ok_to_skip_pre_rebase = 0;
406 struct strbuf msg = STRBUF_INIT;
407 struct strbuf revisions = STRBUF_INIT;
408 struct strbuf buf = STRBUF_INIT;
409 struct object_id merge_base;
410 struct option builtin_rebase_options[] = {
411 OPT_STRING(0, "onto", &options.onto_name,
413 N_("rebase onto given branch instead of upstream")),
414 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
415 N_("allow pre-rebase hook to run")),
416 OPT_NEGBIT('q', "quiet", &options.flags,
417 N_("be quiet. implies --no-stat"),
418 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
419 OPT_BIT('v', "verbose", &options.flags,
420 N_("display a diffstat of what changed upstream"),
421 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
422 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
423 N_("do not show diffstat of what changed upstream"),
424 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
425 OPT_BIT('f', "force-rebase", &options.flags,
426 N_("cherry-pick all commits, even if unchanged"),
428 OPT_BIT(0, "no-ff", &options.flags,
429 N_("cherry-pick all commits, even if unchanged"),
435 * NEEDSWORK: Once the builtin rebase has been tested enough
436 * and git-legacy-rebase.sh is retired to contrib/, this preamble
440 if (!use_builtin_rebase()) {
441 const char *path = mkpath("%s/git-legacy-rebase",
444 if (sane_execvp(path, (char **)argv) < 0)
445 die_errno(_("could not exec %s"), path);
447 BUG("sane_execvp() returned???");
450 if (argc == 2 && !strcmp(argv[1], "-h"))
451 usage_with_options(builtin_rebase_usage,
452 builtin_rebase_options);
454 prefix = setup_git_directory();
455 trace_repo_setup(prefix);
458 git_config(rebase_config, &options);
460 if (is_directory(apply_dir())) {
461 options.type = REBASE_AM;
462 options.state_dir = apply_dir();
463 } else if (is_directory(merge_dir())) {
465 strbuf_addf(&buf, "%s/rewritten", merge_dir());
466 if (is_directory(buf.buf)) {
467 options.type = REBASE_PRESERVE_MERGES;
468 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
471 strbuf_addf(&buf, "%s/interactive", merge_dir());
472 if(file_exists(buf.buf)) {
473 options.type = REBASE_INTERACTIVE;
474 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
476 options.type = REBASE_MERGE;
478 options.state_dir = merge_dir();
481 if (options.type != REBASE_UNSPECIFIED)
484 argc = parse_options(argc, argv, prefix,
485 builtin_rebase_options,
486 builtin_rebase_usage, 0);
489 usage_with_options(builtin_rebase_usage,
490 builtin_rebase_options);
492 /* Make sure no rebase is in progress */
494 const char *last_slash = strrchr(options.state_dir, '/');
495 const char *state_dir_base =
496 last_slash ? last_slash + 1 : options.state_dir;
497 const char *cmd_live_rebase =
498 "git rebase (--continue | --abort | --skip)";
500 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
501 die(_("It seems that there is already a %s directory, and\n"
502 "I wonder if you are in the middle of another rebase. "
504 "case, please try\n\t%s\n"
505 "If that is not the case, please\n\t%s\n"
506 "and run me again. I am stopping in case you still "
508 "valuable there.\n"),
509 state_dir_base, cmd_live_rebase, buf.buf);
512 if (!(options.flags & REBASE_NO_QUIET))
513 strbuf_addstr(&options.git_am_opt, " -q");
515 switch (options.type) {
517 case REBASE_INTERACTIVE:
518 case REBASE_PRESERVE_MERGES:
519 options.state_dir = merge_dir();
522 options.state_dir = apply_dir();
525 /* the default rebase backend is `--am` */
526 options.type = REBASE_AM;
527 options.state_dir = apply_dir();
533 die("TODO: handle @{upstream}");
535 options.upstream_name = argv[0];
538 if (!strcmp(options.upstream_name, "-"))
539 options.upstream_name = "@{-1}";
541 options.upstream = peel_committish(options.upstream_name);
542 if (!options.upstream)
543 die(_("invalid upstream '%s'"), options.upstream_name);
544 options.upstream_arg = options.upstream_name;
546 die("TODO: upstream for --root");
548 /* Make sure the branch to rebase onto is valid. */
549 if (!options.onto_name)
550 options.onto_name = options.upstream_name;
551 if (strstr(options.onto_name, "...")) {
552 if (get_oid_mb(options.onto_name, &merge_base) < 0)
553 die(_("'%s': need exactly one merge base"),
555 options.onto = lookup_commit_or_die(&merge_base,
558 options.onto = peel_committish(options.onto_name);
560 die(_("Does not point to a valid commit '%s'"),
565 * If the branch to rebase is given, that is the branch we will rebase
566 * branch_name -- branch/commit being rebased, or
567 * HEAD (already detached)
568 * orig_head -- commit object name of tip of the branch before rebasing
569 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
572 /* Is it "rebase other branchname" or "rebase other commit"? */
573 branch_name = argv[0];
574 options.switch_to = argv[0];
576 /* Is it a local branch? */
578 strbuf_addf(&buf, "refs/heads/%s", branch_name);
579 if (!read_ref(buf.buf, &options.orig_head))
580 options.head_name = xstrdup(buf.buf);
581 /* If not is it a valid ref (branch or commit)? */
582 else if (!get_oid(branch_name, &options.orig_head))
583 options.head_name = NULL;
585 die(_("fatal: no such branch/commit '%s'"),
587 } else if (argc == 0) {
588 /* Do not need to switch branches, we are already on it. */
590 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
592 if (!options.head_name)
593 die(_("No such ref: %s"), "HEAD");
594 if (flags & REF_ISSYMREF) {
595 if (!skip_prefix(options.head_name,
596 "refs/heads/", &branch_name))
597 branch_name = options.head_name;
600 free(options.head_name);
601 options.head_name = NULL;
602 branch_name = "HEAD";
604 if (get_oid("HEAD", &options.orig_head))
605 die(_("Could not resolve HEAD to a revision"));
607 BUG("unexpected number of arguments left to parse");
609 if (read_index(the_repository->index) < 0)
610 die(_("could not read index"));
612 if (require_clean_work_tree("rebase",
613 _("Please commit or stash them."), 1, 1)) {
619 * Now we are rebasing commits upstream..orig_head (or with --root,
620 * everything leading up to orig_head) on top of onto.
624 * Check if we are already based on onto with linear history,
625 * but this should be done only when upstream and onto are the same
626 * and if this is not an interactive rebase.
628 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
629 !is_interactive(&options) && !options.restrict_revision &&
630 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
633 if (!(options.flags & REBASE_FORCE)) {
634 /* Lazily switch to the target branch if needed... */
635 if (options.switch_to) {
636 struct object_id oid;
638 if (get_oid(options.switch_to, &oid) < 0) {
639 ret = !!error(_("could not parse '%s'"),
645 strbuf_addf(&buf, "rebase: checkout %s",
647 if (reset_head(&oid, "checkout",
648 options.head_name, 0) < 0) {
649 ret = !!error(_("could not switch to "
656 if (!(options.flags & REBASE_NO_QUIET))
658 else if (!strcmp(branch_name, "HEAD") &&
659 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
660 puts(_("HEAD is up to date."));
662 printf(_("Current branch %s is up to date.\n"),
664 ret = !!finish_rebase(&options);
666 } else if (!(options.flags & REBASE_NO_QUIET))
668 else if (!strcmp(branch_name, "HEAD") &&
669 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
670 puts(_("HEAD is up to date, rebase forced."));
672 printf(_("Current branch %s is up to date, rebase "
673 "forced.\n"), branch_name);
676 /* If a hook exists, give it a chance to interrupt*/
677 if (!ok_to_skip_pre_rebase &&
678 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
679 argc ? argv[0] : NULL, NULL))
680 die(_("The pre-rebase hook refused to rebase."));
682 if (options.flags & REBASE_DIFFSTAT) {
683 struct diff_options opts;
685 if (options.flags & REBASE_VERBOSE)
686 printf(_("Changes from %s to %s:\n"),
687 oid_to_hex(&merge_base),
688 oid_to_hex(&options.onto->object.oid));
690 /* We want color (if set), but no pager */
692 opts.stat_width = -1; /* use full terminal width */
693 opts.stat_graph_width = -1; /* respect statGraphWidth config */
694 opts.output_format |=
695 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
696 opts.detect_rename = DIFF_DETECT_RENAME;
697 diff_setup_done(&opts);
698 diff_tree_oid(&merge_base, &options.onto->object.oid,
704 /* Detach HEAD and reset the tree */
705 if (options.flags & REBASE_NO_QUIET)
706 printf(_("First, rewinding head to replay your work on top of "
709 strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
710 if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
711 die(_("Could not detach HEAD"));
712 strbuf_release(&msg);
714 strbuf_addf(&revisions, "%s..%s",
715 options.root ? oid_to_hex(&options.onto->object.oid) :
716 (options.restrict_revision ?
717 oid_to_hex(&options.restrict_revision->object.oid) :
718 oid_to_hex(&options.upstream->object.oid)),
719 oid_to_hex(&options.orig_head));
721 options.revisions = revisions.buf;
723 ret = !!run_specific_rebase(&options);
726 strbuf_release(&revisions);
727 free(options.head_name);