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;
83 struct commit *restrict_revision;
84 int dont_finish_rebase;
86 REBASE_NO_QUIET = 1<<0,
87 REBASE_VERBOSE = 1<<1,
88 REBASE_DIFFSTAT = 1<<2,
91 struct strbuf git_am_opt;
94 static int is_interactive(struct rebase_options *opts)
96 return opts->type == REBASE_INTERACTIVE ||
97 opts->type == REBASE_PRESERVE_MERGES;
100 /* Returns the filename prefixed by the state_dir */
101 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
103 static struct strbuf path = STRBUF_INIT;
104 static size_t prefix_len;
107 strbuf_addf(&path, "%s/", opts->state_dir);
108 prefix_len = path.len;
111 strbuf_setlen(&path, prefix_len);
112 strbuf_addstr(&path, filename);
116 static int finish_rebase(struct rebase_options *opts)
118 struct strbuf dir = STRBUF_INIT;
119 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
121 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
123 close_all_packs(the_repository->objects);
125 * We ignore errors in 'gc --auto', since the
126 * user should see them.
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);
136 static struct commit *peel_committish(const char *name)
139 struct object_id oid;
141 if (get_oid(name, &oid))
143 obj = parse_object(the_repository, &oid);
144 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
147 static void add_var(struct strbuf *buf, const char *name, const char *value)
150 strbuf_addf(buf, "unset %s; ", name);
152 strbuf_addf(buf, "%s=", name);
153 sq_quote_buf(buf, value);
154 strbuf_addstr(buf, "; ");
158 static int run_specific_rebase(struct rebase_options *opts)
160 const char *argv[] = { NULL, NULL };
161 struct strbuf script_snippet = STRBUF_INIT;
163 const char *backend, *backend_func;
165 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
166 add_var(&script_snippet, "state_dir", opts->state_dir);
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" : "");
188 switch (opts->type) {
190 backend = "git-rebase--am";
191 backend_func = "git_rebase__am";
193 case REBASE_INTERACTIVE:
194 backend = "git-rebase--interactive";
195 backend_func = "git_rebase__interactive";
198 backend = "git-rebase--merge";
199 backend_func = "git_rebase__merge";
201 case REBASE_PRESERVE_MERGES:
202 backend = "git-rebase--preserve-merges";
203 backend_func = "git_rebase__preserve_merges";
206 BUG("Unhandled rebase type %d", opts->type);
210 strbuf_addf(&script_snippet,
211 ". git-sh-setup && . git-rebase--common &&"
212 " . %s && %s", backend, backend_func);
213 argv[0] = script_snippet.buf;
215 status = run_command_v_opt(argv, RUN_USING_SHELL);
216 if (opts->dont_finish_rebase)
218 else if (status == 0) {
219 if (!file_exists(state_dir_path("stopped-sha", opts)))
221 } else if (status == 2) {
222 struct strbuf dir = STRBUF_INIT;
225 strbuf_addstr(&dir, opts->state_dir);
226 remove_dir_recursively(&dir, 0);
227 strbuf_release(&dir);
228 die("Nothing to do");
231 strbuf_release(&script_snippet);
233 return status ? -1 : 0;
236 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
238 static int reset_head(struct object_id *oid, const char *action,
239 const char *switch_to_branch, int detach_head)
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;
246 const char *reflog_action;
247 struct strbuf msg = STRBUF_INIT;
249 struct object_id *orig = NULL, oid_orig,
250 *old_orig = NULL, oid_old_orig;
253 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
257 if (get_oid("HEAD", &head_oid)) {
258 rollback_lock_file(&lock);
259 return error(_("could not determine HEAD revision"));
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;
273 unpack_tree_opts.reset = 1;
275 if (read_index_unmerged(the_repository->index) < 0) {
276 rollback_lock_file(&lock);
277 return error(_("could not read index"));
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);
287 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
288 rollback_lock_file(&lock);
289 free((void *)desc.buffer);
293 tree = parse_tree_indirect(oid);
294 prime_cache_tree(the_repository->index, tree);
296 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
297 ret = error(_("could not write index"));
298 free((void *)desc.buffer);
303 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
304 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
305 prefix_len = msg.len;
307 if (!get_oid("ORIG_HEAD", &oid_old_orig))
308 old_orig = &oid_old_orig;
309 if (!get_oid("HEAD", &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);
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);
322 ret = create_symref("HEAD", switch_to_branch, msg.buf);
324 ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
325 UPDATE_REFS_MSG_ON_ERR);
328 strbuf_release(&msg);
332 static int rebase_config(const char *var, const char *value, void *data)
334 struct rebase_options *opts = data;
336 if (!strcmp(var, "rebase.stat")) {
337 if (git_config_bool(var, value))
338 opts->flags |= REBASE_DIFFSTAT;
340 opts->flags &= !REBASE_DIFFSTAT;
344 return git_default_config(var, value, data);
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
352 static int is_linear_history(struct commit *from, struct commit *to)
354 while (to && to != from) {
358 if (to->parents->next)
360 to = to->parents->item;
365 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
366 struct object_id *merge_base)
368 struct commit *head = lookup_commit(the_repository, head_oid);
369 struct commit_list *merge_bases;
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);
380 oidcpy(merge_base, &null_oid);
383 free_commit_list(merge_bases);
384 return res && is_linear_history(onto, head);
387 int cmd_rebase(int argc, const char **argv, const char *prefix)
389 struct rebase_options options = {
390 .type = REBASE_UNSPECIFIED,
391 .flags = REBASE_NO_QUIET,
392 .git_am_opt = STRBUF_INIT,
394 const char *branch_name;
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,
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"),
418 OPT_BIT(0, "no-ff", &options.flags,
419 N_("cherry-pick all commits, even if unchanged"),
425 * NEEDSWORK: Once the builtin rebase has been tested enough
426 * and git-legacy-rebase.sh is retired to contrib/, this preamble
430 if (!use_builtin_rebase()) {
431 const char *path = mkpath("%s/git-legacy-rebase",
434 if (sane_execvp(path, (char **)argv) < 0)
435 die_errno(_("could not exec %s"), path);
437 BUG("sane_execvp() returned???");
440 if (argc == 2 && !strcmp(argv[1], "-h"))
441 usage_with_options(builtin_rebase_usage,
442 builtin_rebase_options);
444 prefix = setup_git_directory();
445 trace_repo_setup(prefix);
448 git_config(rebase_config, &options);
450 argc = parse_options(argc, argv, prefix,
451 builtin_rebase_options,
452 builtin_rebase_usage, 0);
455 usage_with_options(builtin_rebase_usage,
456 builtin_rebase_options);
458 if (!(options.flags & REBASE_NO_QUIET))
459 strbuf_addstr(&options.git_am_opt, " -q");
461 switch (options.type) {
463 case REBASE_INTERACTIVE:
464 case REBASE_PRESERVE_MERGES:
465 options.state_dir = merge_dir();
468 options.state_dir = apply_dir();
471 /* the default rebase backend is `--am` */
472 options.type = REBASE_AM;
473 options.state_dir = apply_dir();
479 die("TODO: handle @{upstream}");
481 options.upstream_name = argv[0];
484 if (!strcmp(options.upstream_name, "-"))
485 options.upstream_name = "@{-1}";
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;
492 die("TODO: upstream for --root");
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"),
501 options.onto = lookup_commit_or_die(&merge_base,
504 options.onto = peel_committish(options.onto_name);
506 die(_("Does not point to a valid commit '%s'"),
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"
518 die("TODO: handle switch_to");
520 /* Do not need to switch branches, we are already on it. */
522 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
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;
532 options.head_name = xstrdup("detached HEAD");
533 branch_name = "HEAD";
535 if (get_oid("HEAD", &options.orig_head))
536 die(_("Could not resolve HEAD to a revision"));
539 if (read_index(the_repository->index) < 0)
540 die(_("could not read index"));
542 if (require_clean_work_tree("rebase",
543 _("Please commit or stash them."), 1, 1)) {
549 * Now we are rebasing commits upstream..orig_head (or with --root,
550 * everything leading up to orig_head) on top of onto.
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.
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)) {
563 if (!(options.flags & REBASE_FORCE)) {
564 if (!(options.flags & REBASE_NO_QUIET))
566 else if (!strcmp(branch_name, "HEAD") &&
567 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
568 puts(_("HEAD is up to date."));
570 printf(_("Current branch %s is up to date.\n"),
572 ret = !!finish_rebase(&options);
574 } else if (!(options.flags & REBASE_NO_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."));
580 printf(_("Current branch %s is up to date, rebase "
581 "forced.\n"), branch_name);
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."));
590 if (options.flags & REBASE_DIFFSTAT) {
591 struct diff_options opts;
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));
598 /* We want color (if set), but no pager */
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,
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 "
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);
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));
629 options.revisions = revisions.buf;
631 ret = !!run_specific_rebase(&options);
634 strbuf_release(&revisions);
635 free(options.head_name);