1/*
2 * "git rebase" builtin command
3 *
4 * Copyright (c) 2018 Pratik Karki
5 */
6
7#include "builtin.h"
8#include "run-command.h"
9#include "exec-cmd.h"
10#include "argv-array.h"
11#include "dir.h"
12#include "packfile.h"
13#include "refs.h"
14#include "quote.h"
15#include "config.h"
16#include "cache-tree.h"
17#include "unpack-trees.h"
18#include "lockfile.h"
19#include "parse-options.h"
20#include "commit.h"
21#include "diff.h"
22#include "wt-status.h"
23#include "revision.h"
24#include "rerere.h"
25
26static 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
33};
34
35static GIT_PATH_FUNC(apply_dir, "rebase-apply")
36static GIT_PATH_FUNC(merge_dir, "rebase-merge")
37
38enum rebase_type {
39 REBASE_UNSPECIFIED = -1,
40 REBASE_AM,
41 REBASE_MERGE,
42 REBASE_INTERACTIVE,
43 REBASE_PRESERVE_MERGES
44};
45
46static int use_builtin_rebase(void)
47{
48 struct child_process cp = CHILD_PROCESS_INIT;
49 struct strbuf out = STRBUF_INIT;
50 int ret;
51
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;
58 }
59
60 strbuf_trim(&out);
61 ret = !strcmp("true", out.buf);
62 strbuf_release(&out);
63 return ret;
64}
65
66struct 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 commit *restrict_revision;
80 int dont_finish_rebase;
81 enum {
82 REBASE_NO_QUIET = 1<<0,
83 REBASE_VERBOSE = 1<<1,
84 REBASE_DIFFSTAT = 1<<2,
85 REBASE_FORCE = 1<<3,
86 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
87 } flags;
88 struct strbuf git_am_opt;
89 const char *action;
90 int signoff;
91 int allow_rerere_autoupdate;
92 int keep_empty;
93 int autosquash;
94 char *gpg_sign_opt;
95 int autostash;
96 char *cmd;
97};
98
99static int is_interactive(struct rebase_options *opts)
100{
101 return opts->type == REBASE_INTERACTIVE ||
102 opts->type == REBASE_PRESERVE_MERGES;
103}
104
105static void imply_interactive(struct rebase_options *opts, const char *option)
106{
107 switch (opts->type) {
108 case REBASE_AM:
109 die(_("%s requires an interactive rebase"), option);
110 break;
111 case REBASE_INTERACTIVE:
112 case REBASE_PRESERVE_MERGES:
113 break;
114 case REBASE_MERGE:
115 /* we silently *upgrade* --merge to --interactive if needed */
116 default:
117 opts->type = REBASE_INTERACTIVE; /* implied */
118 break;
119 }
120}
121
122/* Returns the filename prefixed by the state_dir */
123static const char *state_dir_path(const char *filename, struct rebase_options *opts)
124{
125 static struct strbuf path = STRBUF_INIT;
126 static size_t prefix_len;
127
128 if (!prefix_len) {
129 strbuf_addf(&path, "%s/", opts->state_dir);
130 prefix_len = path.len;
131 }
132
133 strbuf_setlen(&path, prefix_len);
134 strbuf_addstr(&path, filename);
135 return path.buf;
136}
137
138/* Read one file, then strip line endings */
139static int read_one(const char *path, struct strbuf *buf)
140{
141 if (strbuf_read_file(buf, path, 0) < 0)
142 return error_errno(_("could not read '%s'"), path);
143 strbuf_trim_trailing_newline(buf);
144 return 0;
145}
146
147/* Initialize the rebase options from the state directory. */
148static int read_basic_state(struct rebase_options *opts)
149{
150 struct strbuf head_name = STRBUF_INIT;
151 struct strbuf buf = STRBUF_INIT;
152 struct object_id oid;
153
154 if (read_one(state_dir_path("head-name", opts), &head_name) ||
155 read_one(state_dir_path("onto", opts), &buf))
156 return -1;
157 opts->head_name = starts_with(head_name.buf, "refs/") ?
158 xstrdup(head_name.buf) : NULL;
159 strbuf_release(&head_name);
160 if (get_oid(buf.buf, &oid))
161 return error(_("could not get 'onto': '%s'"), buf.buf);
162 opts->onto = lookup_commit_or_die(&oid, buf.buf);
163
164 /*
165 * We always write to orig-head, but interactive rebase used to write to
166 * head. Fall back to reading from head to cover for the case that the
167 * user upgraded git with an ongoing interactive rebase.
168 */
169 strbuf_reset(&buf);
170 if (file_exists(state_dir_path("orig-head", opts))) {
171 if (read_one(state_dir_path("orig-head", opts), &buf))
172 return -1;
173 } else if (read_one(state_dir_path("head", opts), &buf))
174 return -1;
175 if (get_oid(buf.buf, &opts->orig_head))
176 return error(_("invalid orig-head: '%s'"), buf.buf);
177
178 strbuf_reset(&buf);
179 if (read_one(state_dir_path("quiet", opts), &buf))
180 return -1;
181 if (buf.len)
182 opts->flags &= ~REBASE_NO_QUIET;
183 else
184 opts->flags |= REBASE_NO_QUIET;
185
186 if (file_exists(state_dir_path("verbose", opts)))
187 opts->flags |= REBASE_VERBOSE;
188
189 if (file_exists(state_dir_path("signoff", opts))) {
190 opts->signoff = 1;
191 opts->flags |= REBASE_FORCE;
192 }
193
194 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
195 strbuf_reset(&buf);
196 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
197 &buf))
198 return -1;
199 if (!strcmp(buf.buf, "--rerere-autoupdate"))
200 opts->allow_rerere_autoupdate = 1;
201 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
202 opts->allow_rerere_autoupdate = 0;
203 else
204 warning(_("ignoring invalid allow_rerere_autoupdate: "
205 "'%s'"), buf.buf);
206 } else
207 opts->allow_rerere_autoupdate = -1;
208
209 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
210 strbuf_reset(&buf);
211 if (read_one(state_dir_path("gpg_sign_opt", opts),
212 &buf))
213 return -1;
214 free(opts->gpg_sign_opt);
215 opts->gpg_sign_opt = xstrdup(buf.buf);
216 }
217
218 strbuf_release(&buf);
219
220 return 0;
221}
222
223static int apply_autostash(struct rebase_options *opts)
224{
225 const char *path = state_dir_path("autostash", opts);
226 struct strbuf autostash = STRBUF_INIT;
227 struct child_process stash_apply = CHILD_PROCESS_INIT;
228
229 if (!file_exists(path))
230 return 0;
231
232 if (read_one(state_dir_path("autostash", opts), &autostash))
233 return error(_("Could not read '%s'"), path);
234 argv_array_pushl(&stash_apply.args,
235 "stash", "apply", autostash.buf, NULL);
236 stash_apply.git_cmd = 1;
237 stash_apply.no_stderr = stash_apply.no_stdout =
238 stash_apply.no_stdin = 1;
239 if (!run_command(&stash_apply))
240 printf(_("Applied autostash.\n"));
241 else {
242 struct argv_array args = ARGV_ARRAY_INIT;
243 int res = 0;
244
245 argv_array_pushl(&args,
246 "stash", "store", "-m", "autostash", "-q",
247 autostash.buf, NULL);
248 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
249 res = error(_("Cannot store %s"), autostash.buf);
250 argv_array_clear(&args);
251 strbuf_release(&autostash);
252 if (res)
253 return res;
254
255 fprintf(stderr,
256 _("Applying autostash resulted in conflicts.\n"
257 "Your changes are safe in the stash.\n"
258 "You can run \"git stash pop\" or \"git stash drop\" "
259 "at any time.\n"));
260 }
261
262 strbuf_release(&autostash);
263 return 0;
264}
265
266static int finish_rebase(struct rebase_options *opts)
267{
268 struct strbuf dir = STRBUF_INIT;
269 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
270
271 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
272 apply_autostash(opts);
273 close_all_packs(the_repository->objects);
274 /*
275 * We ignore errors in 'gc --auto', since the
276 * user should see them.
277 */
278 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
279 strbuf_addstr(&dir, opts->state_dir);
280 remove_dir_recursively(&dir, 0);
281 strbuf_release(&dir);
282
283 return 0;
284}
285
286static struct commit *peel_committish(const char *name)
287{
288 struct object *obj;
289 struct object_id oid;
290
291 if (get_oid(name, &oid))
292 return NULL;
293 obj = parse_object(the_repository, &oid);
294 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
295}
296
297static void add_var(struct strbuf *buf, const char *name, const char *value)
298{
299 if (!value)
300 strbuf_addf(buf, "unset %s; ", name);
301 else {
302 strbuf_addf(buf, "%s=", name);
303 sq_quote_buf(buf, value);
304 strbuf_addstr(buf, "; ");
305 }
306}
307
308static int run_specific_rebase(struct rebase_options *opts)
309{
310 const char *argv[] = { NULL, NULL };
311 struct strbuf script_snippet = STRBUF_INIT;
312 int status;
313 const char *backend, *backend_func;
314
315 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
316 add_var(&script_snippet, "state_dir", opts->state_dir);
317
318 add_var(&script_snippet, "upstream_name", opts->upstream_name);
319 add_var(&script_snippet, "upstream", opts->upstream ?
320 oid_to_hex(&opts->upstream->object.oid) : NULL);
321 add_var(&script_snippet, "head_name",
322 opts->head_name ? opts->head_name : "detached HEAD");
323 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
324 add_var(&script_snippet, "onto", opts->onto ?
325 oid_to_hex(&opts->onto->object.oid) : NULL);
326 add_var(&script_snippet, "onto_name", opts->onto_name);
327 add_var(&script_snippet, "revisions", opts->revisions);
328 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
329 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
330 add_var(&script_snippet, "GIT_QUIET",
331 opts->flags & REBASE_NO_QUIET ? "" : "t");
332 add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
333 add_var(&script_snippet, "verbose",
334 opts->flags & REBASE_VERBOSE ? "t" : "");
335 add_var(&script_snippet, "diffstat",
336 opts->flags & REBASE_DIFFSTAT ? "t" : "");
337 add_var(&script_snippet, "force_rebase",
338 opts->flags & REBASE_FORCE ? "t" : "");
339 if (opts->switch_to)
340 add_var(&script_snippet, "switch_to", opts->switch_to);
341 add_var(&script_snippet, "action", opts->action ? opts->action : "");
342 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
343 add_var(&script_snippet, "allow_rerere_autoupdate",
344 opts->allow_rerere_autoupdate < 0 ? "" :
345 opts->allow_rerere_autoupdate ?
346 "--rerere-autoupdate" : "--no-rerere-autoupdate");
347 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
348 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
349 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
350 add_var(&script_snippet, "cmd", opts->cmd);
351
352 switch (opts->type) {
353 case REBASE_AM:
354 backend = "git-rebase--am";
355 backend_func = "git_rebase__am";
356 break;
357 case REBASE_INTERACTIVE:
358 backend = "git-rebase--interactive";
359 backend_func = "git_rebase__interactive";
360 break;
361 case REBASE_MERGE:
362 backend = "git-rebase--merge";
363 backend_func = "git_rebase__merge";
364 break;
365 case REBASE_PRESERVE_MERGES:
366 backend = "git-rebase--preserve-merges";
367 backend_func = "git_rebase__preserve_merges";
368 break;
369 default:
370 BUG("Unhandled rebase type %d", opts->type);
371 break;
372 }
373
374 strbuf_addf(&script_snippet,
375 ". git-sh-setup && . git-rebase--common &&"
376 " . %s && %s", backend, backend_func);
377 argv[0] = script_snippet.buf;
378
379 status = run_command_v_opt(argv, RUN_USING_SHELL);
380 if (opts->dont_finish_rebase)
381 ; /* do nothing */
382 else if (status == 0) {
383 if (!file_exists(state_dir_path("stopped-sha", opts)))
384 finish_rebase(opts);
385 } else if (status == 2) {
386 struct strbuf dir = STRBUF_INIT;
387
388 apply_autostash(opts);
389 strbuf_addstr(&dir, opts->state_dir);
390 remove_dir_recursively(&dir, 0);
391 strbuf_release(&dir);
392 die("Nothing to do");
393 }
394
395 strbuf_release(&script_snippet);
396
397 return status ? -1 : 0;
398}
399
400#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
401
402static int reset_head(struct object_id *oid, const char *action,
403 const char *switch_to_branch, int detach_head)
404{
405 struct object_id head_oid;
406 struct tree_desc desc;
407 struct lock_file lock = LOCK_INIT;
408 struct unpack_trees_options unpack_tree_opts;
409 struct tree *tree;
410 const char *reflog_action;
411 struct strbuf msg = STRBUF_INIT;
412 size_t prefix_len;
413 struct object_id *orig = NULL, oid_orig,
414 *old_orig = NULL, oid_old_orig;
415 int ret = 0;
416
417 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
418 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
419
420 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
421 return -1;
422
423 if (!oid) {
424 if (get_oid("HEAD", &head_oid)) {
425 rollback_lock_file(&lock);
426 return error(_("could not determine HEAD revision"));
427 }
428 oid = &head_oid;
429 }
430
431 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
432 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
433 unpack_tree_opts.head_idx = 1;
434 unpack_tree_opts.src_index = the_repository->index;
435 unpack_tree_opts.dst_index = the_repository->index;
436 unpack_tree_opts.fn = oneway_merge;
437 unpack_tree_opts.update = 1;
438 unpack_tree_opts.merge = 1;
439 if (!detach_head)
440 unpack_tree_opts.reset = 1;
441
442 if (read_index_unmerged(the_repository->index) < 0) {
443 rollback_lock_file(&lock);
444 return error(_("could not read index"));
445 }
446
447 if (!fill_tree_descriptor(&desc, oid)) {
448 error(_("failed to find tree of %s"), oid_to_hex(oid));
449 rollback_lock_file(&lock);
450 free((void *)desc.buffer);
451 return -1;
452 }
453
454 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
455 rollback_lock_file(&lock);
456 free((void *)desc.buffer);
457 return -1;
458 }
459
460 tree = parse_tree_indirect(oid);
461 prime_cache_tree(the_repository->index, tree);
462
463 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
464 ret = error(_("could not write index"));
465 free((void *)desc.buffer);
466
467 if (ret)
468 return ret;
469
470 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
471 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
472 prefix_len = msg.len;
473
474 if (!get_oid("ORIG_HEAD", &oid_old_orig))
475 old_orig = &oid_old_orig;
476 if (!get_oid("HEAD", &oid_orig)) {
477 orig = &oid_orig;
478 strbuf_addstr(&msg, "updating ORIG_HEAD");
479 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
480 UPDATE_REFS_MSG_ON_ERR);
481 } else if (old_orig)
482 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
483 strbuf_setlen(&msg, prefix_len);
484 strbuf_addstr(&msg, "updating HEAD");
485 if (!switch_to_branch)
486 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
487 UPDATE_REFS_MSG_ON_ERR);
488 else {
489 ret = create_symref("HEAD", switch_to_branch, msg.buf);
490 if (!ret)
491 ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
492 UPDATE_REFS_MSG_ON_ERR);
493 }
494
495 strbuf_release(&msg);
496 return ret;
497}
498
499static int rebase_config(const char *var, const char *value, void *data)
500{
501 struct rebase_options *opts = data;
502
503 if (!strcmp(var, "rebase.stat")) {
504 if (git_config_bool(var, value))
505 opts->flags |= REBASE_DIFFSTAT;
506 else
507 opts->flags &= !REBASE_DIFFSTAT;
508 return 0;
509 }
510
511 if (!strcmp(var, "rebase.autosquash")) {
512 opts->autosquash = git_config_bool(var, value);
513 return 0;
514 }
515
516 if (!strcmp(var, "commit.gpgsign")) {
517 free(opts->gpg_sign_opt);
518 opts->gpg_sign_opt = git_config_bool(var, value) ?
519 xstrdup("-S") : NULL;
520 return 0;
521 }
522
523 if (!strcmp(var, "rebase.autostash")) {
524 opts->autostash = git_config_bool(var, value);
525 return 0;
526 }
527
528 return git_default_config(var, value, data);
529}
530
531/*
532 * Determines whether the commits in from..to are linear, i.e. contain
533 * no merge commits. This function *expects* `from` to be an ancestor of
534 * `to`.
535 */
536static int is_linear_history(struct commit *from, struct commit *to)
537{
538 while (to && to != from) {
539 parse_commit(to);
540 if (!to->parents)
541 return 1;
542 if (to->parents->next)
543 return 0;
544 to = to->parents->item;
545 }
546 return 1;
547}
548
549static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
550 struct object_id *merge_base)
551{
552 struct commit *head = lookup_commit(the_repository, head_oid);
553 struct commit_list *merge_bases;
554 int res;
555
556 if (!head)
557 return 0;
558
559 merge_bases = get_merge_bases(onto, head);
560 if (merge_bases && !merge_bases->next) {
561 oidcpy(merge_base, &merge_bases->item->object.oid);
562 res = !oidcmp(merge_base, &onto->object.oid);
563 } else {
564 oidcpy(merge_base, &null_oid);
565 res = 0;
566 }
567 free_commit_list(merge_bases);
568 return res && is_linear_history(onto, head);
569}
570
571/* -i followed by -m is still -i */
572static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
573{
574 struct rebase_options *opts = opt->value;
575
576 if (!is_interactive(opts))
577 opts->type = REBASE_MERGE;
578
579 return 0;
580}
581
582/* -i followed by -p is still explicitly interactive, but -p alone is not */
583static int parse_opt_interactive(const struct option *opt, const char *arg,
584 int unset)
585{
586 struct rebase_options *opts = opt->value;
587
588 opts->type = REBASE_INTERACTIVE;
589 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
590
591 return 0;
592}
593
594int cmd_rebase(int argc, const char **argv, const char *prefix)
595{
596 struct rebase_options options = {
597 .type = REBASE_UNSPECIFIED,
598 .flags = REBASE_NO_QUIET,
599 .git_am_opt = STRBUF_INIT,
600 .allow_rerere_autoupdate = -1,
601 };
602 const char *branch_name;
603 int ret, flags, total_argc, in_progress = 0;
604 int ok_to_skip_pre_rebase = 0;
605 struct strbuf msg = STRBUF_INIT;
606 struct strbuf revisions = STRBUF_INIT;
607 struct strbuf buf = STRBUF_INIT;
608 struct object_id merge_base;
609 enum {
610 NO_ACTION,
611 ACTION_CONTINUE,
612 ACTION_SKIP,
613 ACTION_ABORT,
614 ACTION_QUIT,
615 ACTION_EDIT_TODO,
616 ACTION_SHOW_CURRENT_PATCH,
617 } action = NO_ACTION;
618 int committer_date_is_author_date = 0;
619 int ignore_date = 0;
620 int ignore_whitespace = 0;
621 const char *gpg_sign = NULL;
622 int opt_c = -1;
623 struct string_list whitespace = STRING_LIST_INIT_NODUP;
624 struct string_list exec = STRING_LIST_INIT_NODUP;
625 struct option builtin_rebase_options[] = {
626 OPT_STRING(0, "onto", &options.onto_name,
627 N_("revision"),
628 N_("rebase onto given branch instead of upstream")),
629 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
630 N_("allow pre-rebase hook to run")),
631 OPT_NEGBIT('q', "quiet", &options.flags,
632 N_("be quiet. implies --no-stat"),
633 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
634 OPT_BIT('v', "verbose", &options.flags,
635 N_("display a diffstat of what changed upstream"),
636 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
637 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
638 N_("do not show diffstat of what changed upstream"),
639 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
640 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
641 N_("passed to 'git apply'")),
642 OPT_BOOL(0, "signoff", &options.signoff,
643 N_("add a Signed-off-by: line to each commit")),
644 OPT_BOOL(0, "committer-date-is-author-date",
645 &committer_date_is_author_date,
646 N_("passed to 'git am'")),
647 OPT_BOOL(0, "ignore-date", &ignore_date,
648 N_("passed to 'git am'")),
649 OPT_BIT('f', "force-rebase", &options.flags,
650 N_("cherry-pick all commits, even if unchanged"),
651 REBASE_FORCE),
652 OPT_BIT(0, "no-ff", &options.flags,
653 N_("cherry-pick all commits, even if unchanged"),
654 REBASE_FORCE),
655 OPT_CMDMODE(0, "continue", &action, N_("continue"),
656 ACTION_CONTINUE),
657 OPT_CMDMODE(0, "skip", &action,
658 N_("skip current patch and continue"), ACTION_SKIP),
659 OPT_CMDMODE(0, "abort", &action,
660 N_("abort and check out the original branch"),
661 ACTION_ABORT),
662 OPT_CMDMODE(0, "quit", &action,
663 N_("abort but keep HEAD where it is"), ACTION_QUIT),
664 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
665 "during an interactive rebase"), ACTION_EDIT_TODO),
666 OPT_CMDMODE(0, "show-current-patch", &action,
667 N_("show the patch file being applied or merged"),
668 ACTION_SHOW_CURRENT_PATCH),
669 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
670 N_("use merging strategies to rebase"),
671 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
672 parse_opt_merge },
673 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
674 N_("let the user edit the list of commits to rebase"),
675 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
676 parse_opt_interactive },
677 OPT_SET_INT('p', "preserve-merges", &options.type,
678 N_("try to recreate merges instead of ignoring "
679 "them"), REBASE_PRESERVE_MERGES),
680 OPT_BOOL(0, "rerere-autoupdate",
681 &options.allow_rerere_autoupdate,
682 N_("allow rerere to update index with resolved "
683 "conflict")),
684 OPT_BOOL('k', "keep-empty", &options.keep_empty,
685 N_("preserve empty commits during rebase")),
686 OPT_BOOL(0, "autosquash", &options.autosquash,
687 N_("move commits that begin with "
688 "squash!/fixup! under -i")),
689 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
690 N_("GPG-sign commits"),
691 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
692 OPT_STRING_LIST(0, "whitespace", &whitespace,
693 N_("whitespace"), N_("passed to 'git apply'")),
694 OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
695 REBASE_AM),
696 OPT_BOOL(0, "autostash", &options.autostash,
697 N_("automatically stash/stash pop before and after")),
698 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
699 N_("add exec lines after each commit of the "
700 "editable list")),
701 OPT_END(),
702 };
703
704 /*
705 * NEEDSWORK: Once the builtin rebase has been tested enough
706 * and git-legacy-rebase.sh is retired to contrib/, this preamble
707 * can be removed.
708 */
709
710 if (!use_builtin_rebase()) {
711 const char *path = mkpath("%s/git-legacy-rebase",
712 git_exec_path());
713
714 if (sane_execvp(path, (char **)argv) < 0)
715 die_errno(_("could not exec %s"), path);
716 else
717 BUG("sane_execvp() returned???");
718 }
719
720 if (argc == 2 && !strcmp(argv[1], "-h"))
721 usage_with_options(builtin_rebase_usage,
722 builtin_rebase_options);
723
724 prefix = setup_git_directory();
725 trace_repo_setup(prefix);
726 setup_work_tree();
727
728 git_config(rebase_config, &options);
729
730 strbuf_reset(&buf);
731 strbuf_addf(&buf, "%s/applying", apply_dir());
732 if(file_exists(buf.buf))
733 die(_("It looks like 'git am' is in progress. Cannot rebase."));
734
735 if (is_directory(apply_dir())) {
736 options.type = REBASE_AM;
737 options.state_dir = apply_dir();
738 } else if (is_directory(merge_dir())) {
739 strbuf_reset(&buf);
740 strbuf_addf(&buf, "%s/rewritten", merge_dir());
741 if (is_directory(buf.buf)) {
742 options.type = REBASE_PRESERVE_MERGES;
743 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
744 } else {
745 strbuf_reset(&buf);
746 strbuf_addf(&buf, "%s/interactive", merge_dir());
747 if(file_exists(buf.buf)) {
748 options.type = REBASE_INTERACTIVE;
749 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
750 } else
751 options.type = REBASE_MERGE;
752 }
753 options.state_dir = merge_dir();
754 }
755
756 if (options.type != REBASE_UNSPECIFIED)
757 in_progress = 1;
758
759 total_argc = argc;
760 argc = parse_options(argc, argv, prefix,
761 builtin_rebase_options,
762 builtin_rebase_usage, 0);
763
764 if (action != NO_ACTION && total_argc != 2) {
765 usage_with_options(builtin_rebase_usage,
766 builtin_rebase_options);
767 }
768
769 if (argc > 2)
770 usage_with_options(builtin_rebase_usage,
771 builtin_rebase_options);
772
773 if (action != NO_ACTION && !in_progress)
774 die(_("No rebase in progress?"));
775
776 if (action == ACTION_EDIT_TODO && !is_interactive(&options))
777 die(_("The --edit-todo action can only be used during "
778 "interactive rebase."));
779
780 switch (action) {
781 case ACTION_CONTINUE: {
782 struct object_id head;
783 struct lock_file lock_file = LOCK_INIT;
784 int fd;
785
786 options.action = "continue";
787
788 /* Sanity check */
789 if (get_oid("HEAD", &head))
790 die(_("Cannot read HEAD"));
791
792 fd = hold_locked_index(&lock_file, 0);
793 if (read_index(the_repository->index) < 0)
794 die(_("could not read index"));
795 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
796 NULL);
797 if (0 <= fd)
798 update_index_if_able(the_repository->index,
799 &lock_file);
800 rollback_lock_file(&lock_file);
801
802 if (has_unstaged_changes(1)) {
803 puts(_("You must edit all merge conflicts and then\n"
804 "mark them as resolved using git add"));
805 exit(1);
806 }
807 if (read_basic_state(&options))
808 exit(1);
809 goto run_rebase;
810 }
811 case ACTION_SKIP: {
812 struct string_list merge_rr = STRING_LIST_INIT_DUP;
813
814 options.action = "skip";
815
816 rerere_clear(&merge_rr);
817 string_list_clear(&merge_rr, 1);
818
819 if (reset_head(NULL, "reset", NULL, 0) < 0)
820 die(_("could not discard worktree changes"));
821 if (read_basic_state(&options))
822 exit(1);
823 goto run_rebase;
824 }
825 case ACTION_ABORT: {
826 struct string_list merge_rr = STRING_LIST_INIT_DUP;
827 options.action = "abort";
828
829 rerere_clear(&merge_rr);
830 string_list_clear(&merge_rr, 1);
831
832 if (read_basic_state(&options))
833 exit(1);
834 if (reset_head(&options.orig_head, "reset",
835 options.head_name, 0) < 0)
836 die(_("could not move back to %s"),
837 oid_to_hex(&options.orig_head));
838 ret = finish_rebase(&options);
839 goto cleanup;
840 }
841 case ACTION_QUIT: {
842 strbuf_reset(&buf);
843 strbuf_addstr(&buf, options.state_dir);
844 ret = !!remove_dir_recursively(&buf, 0);
845 if (ret)
846 die(_("could not remove '%s'"), options.state_dir);
847 goto cleanup;
848 }
849 case ACTION_EDIT_TODO:
850 options.action = "edit-todo";
851 options.dont_finish_rebase = 1;
852 goto run_rebase;
853 case ACTION_SHOW_CURRENT_PATCH:
854 options.action = "show-current-patch";
855 options.dont_finish_rebase = 1;
856 goto run_rebase;
857 case NO_ACTION:
858 break;
859 default:
860 BUG("action: %d", action);
861 }
862
863 /* Make sure no rebase is in progress */
864 if (in_progress) {
865 const char *last_slash = strrchr(options.state_dir, '/');
866 const char *state_dir_base =
867 last_slash ? last_slash + 1 : options.state_dir;
868 const char *cmd_live_rebase =
869 "git rebase (--continue | --abort | --skip)";
870 strbuf_reset(&buf);
871 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
872 die(_("It seems that there is already a %s directory, and\n"
873 "I wonder if you are in the middle of another rebase. "
874 "If that is the\n"
875 "case, please try\n\t%s\n"
876 "If that is not the case, please\n\t%s\n"
877 "and run me again. I am stopping in case you still "
878 "have something\n"
879 "valuable there.\n"),
880 state_dir_base, cmd_live_rebase, buf.buf);
881 }
882
883 if (!(options.flags & REBASE_NO_QUIET))
884 strbuf_addstr(&options.git_am_opt, " -q");
885
886 if (committer_date_is_author_date) {
887 strbuf_addstr(&options.git_am_opt,
888 " --committer-date-is-author-date");
889 options.flags |= REBASE_FORCE;
890 }
891
892 if (ignore_whitespace)
893 strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
894
895 if (ignore_date) {
896 strbuf_addstr(&options.git_am_opt, " --ignore-date");
897 options.flags |= REBASE_FORCE;
898 }
899
900 if (options.keep_empty)
901 imply_interactive(&options, "--keep-empty");
902
903 if (gpg_sign) {
904 free(options.gpg_sign_opt);
905 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
906 }
907
908 if (opt_c >= 0)
909 strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
910
911 if (whitespace.nr) {
912 int i;
913
914 for (i = 0; i < whitespace.nr; i++) {
915 const char *item = whitespace.items[i].string;
916
917 strbuf_addf(&options.git_am_opt, " --whitespace=%s",
918 item);
919
920 if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
921 options.flags |= REBASE_FORCE;
922 }
923 }
924
925 if (exec.nr) {
926 int i;
927
928 imply_interactive(&options, "--exec");
929
930 strbuf_reset(&buf);
931 for (i = 0; i < exec.nr; i++)
932 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
933 options.cmd = xstrdup(buf.buf);
934 }
935
936 switch (options.type) {
937 case REBASE_MERGE:
938 case REBASE_INTERACTIVE:
939 case REBASE_PRESERVE_MERGES:
940 options.state_dir = merge_dir();
941 break;
942 case REBASE_AM:
943 options.state_dir = apply_dir();
944 break;
945 default:
946 /* the default rebase backend is `--am` */
947 options.type = REBASE_AM;
948 options.state_dir = apply_dir();
949 break;
950 }
951
952 if (options.signoff) {
953 if (options.type == REBASE_PRESERVE_MERGES)
954 die("cannot combine '--signoff' with "
955 "'--preserve-merges'");
956 strbuf_addstr(&options.git_am_opt, " --signoff");
957 options.flags |= REBASE_FORCE;
958 }
959
960 if (!options.root) {
961 if (argc < 1)
962 die("TODO: handle @{upstream}");
963 else {
964 options.upstream_name = argv[0];
965 argc--;
966 argv++;
967 if (!strcmp(options.upstream_name, "-"))
968 options.upstream_name = "@{-1}";
969 }
970 options.upstream = peel_committish(options.upstream_name);
971 if (!options.upstream)
972 die(_("invalid upstream '%s'"), options.upstream_name);
973 options.upstream_arg = options.upstream_name;
974 } else
975 die("TODO: upstream for --root");
976
977 /* Make sure the branch to rebase onto is valid. */
978 if (!options.onto_name)
979 options.onto_name = options.upstream_name;
980 if (strstr(options.onto_name, "...")) {
981 if (get_oid_mb(options.onto_name, &merge_base) < 0)
982 die(_("'%s': need exactly one merge base"),
983 options.onto_name);
984 options.onto = lookup_commit_or_die(&merge_base,
985 options.onto_name);
986 } else {
987 options.onto = peel_committish(options.onto_name);
988 if (!options.onto)
989 die(_("Does not point to a valid commit '%s'"),
990 options.onto_name);
991 }
992
993 /*
994 * If the branch to rebase is given, that is the branch we will rebase
995 * branch_name -- branch/commit being rebased, or
996 * HEAD (already detached)
997 * orig_head -- commit object name of tip of the branch before rebasing
998 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
999 */
1000 if (argc == 1) {
1001 /* Is it "rebase other branchname" or "rebase other commit"? */
1002 branch_name = argv[0];
1003 options.switch_to = argv[0];
1004
1005 /* Is it a local branch? */
1006 strbuf_reset(&buf);
1007 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1008 if (!read_ref(buf.buf, &options.orig_head))
1009 options.head_name = xstrdup(buf.buf);
1010 /* If not is it a valid ref (branch or commit)? */
1011 else if (!get_oid(branch_name, &options.orig_head))
1012 options.head_name = NULL;
1013 else
1014 die(_("fatal: no such branch/commit '%s'"),
1015 branch_name);
1016 } else if (argc == 0) {
1017 /* Do not need to switch branches, we are already on it. */
1018 options.head_name =
1019 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1020 &flags));
1021 if (!options.head_name)
1022 die(_("No such ref: %s"), "HEAD");
1023 if (flags & REF_ISSYMREF) {
1024 if (!skip_prefix(options.head_name,
1025 "refs/heads/", &branch_name))
1026 branch_name = options.head_name;
1027
1028 } else {
1029 free(options.head_name);
1030 options.head_name = NULL;
1031 branch_name = "HEAD";
1032 }
1033 if (get_oid("HEAD", &options.orig_head))
1034 die(_("Could not resolve HEAD to a revision"));
1035 } else
1036 BUG("unexpected number of arguments left to parse");
1037
1038 if (read_index(the_repository->index) < 0)
1039 die(_("could not read index"));
1040
1041 if (options.autostash) {
1042 struct lock_file lock_file = LOCK_INIT;
1043 int fd;
1044
1045 fd = hold_locked_index(&lock_file, 0);
1046 refresh_cache(REFRESH_QUIET);
1047 if (0 <= fd)
1048 update_index_if_able(&the_index, &lock_file);
1049 rollback_lock_file(&lock_file);
1050
1051 if (has_unstaged_changes(0) || has_uncommitted_changes(0)) {
1052 const char *autostash =
1053 state_dir_path("autostash", &options);
1054 struct child_process stash = CHILD_PROCESS_INIT;
1055 struct object_id oid;
1056 struct commit *head =
1057 lookup_commit_reference(the_repository,
1058 &options.orig_head);
1059
1060 argv_array_pushl(&stash.args,
1061 "stash", "create", "autostash", NULL);
1062 stash.git_cmd = 1;
1063 stash.no_stdin = 1;
1064 strbuf_reset(&buf);
1065 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1066 die(_("Cannot autostash"));
1067 strbuf_trim_trailing_newline(&buf);
1068 if (get_oid(buf.buf, &oid))
1069 die(_("Unexpected stash response: '%s'"),
1070 buf.buf);
1071 strbuf_reset(&buf);
1072 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1073
1074 if (safe_create_leading_directories_const(autostash))
1075 die(_("Could not create directory for '%s'"),
1076 options.state_dir);
1077 write_file(autostash, "%s", buf.buf);
1078 printf(_("Created autostash: %s\n"), buf.buf);
1079 if (reset_head(&head->object.oid, "reset --hard",
1080 NULL, 0) < 0)
1081 die(_("could not reset --hard"));
1082 printf(_("HEAD is now at %s"),
1083 find_unique_abbrev(&head->object.oid,
1084 DEFAULT_ABBREV));
1085 strbuf_reset(&buf);
1086 pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1087 if (buf.len > 0)
1088 printf(" %s", buf.buf);
1089 putchar('\n');
1090
1091 if (discard_index(the_repository->index) < 0 ||
1092 read_index(the_repository->index) < 0)
1093 die(_("could not read index"));
1094 }
1095 }
1096
1097 if (require_clean_work_tree("rebase",
1098 _("Please commit or stash them."), 1, 1)) {
1099 ret = 1;
1100 goto cleanup;
1101 }
1102
1103 /*
1104 * Now we are rebasing commits upstream..orig_head (or with --root,
1105 * everything leading up to orig_head) on top of onto.
1106 */
1107
1108 /*
1109 * Check if we are already based on onto with linear history,
1110 * but this should be done only when upstream and onto are the same
1111 * and if this is not an interactive rebase.
1112 */
1113 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1114 !is_interactive(&options) && !options.restrict_revision &&
1115 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1116 int flag;
1117
1118 if (!(options.flags & REBASE_FORCE)) {
1119 /* Lazily switch to the target branch if needed... */
1120 if (options.switch_to) {
1121 struct object_id oid;
1122
1123 if (get_oid(options.switch_to, &oid) < 0) {
1124 ret = !!error(_("could not parse '%s'"),
1125 options.switch_to);
1126 goto cleanup;
1127 }
1128
1129 strbuf_reset(&buf);
1130 strbuf_addf(&buf, "rebase: checkout %s",
1131 options.switch_to);
1132 if (reset_head(&oid, "checkout",
1133 options.head_name, 0) < 0) {
1134 ret = !!error(_("could not switch to "
1135 "%s"),
1136 options.switch_to);
1137 goto cleanup;
1138 }
1139 }
1140
1141 if (!(options.flags & REBASE_NO_QUIET))
1142 ; /* be quiet */
1143 else if (!strcmp(branch_name, "HEAD") &&
1144 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1145 puts(_("HEAD is up to date."));
1146 else
1147 printf(_("Current branch %s is up to date.\n"),
1148 branch_name);
1149 ret = !!finish_rebase(&options);
1150 goto cleanup;
1151 } else if (!(options.flags & REBASE_NO_QUIET))
1152 ; /* be quiet */
1153 else if (!strcmp(branch_name, "HEAD") &&
1154 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1155 puts(_("HEAD is up to date, rebase forced."));
1156 else
1157 printf(_("Current branch %s is up to date, rebase "
1158 "forced.\n"), branch_name);
1159 }
1160
1161 /* If a hook exists, give it a chance to interrupt*/
1162 if (!ok_to_skip_pre_rebase &&
1163 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1164 argc ? argv[0] : NULL, NULL))
1165 die(_("The pre-rebase hook refused to rebase."));
1166
1167 if (options.flags & REBASE_DIFFSTAT) {
1168 struct diff_options opts;
1169
1170 if (options.flags & REBASE_VERBOSE)
1171 printf(_("Changes from %s to %s:\n"),
1172 oid_to_hex(&merge_base),
1173 oid_to_hex(&options.onto->object.oid));
1174
1175 /* We want color (if set), but no pager */
1176 diff_setup(&opts);
1177 opts.stat_width = -1; /* use full terminal width */
1178 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1179 opts.output_format |=
1180 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1181 opts.detect_rename = DIFF_DETECT_RENAME;
1182 diff_setup_done(&opts);
1183 diff_tree_oid(&merge_base, &options.onto->object.oid,
1184 "", &opts);
1185 diffcore_std(&opts);
1186 diff_flush(&opts);
1187 }
1188
1189 if (is_interactive(&options))
1190 goto run_rebase;
1191
1192 /* Detach HEAD and reset the tree */
1193 if (options.flags & REBASE_NO_QUIET)
1194 printf(_("First, rewinding head to replay your work on top of "
1195 "it...\n"));
1196
1197 strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1198 if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
1199 die(_("Could not detach HEAD"));
1200 strbuf_release(&msg);
1201
1202 strbuf_addf(&revisions, "%s..%s",
1203 options.root ? oid_to_hex(&options.onto->object.oid) :
1204 (options.restrict_revision ?
1205 oid_to_hex(&options.restrict_revision->object.oid) :
1206 oid_to_hex(&options.upstream->object.oid)),
1207 oid_to_hex(&options.orig_head));
1208
1209 options.revisions = revisions.buf;
1210
1211run_rebase:
1212 ret = !!run_specific_rebase(&options);
1213
1214cleanup:
1215 strbuf_release(&revisions);
1216 free(options.head_name);
1217 free(options.gpg_sign_opt);
1218 free(options.cmd);
1219 return ret;
1220}