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