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