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"
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>] "
30 N_("git rebase --continue | --abort | --skip | --edit-todo"),
34 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
35 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
38 REBASE_UNSPECIFIED = -1,
42 REBASE_PRESERVE_MERGES
45 static int use_builtin_rebase(void)
47 struct child_process cp = CHILD_PROCESS_INIT;
48 struct strbuf out = STRBUF_INIT;
51 argv_array_pushl(&cp.args,
52 "config", "--bool", "rebase.usebuiltin", NULL);
54 if (capture_command(&cp, &out, 6)) {
60 ret = !strcmp("true", out.buf);
65 static int apply_autostash(void)
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;
78 struct object_id orig_head;
80 const char *onto_name;
81 const char *revisions;
82 const char *switch_to;
84 struct commit *restrict_revision;
85 int dont_finish_rebase;
87 REBASE_NO_QUIET = 1<<0,
88 REBASE_VERBOSE = 1<<1,
89 REBASE_DIFFSTAT = 1<<2,
91 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
93 struct strbuf git_am_opt;
96 static int is_interactive(struct rebase_options *opts)
98 return opts->type == REBASE_INTERACTIVE ||
99 opts->type == REBASE_PRESERVE_MERGES;
102 /* Returns the filename prefixed by the state_dir */
103 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
105 static struct strbuf path = STRBUF_INIT;
106 static size_t prefix_len;
109 strbuf_addf(&path, "%s/", opts->state_dir);
110 prefix_len = path.len;
113 strbuf_setlen(&path, prefix_len);
114 strbuf_addstr(&path, filename);
118 static int finish_rebase(struct rebase_options *opts)
120 struct strbuf dir = STRBUF_INIT;
121 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
123 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
125 close_all_packs(the_repository->objects);
127 * We ignore errors in 'gc --auto', since the
128 * user should see them.
130 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
131 strbuf_addstr(&dir, opts->state_dir);
132 remove_dir_recursively(&dir, 0);
133 strbuf_release(&dir);
138 static struct commit *peel_committish(const char *name)
141 struct object_id oid;
143 if (get_oid(name, &oid))
145 obj = parse_object(the_repository, &oid);
146 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
149 static void add_var(struct strbuf *buf, const char *name, const char *value)
152 strbuf_addf(buf, "unset %s; ", name);
154 strbuf_addf(buf, "%s=", name);
155 sq_quote_buf(buf, value);
156 strbuf_addstr(buf, "; ");
160 static int run_specific_rebase(struct rebase_options *opts)
162 const char *argv[] = { NULL, NULL };
163 struct strbuf script_snippet = STRBUF_INIT;
165 const char *backend, *backend_func;
167 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
168 add_var(&script_snippet, "state_dir", opts->state_dir);
170 add_var(&script_snippet, "upstream_name", opts->upstream_name);
171 add_var(&script_snippet, "upstream",
172 oid_to_hex(&opts->upstream->object.oid));
173 add_var(&script_snippet, "head_name",
174 opts->head_name ? opts->head_name : "detached HEAD");
175 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
176 add_var(&script_snippet, "onto", oid_to_hex(&opts->onto->object.oid));
177 add_var(&script_snippet, "onto_name", opts->onto_name);
178 add_var(&script_snippet, "revisions", opts->revisions);
179 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
180 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
181 add_var(&script_snippet, "GIT_QUIET",
182 opts->flags & REBASE_NO_QUIET ? "" : "t");
183 add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
184 add_var(&script_snippet, "verbose",
185 opts->flags & REBASE_VERBOSE ? "t" : "");
186 add_var(&script_snippet, "diffstat",
187 opts->flags & REBASE_DIFFSTAT ? "t" : "");
188 add_var(&script_snippet, "force_rebase",
189 opts->flags & REBASE_FORCE ? "t" : "");
191 add_var(&script_snippet, "switch_to", opts->switch_to);
193 switch (opts->type) {
195 backend = "git-rebase--am";
196 backend_func = "git_rebase__am";
198 case REBASE_INTERACTIVE:
199 backend = "git-rebase--interactive";
200 backend_func = "git_rebase__interactive";
203 backend = "git-rebase--merge";
204 backend_func = "git_rebase__merge";
206 case REBASE_PRESERVE_MERGES:
207 backend = "git-rebase--preserve-merges";
208 backend_func = "git_rebase__preserve_merges";
211 BUG("Unhandled rebase type %d", opts->type);
215 strbuf_addf(&script_snippet,
216 ". git-sh-setup && . git-rebase--common &&"
217 " . %s && %s", backend, backend_func);
218 argv[0] = script_snippet.buf;
220 status = run_command_v_opt(argv, RUN_USING_SHELL);
221 if (opts->dont_finish_rebase)
223 else if (status == 0) {
224 if (!file_exists(state_dir_path("stopped-sha", opts)))
226 } else if (status == 2) {
227 struct strbuf dir = STRBUF_INIT;
230 strbuf_addstr(&dir, opts->state_dir);
231 remove_dir_recursively(&dir, 0);
232 strbuf_release(&dir);
233 die("Nothing to do");
236 strbuf_release(&script_snippet);
238 return status ? -1 : 0;
241 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
243 static int reset_head(struct object_id *oid, const char *action,
244 const char *switch_to_branch, int detach_head)
246 struct object_id head_oid;
247 struct tree_desc desc;
248 struct lock_file lock = LOCK_INIT;
249 struct unpack_trees_options unpack_tree_opts;
251 const char *reflog_action;
252 struct strbuf msg = STRBUF_INIT;
254 struct object_id *orig = NULL, oid_orig,
255 *old_orig = NULL, oid_old_orig;
258 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
259 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
261 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
265 if (get_oid("HEAD", &head_oid)) {
266 rollback_lock_file(&lock);
267 return error(_("could not determine HEAD revision"));
272 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
273 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
274 unpack_tree_opts.head_idx = 1;
275 unpack_tree_opts.src_index = the_repository->index;
276 unpack_tree_opts.dst_index = the_repository->index;
277 unpack_tree_opts.fn = oneway_merge;
278 unpack_tree_opts.update = 1;
279 unpack_tree_opts.merge = 1;
281 unpack_tree_opts.reset = 1;
283 if (read_index_unmerged(the_repository->index) < 0) {
284 rollback_lock_file(&lock);
285 return error(_("could not read index"));
288 if (!fill_tree_descriptor(&desc, oid)) {
289 error(_("failed to find tree of %s"), oid_to_hex(oid));
290 rollback_lock_file(&lock);
291 free((void *)desc.buffer);
295 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
296 rollback_lock_file(&lock);
297 free((void *)desc.buffer);
301 tree = parse_tree_indirect(oid);
302 prime_cache_tree(the_repository->index, tree);
304 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
305 ret = error(_("could not write index"));
306 free((void *)desc.buffer);
311 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
312 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
313 prefix_len = msg.len;
315 if (!get_oid("ORIG_HEAD", &oid_old_orig))
316 old_orig = &oid_old_orig;
317 if (!get_oid("HEAD", &oid_orig)) {
319 strbuf_addstr(&msg, "updating ORIG_HEAD");
320 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
321 UPDATE_REFS_MSG_ON_ERR);
323 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
324 strbuf_setlen(&msg, prefix_len);
325 strbuf_addstr(&msg, "updating HEAD");
326 if (!switch_to_branch)
327 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
328 UPDATE_REFS_MSG_ON_ERR);
330 ret = create_symref("HEAD", switch_to_branch, msg.buf);
332 ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
333 UPDATE_REFS_MSG_ON_ERR);
336 strbuf_release(&msg);
340 static int rebase_config(const char *var, const char *value, void *data)
342 struct rebase_options *opts = data;
344 if (!strcmp(var, "rebase.stat")) {
345 if (git_config_bool(var, value))
346 opts->flags |= REBASE_DIFFSTAT;
348 opts->flags &= !REBASE_DIFFSTAT;
352 return git_default_config(var, value, data);
356 * Determines whether the commits in from..to are linear, i.e. contain
357 * no merge commits. This function *expects* `from` to be an ancestor of
360 static int is_linear_history(struct commit *from, struct commit *to)
362 while (to && to != from) {
366 if (to->parents->next)
368 to = to->parents->item;
373 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
374 struct object_id *merge_base)
376 struct commit *head = lookup_commit(the_repository, head_oid);
377 struct commit_list *merge_bases;
383 merge_bases = get_merge_bases(onto, head);
384 if (merge_bases && !merge_bases->next) {
385 oidcpy(merge_base, &merge_bases->item->object.oid);
386 res = !oidcmp(merge_base, &onto->object.oid);
388 oidcpy(merge_base, &null_oid);
391 free_commit_list(merge_bases);
392 return res && is_linear_history(onto, head);
395 int cmd_rebase(int argc, const char **argv, const char *prefix)
397 struct rebase_options options = {
398 .type = REBASE_UNSPECIFIED,
399 .flags = REBASE_NO_QUIET,
400 .git_am_opt = STRBUF_INIT,
402 const char *branch_name;
403 int ret, flags, in_progress = 0;
404 int ok_to_skip_pre_rebase = 0;
405 struct strbuf msg = STRBUF_INIT;
406 struct strbuf revisions = STRBUF_INIT;
407 struct strbuf buf = STRBUF_INIT;
408 struct object_id merge_base;
409 struct option builtin_rebase_options[] = {
410 OPT_STRING(0, "onto", &options.onto_name,
412 N_("rebase onto given branch instead of upstream")),
413 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
414 N_("allow pre-rebase hook to run")),
415 OPT_NEGBIT('q', "quiet", &options.flags,
416 N_("be quiet. implies --no-stat"),
417 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
418 OPT_BIT('v', "verbose", &options.flags,
419 N_("display a diffstat of what changed upstream"),
420 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
421 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
422 N_("do not show diffstat of what changed upstream"),
423 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
424 OPT_BIT('f', "force-rebase", &options.flags,
425 N_("cherry-pick all commits, even if unchanged"),
427 OPT_BIT(0, "no-ff", &options.flags,
428 N_("cherry-pick all commits, even if unchanged"),
434 * NEEDSWORK: Once the builtin rebase has been tested enough
435 * and git-legacy-rebase.sh is retired to contrib/, this preamble
439 if (!use_builtin_rebase()) {
440 const char *path = mkpath("%s/git-legacy-rebase",
443 if (sane_execvp(path, (char **)argv) < 0)
444 die_errno(_("could not exec %s"), path);
446 BUG("sane_execvp() returned???");
449 if (argc == 2 && !strcmp(argv[1], "-h"))
450 usage_with_options(builtin_rebase_usage,
451 builtin_rebase_options);
453 prefix = setup_git_directory();
454 trace_repo_setup(prefix);
457 git_config(rebase_config, &options);
459 if (is_directory(apply_dir())) {
460 options.type = REBASE_AM;
461 options.state_dir = apply_dir();
462 } else if (is_directory(merge_dir())) {
464 strbuf_addf(&buf, "%s/rewritten", merge_dir());
465 if (is_directory(buf.buf)) {
466 options.type = REBASE_PRESERVE_MERGES;
467 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
470 strbuf_addf(&buf, "%s/interactive", merge_dir());
471 if(file_exists(buf.buf)) {
472 options.type = REBASE_INTERACTIVE;
473 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
475 options.type = REBASE_MERGE;
477 options.state_dir = merge_dir();
480 if (options.type != REBASE_UNSPECIFIED)
483 argc = parse_options(argc, argv, prefix,
484 builtin_rebase_options,
485 builtin_rebase_usage, 0);
488 usage_with_options(builtin_rebase_usage,
489 builtin_rebase_options);
491 /* Make sure no rebase is in progress */
493 const char *last_slash = strrchr(options.state_dir, '/');
494 const char *state_dir_base =
495 last_slash ? last_slash + 1 : options.state_dir;
496 const char *cmd_live_rebase =
497 "git rebase (--continue | --abort | --skip)";
499 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
500 die(_("It seems that there is already a %s directory, and\n"
501 "I wonder if you are in the middle of another rebase. "
503 "case, please try\n\t%s\n"
504 "If that is not the case, please\n\t%s\n"
505 "and run me again. I am stopping in case you still "
507 "valuable there.\n"),
508 state_dir_base, cmd_live_rebase, buf.buf);
511 if (!(options.flags & REBASE_NO_QUIET))
512 strbuf_addstr(&options.git_am_opt, " -q");
514 switch (options.type) {
516 case REBASE_INTERACTIVE:
517 case REBASE_PRESERVE_MERGES:
518 options.state_dir = merge_dir();
521 options.state_dir = apply_dir();
524 /* the default rebase backend is `--am` */
525 options.type = REBASE_AM;
526 options.state_dir = apply_dir();
532 die("TODO: handle @{upstream}");
534 options.upstream_name = argv[0];
537 if (!strcmp(options.upstream_name, "-"))
538 options.upstream_name = "@{-1}";
540 options.upstream = peel_committish(options.upstream_name);
541 if (!options.upstream)
542 die(_("invalid upstream '%s'"), options.upstream_name);
543 options.upstream_arg = options.upstream_name;
545 die("TODO: upstream for --root");
547 /* Make sure the branch to rebase onto is valid. */
548 if (!options.onto_name)
549 options.onto_name = options.upstream_name;
550 if (strstr(options.onto_name, "...")) {
551 if (get_oid_mb(options.onto_name, &merge_base) < 0)
552 die(_("'%s': need exactly one merge base"),
554 options.onto = lookup_commit_or_die(&merge_base,
557 options.onto = peel_committish(options.onto_name);
559 die(_("Does not point to a valid commit '%s'"),
564 * If the branch to rebase is given, that is the branch we will rebase
565 * branch_name -- branch/commit being rebased, or
566 * HEAD (already detached)
567 * orig_head -- commit object name of tip of the branch before rebasing
568 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
571 /* Is it "rebase other branchname" or "rebase other commit"? */
572 branch_name = argv[0];
573 options.switch_to = argv[0];
575 /* Is it a local branch? */
577 strbuf_addf(&buf, "refs/heads/%s", branch_name);
578 if (!read_ref(buf.buf, &options.orig_head))
579 options.head_name = xstrdup(buf.buf);
580 /* If not is it a valid ref (branch or commit)? */
581 else if (!get_oid(branch_name, &options.orig_head))
582 options.head_name = NULL;
584 die(_("fatal: no such branch/commit '%s'"),
586 } else if (argc == 0) {
587 /* Do not need to switch branches, we are already on it. */
589 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
591 if (!options.head_name)
592 die(_("No such ref: %s"), "HEAD");
593 if (flags & REF_ISSYMREF) {
594 if (!skip_prefix(options.head_name,
595 "refs/heads/", &branch_name))
596 branch_name = options.head_name;
599 free(options.head_name);
600 options.head_name = NULL;
601 branch_name = "HEAD";
603 if (get_oid("HEAD", &options.orig_head))
604 die(_("Could not resolve HEAD to a revision"));
606 BUG("unexpected number of arguments left to parse");
608 if (read_index(the_repository->index) < 0)
609 die(_("could not read index"));
611 if (require_clean_work_tree("rebase",
612 _("Please commit or stash them."), 1, 1)) {
618 * Now we are rebasing commits upstream..orig_head (or with --root,
619 * everything leading up to orig_head) on top of onto.
623 * Check if we are already based on onto with linear history,
624 * but this should be done only when upstream and onto are the same
625 * and if this is not an interactive rebase.
627 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
628 !is_interactive(&options) && !options.restrict_revision &&
629 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
632 if (!(options.flags & REBASE_FORCE)) {
633 /* Lazily switch to the target branch if needed... */
634 if (options.switch_to) {
635 struct object_id oid;
637 if (get_oid(options.switch_to, &oid) < 0) {
638 ret = !!error(_("could not parse '%s'"),
644 strbuf_addf(&buf, "rebase: checkout %s",
646 if (reset_head(&oid, "checkout",
647 options.head_name, 0) < 0) {
648 ret = !!error(_("could not switch to "
655 if (!(options.flags & REBASE_NO_QUIET))
657 else if (!strcmp(branch_name, "HEAD") &&
658 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
659 puts(_("HEAD is up to date."));
661 printf(_("Current branch %s is up to date.\n"),
663 ret = !!finish_rebase(&options);
665 } else if (!(options.flags & REBASE_NO_QUIET))
667 else if (!strcmp(branch_name, "HEAD") &&
668 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
669 puts(_("HEAD is up to date, rebase forced."));
671 printf(_("Current branch %s is up to date, rebase "
672 "forced.\n"), branch_name);
675 /* If a hook exists, give it a chance to interrupt*/
676 if (!ok_to_skip_pre_rebase &&
677 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
678 argc ? argv[0] : NULL, NULL))
679 die(_("The pre-rebase hook refused to rebase."));
681 if (options.flags & REBASE_DIFFSTAT) {
682 struct diff_options opts;
684 if (options.flags & REBASE_VERBOSE)
685 printf(_("Changes from %s to %s:\n"),
686 oid_to_hex(&merge_base),
687 oid_to_hex(&options.onto->object.oid));
689 /* We want color (if set), but no pager */
691 opts.stat_width = -1; /* use full terminal width */
692 opts.stat_graph_width = -1; /* respect statGraphWidth config */
693 opts.output_format |=
694 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
695 opts.detect_rename = DIFF_DETECT_RENAME;
696 diff_setup_done(&opts);
697 diff_tree_oid(&merge_base, &options.onto->object.oid,
703 /* Detach HEAD and reset the tree */
704 if (options.flags & REBASE_NO_QUIET)
705 printf(_("First, rewinding head to replay your work on top of "
708 strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
709 if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
710 die(_("Could not detach HEAD"));
711 strbuf_release(&msg);
713 strbuf_addf(&revisions, "%s..%s",
714 options.root ? oid_to_hex(&options.onto->object.oid) :
715 (options.restrict_revision ?
716 oid_to_hex(&options.restrict_revision->object.oid) :
717 oid_to_hex(&options.upstream->object.oid)),
718 oid_to_hex(&options.orig_head));
720 options.revisions = revisions.buf;
722 ret = !!run_specific_rebase(&options);
725 strbuf_release(&revisions);
726 free(options.head_name);