built-in rebase: set ORIG_HEAD just once, before the rebase
[git/git.git] / builtin / rebase.c
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 "commit-reach.h"
25 #include "rerere.h"
26 #include "branch.h"
27
28 static char const * const builtin_rebase_usage[] = {
29 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
30 "[<upstream>] [<branch>]"),
31 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
32 "--root [<branch>]"),
33 N_("git rebase --continue | --abort | --skip | --edit-todo"),
34 NULL
35 };
36
37 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
38 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
39
40 enum rebase_type {
41 REBASE_UNSPECIFIED = -1,
42 REBASE_AM,
43 REBASE_MERGE,
44 REBASE_INTERACTIVE,
45 REBASE_PRESERVE_MERGES
46 };
47
48 static int use_builtin_rebase(void)
49 {
50 struct child_process cp = CHILD_PROCESS_INIT;
51 struct strbuf out = STRBUF_INIT;
52 int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
53
54 if (env != -1)
55 return env;
56
57 argv_array_pushl(&cp.args,
58 "config", "--bool", "rebase.usebuiltin", NULL);
59 cp.git_cmd = 1;
60 if (capture_command(&cp, &out, 6)) {
61 strbuf_release(&out);
62 return 1;
63 }
64
65 strbuf_trim(&out);
66 ret = !strcmp("true", out.buf);
67 strbuf_release(&out);
68 return ret;
69 }
70
71 struct rebase_options {
72 enum rebase_type type;
73 const char *state_dir;
74 struct commit *upstream;
75 const char *upstream_name;
76 const char *upstream_arg;
77 char *head_name;
78 struct object_id orig_head;
79 struct commit *onto;
80 const char *onto_name;
81 const char *revisions;
82 const char *switch_to;
83 int root;
84 struct object_id *squash_onto;
85 struct commit *restrict_revision;
86 int dont_finish_rebase;
87 enum {
88 REBASE_NO_QUIET = 1<<0,
89 REBASE_VERBOSE = 1<<1,
90 REBASE_DIFFSTAT = 1<<2,
91 REBASE_FORCE = 1<<3,
92 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
93 } flags;
94 struct argv_array git_am_opts;
95 const char *action;
96 int signoff;
97 int allow_rerere_autoupdate;
98 int keep_empty;
99 int autosquash;
100 char *gpg_sign_opt;
101 int autostash;
102 char *cmd;
103 int allow_empty_message;
104 int rebase_merges, rebase_cousins;
105 char *strategy, *strategy_opts;
106 struct strbuf git_format_patch_opt;
107 };
108
109 static int is_interactive(struct rebase_options *opts)
110 {
111 return opts->type == REBASE_INTERACTIVE ||
112 opts->type == REBASE_PRESERVE_MERGES;
113 }
114
115 static void imply_interactive(struct rebase_options *opts, const char *option)
116 {
117 switch (opts->type) {
118 case REBASE_AM:
119 die(_("%s requires an interactive rebase"), option);
120 break;
121 case REBASE_INTERACTIVE:
122 case REBASE_PRESERVE_MERGES:
123 break;
124 case REBASE_MERGE:
125 /* we silently *upgrade* --merge to --interactive if needed */
126 default:
127 opts->type = REBASE_INTERACTIVE; /* implied */
128 break;
129 }
130 }
131
132 /* Returns the filename prefixed by the state_dir */
133 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
134 {
135 static struct strbuf path = STRBUF_INIT;
136 static size_t prefix_len;
137
138 if (!prefix_len) {
139 strbuf_addf(&path, "%s/", opts->state_dir);
140 prefix_len = path.len;
141 }
142
143 strbuf_setlen(&path, prefix_len);
144 strbuf_addstr(&path, filename);
145 return path.buf;
146 }
147
148 /* Read one file, then strip line endings */
149 static int read_one(const char *path, struct strbuf *buf)
150 {
151 if (strbuf_read_file(buf, path, 0) < 0)
152 return error_errno(_("could not read '%s'"), path);
153 strbuf_trim_trailing_newline(buf);
154 return 0;
155 }
156
157 /* Initialize the rebase options from the state directory. */
158 static int read_basic_state(struct rebase_options *opts)
159 {
160 struct strbuf head_name = STRBUF_INIT;
161 struct strbuf buf = STRBUF_INIT;
162 struct object_id oid;
163
164 if (read_one(state_dir_path("head-name", opts), &head_name) ||
165 read_one(state_dir_path("onto", opts), &buf))
166 return -1;
167 opts->head_name = starts_with(head_name.buf, "refs/") ?
168 xstrdup(head_name.buf) : NULL;
169 strbuf_release(&head_name);
170 if (get_oid(buf.buf, &oid))
171 return error(_("could not get 'onto': '%s'"), buf.buf);
172 opts->onto = lookup_commit_or_die(&oid, buf.buf);
173
174 /*
175 * We always write to orig-head, but interactive rebase used to write to
176 * head. Fall back to reading from head to cover for the case that the
177 * user upgraded git with an ongoing interactive rebase.
178 */
179 strbuf_reset(&buf);
180 if (file_exists(state_dir_path("orig-head", opts))) {
181 if (read_one(state_dir_path("orig-head", opts), &buf))
182 return -1;
183 } else if (read_one(state_dir_path("head", opts), &buf))
184 return -1;
185 if (get_oid(buf.buf, &opts->orig_head))
186 return error(_("invalid orig-head: '%s'"), buf.buf);
187
188 strbuf_reset(&buf);
189 if (read_one(state_dir_path("quiet", opts), &buf))
190 return -1;
191 if (buf.len)
192 opts->flags &= ~REBASE_NO_QUIET;
193 else
194 opts->flags |= REBASE_NO_QUIET;
195
196 if (file_exists(state_dir_path("verbose", opts)))
197 opts->flags |= REBASE_VERBOSE;
198
199 if (file_exists(state_dir_path("signoff", opts))) {
200 opts->signoff = 1;
201 opts->flags |= REBASE_FORCE;
202 }
203
204 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
205 strbuf_reset(&buf);
206 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
207 &buf))
208 return -1;
209 if (!strcmp(buf.buf, "--rerere-autoupdate"))
210 opts->allow_rerere_autoupdate = 1;
211 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
212 opts->allow_rerere_autoupdate = 0;
213 else
214 warning(_("ignoring invalid allow_rerere_autoupdate: "
215 "'%s'"), buf.buf);
216 } else
217 opts->allow_rerere_autoupdate = -1;
218
219 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
220 strbuf_reset(&buf);
221 if (read_one(state_dir_path("gpg_sign_opt", opts),
222 &buf))
223 return -1;
224 free(opts->gpg_sign_opt);
225 opts->gpg_sign_opt = xstrdup(buf.buf);
226 }
227
228 if (file_exists(state_dir_path("strategy", opts))) {
229 strbuf_reset(&buf);
230 if (read_one(state_dir_path("strategy", opts), &buf))
231 return -1;
232 free(opts->strategy);
233 opts->strategy = xstrdup(buf.buf);
234 }
235
236 if (file_exists(state_dir_path("strategy_opts", opts))) {
237 strbuf_reset(&buf);
238 if (read_one(state_dir_path("strategy_opts", opts), &buf))
239 return -1;
240 free(opts->strategy_opts);
241 opts->strategy_opts = xstrdup(buf.buf);
242 }
243
244 strbuf_release(&buf);
245
246 return 0;
247 }
248
249 static int write_basic_state(struct rebase_options *opts)
250 {
251 write_file(state_dir_path("head-name", opts), "%s",
252 opts->head_name ? opts->head_name : "detached HEAD");
253 write_file(state_dir_path("onto", opts), "%s",
254 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
255 write_file(state_dir_path("orig-head", opts), "%s",
256 oid_to_hex(&opts->orig_head));
257 write_file(state_dir_path("quiet", opts), "%s",
258 opts->flags & REBASE_NO_QUIET ? "" : "t");
259 if (opts->flags & REBASE_VERBOSE)
260 write_file(state_dir_path("verbose", opts), "%s", "");
261 if (opts->strategy)
262 write_file(state_dir_path("strategy", opts), "%s",
263 opts->strategy);
264 if (opts->strategy_opts)
265 write_file(state_dir_path("strategy_opts", opts), "%s",
266 opts->strategy_opts);
267 if (opts->allow_rerere_autoupdate >= 0)
268 write_file(state_dir_path("allow_rerere_autoupdate", opts),
269 "-%s-rerere-autoupdate",
270 opts->allow_rerere_autoupdate ? "" : "-no");
271 if (opts->gpg_sign_opt)
272 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
273 opts->gpg_sign_opt);
274 if (opts->signoff)
275 write_file(state_dir_path("strategy", opts), "--signoff");
276
277 return 0;
278 }
279
280 static int apply_autostash(struct rebase_options *opts)
281 {
282 const char *path = state_dir_path("autostash", opts);
283 struct strbuf autostash = STRBUF_INIT;
284 struct child_process stash_apply = CHILD_PROCESS_INIT;
285
286 if (!file_exists(path))
287 return 0;
288
289 if (read_one(path, &autostash))
290 return error(_("Could not read '%s'"), path);
291 /* Ensure that the hash is not mistaken for a number */
292 strbuf_addstr(&autostash, "^0");
293 argv_array_pushl(&stash_apply.args,
294 "stash", "apply", autostash.buf, NULL);
295 stash_apply.git_cmd = 1;
296 stash_apply.no_stderr = stash_apply.no_stdout =
297 stash_apply.no_stdin = 1;
298 if (!run_command(&stash_apply))
299 printf(_("Applied autostash.\n"));
300 else {
301 struct argv_array args = ARGV_ARRAY_INIT;
302 int res = 0;
303
304 argv_array_pushl(&args,
305 "stash", "store", "-m", "autostash", "-q",
306 autostash.buf, NULL);
307 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
308 res = error(_("Cannot store %s"), autostash.buf);
309 argv_array_clear(&args);
310 strbuf_release(&autostash);
311 if (res)
312 return res;
313
314 fprintf(stderr,
315 _("Applying autostash resulted in conflicts.\n"
316 "Your changes are safe in the stash.\n"
317 "You can run \"git stash pop\" or \"git stash drop\" "
318 "at any time.\n"));
319 }
320
321 strbuf_release(&autostash);
322 return 0;
323 }
324
325 static int finish_rebase(struct rebase_options *opts)
326 {
327 struct strbuf dir = STRBUF_INIT;
328 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
329
330 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
331 apply_autostash(opts);
332 close_all_packs(the_repository->objects);
333 /*
334 * We ignore errors in 'gc --auto', since the
335 * user should see them.
336 */
337 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
338 strbuf_addstr(&dir, opts->state_dir);
339 remove_dir_recursively(&dir, 0);
340 strbuf_release(&dir);
341
342 return 0;
343 }
344
345 static struct commit *peel_committish(const char *name)
346 {
347 struct object *obj;
348 struct object_id oid;
349
350 if (get_oid(name, &oid))
351 return NULL;
352 obj = parse_object(the_repository, &oid);
353 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
354 }
355
356 static void add_var(struct strbuf *buf, const char *name, const char *value)
357 {
358 if (!value)
359 strbuf_addf(buf, "unset %s; ", name);
360 else {
361 strbuf_addf(buf, "%s=", name);
362 sq_quote_buf(buf, value);
363 strbuf_addstr(buf, "; ");
364 }
365 }
366
367 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
368
369 #define RESET_HEAD_DETACH (1<<0)
370 #define RESET_HEAD_HARD (1<<1)
371 #define RESET_HEAD_REFS_ONLY (1<<2)
372 #define RESET_ORIG_HEAD (1<<3)
373
374 static int reset_head(struct object_id *oid, const char *action,
375 const char *switch_to_branch, unsigned flags,
376 const char *reflog_orig_head, const char *reflog_head)
377 {
378 unsigned detach_head = flags & RESET_HEAD_DETACH;
379 unsigned reset_hard = flags & RESET_HEAD_HARD;
380 unsigned refs_only = flags & RESET_HEAD_REFS_ONLY;
381 unsigned update_orig_head = flags & RESET_ORIG_HEAD;
382 struct object_id head_oid;
383 struct tree_desc desc[2] = { { NULL }, { NULL } };
384 struct lock_file lock = LOCK_INIT;
385 struct unpack_trees_options unpack_tree_opts;
386 struct tree *tree;
387 const char *reflog_action;
388 struct strbuf msg = STRBUF_INIT;
389 size_t prefix_len;
390 struct object_id *orig = NULL, oid_orig,
391 *old_orig = NULL, oid_old_orig;
392 int ret = 0, nr = 0;
393
394 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
395 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
396
397 if (!refs_only && hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
398 ret = -1;
399 goto leave_reset_head;
400 }
401
402 if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
403 ret = error(_("could not determine HEAD revision"));
404 goto leave_reset_head;
405 }
406
407 if (!oid)
408 oid = &head_oid;
409
410 if (refs_only)
411 goto reset_head_refs;
412
413 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
414 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
415 unpack_tree_opts.head_idx = 1;
416 unpack_tree_opts.src_index = the_repository->index;
417 unpack_tree_opts.dst_index = the_repository->index;
418 unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
419 unpack_tree_opts.update = 1;
420 unpack_tree_opts.merge = 1;
421 if (!detach_head)
422 unpack_tree_opts.reset = 1;
423
424 if (read_index_unmerged(the_repository->index) < 0) {
425 ret = error(_("could not read index"));
426 goto leave_reset_head;
427 }
428
429 if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
430 ret = error(_("failed to find tree of %s"),
431 oid_to_hex(&head_oid));
432 goto leave_reset_head;
433 }
434
435 if (!fill_tree_descriptor(&desc[nr++], oid)) {
436 ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
437 goto leave_reset_head;
438 }
439
440 if (unpack_trees(nr, desc, &unpack_tree_opts)) {
441 ret = -1;
442 goto leave_reset_head;
443 }
444
445 tree = parse_tree_indirect(oid);
446 prime_cache_tree(the_repository->index, tree);
447
448 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
449 ret = error(_("could not write index"));
450 goto leave_reset_head;
451 }
452
453 reset_head_refs:
454 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
455 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
456 prefix_len = msg.len;
457
458 if (update_orig_head) {
459 if (!get_oid("ORIG_HEAD", &oid_old_orig))
460 old_orig = &oid_old_orig;
461 if (!get_oid("HEAD", &oid_orig)) {
462 orig = &oid_orig;
463 if (!reflog_orig_head) {
464 strbuf_addstr(&msg, "updating ORIG_HEAD");
465 reflog_orig_head = msg.buf;
466 }
467 update_ref(reflog_orig_head, "ORIG_HEAD", orig,
468 old_orig, 0, UPDATE_REFS_MSG_ON_ERR);
469 } else if (old_orig)
470 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
471 }
472
473 if (!reflog_head) {
474 strbuf_setlen(&msg, prefix_len);
475 strbuf_addstr(&msg, "updating HEAD");
476 reflog_head = msg.buf;
477 }
478 if (!switch_to_branch)
479 ret = update_ref(reflog_head, "HEAD", oid, orig,
480 detach_head ? REF_NO_DEREF : 0,
481 UPDATE_REFS_MSG_ON_ERR);
482 else {
483 ret = update_ref(reflog_head, switch_to_branch, oid,
484 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
485 if (!ret)
486 ret = create_symref("HEAD", switch_to_branch,
487 reflog_head);
488 }
489
490 leave_reset_head:
491 strbuf_release(&msg);
492 rollback_lock_file(&lock);
493 while (nr)
494 free((void *)desc[--nr].buffer);
495 return ret;
496 }
497
498 static int move_to_original_branch(struct rebase_options *opts)
499 {
500 struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
501 int ret;
502
503 if (!opts->head_name)
504 return 0; /* nothing to move back to */
505
506 if (!opts->onto)
507 BUG("move_to_original_branch without onto");
508
509 strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
510 opts->head_name, oid_to_hex(&opts->onto->object.oid));
511 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
512 opts->head_name);
513 ret = reset_head(NULL, "", opts->head_name, RESET_HEAD_REFS_ONLY,
514 orig_head_reflog.buf, head_reflog.buf);
515
516 strbuf_release(&orig_head_reflog);
517 strbuf_release(&head_reflog);
518 return ret;
519 }
520
521 static const char *resolvemsg =
522 N_("Resolve all conflicts manually, mark them as resolved with\n"
523 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
524 "You can instead skip this commit: run \"git rebase --skip\".\n"
525 "To abort and get back to the state before \"git rebase\", run "
526 "\"git rebase --abort\".");
527
528 static int run_am(struct rebase_options *opts)
529 {
530 struct child_process am = CHILD_PROCESS_INIT;
531 struct child_process format_patch = CHILD_PROCESS_INIT;
532 struct strbuf revisions = STRBUF_INIT;
533 int status;
534 char *rebased_patches;
535
536 am.git_cmd = 1;
537 argv_array_push(&am.args, "am");
538
539 if (opts->action && !strcmp("continue", opts->action)) {
540 argv_array_push(&am.args, "--resolved");
541 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
542 if (opts->gpg_sign_opt)
543 argv_array_push(&am.args, opts->gpg_sign_opt);
544 status = run_command(&am);
545 if (status)
546 return status;
547
548 return move_to_original_branch(opts);
549 }
550 if (opts->action && !strcmp("skip", opts->action)) {
551 argv_array_push(&am.args, "--skip");
552 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
553 status = run_command(&am);
554 if (status)
555 return status;
556
557 return move_to_original_branch(opts);
558 }
559 if (opts->action && !strcmp("show-current-patch", opts->action)) {
560 argv_array_push(&am.args, "--show-current-patch");
561 return run_command(&am);
562 }
563
564 strbuf_addf(&revisions, "%s...%s",
565 oid_to_hex(opts->root ?
566 /* this is now equivalent to !opts->upstream */
567 &opts->onto->object.oid :
568 &opts->upstream->object.oid),
569 oid_to_hex(&opts->orig_head));
570
571 rebased_patches = xstrdup(git_path("rebased-patches"));
572 format_patch.out = open(rebased_patches,
573 O_WRONLY | O_CREAT | O_TRUNC, 0666);
574 if (format_patch.out < 0) {
575 status = error_errno(_("could not open '%s' for writing"),
576 rebased_patches);
577 free(rebased_patches);
578 argv_array_clear(&am.args);
579 return status;
580 }
581
582 format_patch.git_cmd = 1;
583 argv_array_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
584 "--full-index", "--cherry-pick", "--right-only",
585 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
586 "--no-cover-letter", "--pretty=mboxrd", NULL);
587 if (opts->git_format_patch_opt.len)
588 argv_array_split(&format_patch.args,
589 opts->git_format_patch_opt.buf);
590 argv_array_push(&format_patch.args, revisions.buf);
591 if (opts->restrict_revision)
592 argv_array_pushf(&format_patch.args, "^%s",
593 oid_to_hex(&opts->restrict_revision->object.oid));
594
595 status = run_command(&format_patch);
596 if (status) {
597 unlink(rebased_patches);
598 free(rebased_patches);
599 argv_array_clear(&am.args);
600
601 reset_head(&opts->orig_head, "checkout", opts->head_name, 0,
602 "HEAD", NULL);
603 error(_("\ngit encountered an error while preparing the "
604 "patches to replay\n"
605 "these revisions:\n"
606 "\n %s\n\n"
607 "As a result, git cannot rebase them."),
608 opts->revisions);
609
610 strbuf_release(&revisions);
611 return status;
612 }
613 strbuf_release(&revisions);
614
615 am.in = open(rebased_patches, O_RDONLY);
616 if (am.in < 0) {
617 status = error_errno(_("could not open '%s' for reading"),
618 rebased_patches);
619 free(rebased_patches);
620 argv_array_clear(&am.args);
621 return status;
622 }
623
624 argv_array_pushv(&am.args, opts->git_am_opts.argv);
625 argv_array_push(&am.args, "--rebasing");
626 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
627 argv_array_push(&am.args, "--patch-format=mboxrd");
628 if (opts->allow_rerere_autoupdate > 0)
629 argv_array_push(&am.args, "--rerere-autoupdate");
630 else if (opts->allow_rerere_autoupdate == 0)
631 argv_array_push(&am.args, "--no-rerere-autoupdate");
632 if (opts->gpg_sign_opt)
633 argv_array_push(&am.args, opts->gpg_sign_opt);
634 status = run_command(&am);
635 unlink(rebased_patches);
636 free(rebased_patches);
637
638 if (!status) {
639 return move_to_original_branch(opts);
640 }
641
642 if (is_directory(opts->state_dir))
643 write_basic_state(opts);
644
645 return status;
646 }
647
648 static int run_specific_rebase(struct rebase_options *opts)
649 {
650 const char *argv[] = { NULL, NULL };
651 struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
652 int status;
653 const char *backend, *backend_func;
654
655 if (opts->type == REBASE_INTERACTIVE) {
656 /* Run builtin interactive rebase */
657 struct child_process child = CHILD_PROCESS_INIT;
658
659 argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
660 resolvemsg);
661 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
662 argv_array_push(&child.env_array, "GIT_EDITOR=:");
663 opts->autosquash = 0;
664 }
665
666 child.git_cmd = 1;
667 argv_array_push(&child.args, "rebase--interactive");
668
669 if (opts->action)
670 argv_array_pushf(&child.args, "--%s", opts->action);
671 if (opts->keep_empty)
672 argv_array_push(&child.args, "--keep-empty");
673 if (opts->rebase_merges)
674 argv_array_push(&child.args, "--rebase-merges");
675 if (opts->rebase_cousins)
676 argv_array_push(&child.args, "--rebase-cousins");
677 if (opts->autosquash)
678 argv_array_push(&child.args, "--autosquash");
679 if (opts->flags & REBASE_VERBOSE)
680 argv_array_push(&child.args, "--verbose");
681 if (opts->flags & REBASE_FORCE)
682 argv_array_push(&child.args, "--no-ff");
683 if (opts->restrict_revision)
684 argv_array_pushf(&child.args,
685 "--restrict-revision=^%s",
686 oid_to_hex(&opts->restrict_revision->object.oid));
687 if (opts->upstream)
688 argv_array_pushf(&child.args, "--upstream=%s",
689 oid_to_hex(&opts->upstream->object.oid));
690 if (opts->onto)
691 argv_array_pushf(&child.args, "--onto=%s",
692 oid_to_hex(&opts->onto->object.oid));
693 if (opts->squash_onto)
694 argv_array_pushf(&child.args, "--squash-onto=%s",
695 oid_to_hex(opts->squash_onto));
696 if (opts->onto_name)
697 argv_array_pushf(&child.args, "--onto-name=%s",
698 opts->onto_name);
699 argv_array_pushf(&child.args, "--head-name=%s",
700 opts->head_name ?
701 opts->head_name : "detached HEAD");
702 if (opts->strategy)
703 argv_array_pushf(&child.args, "--strategy=%s",
704 opts->strategy);
705 if (opts->strategy_opts)
706 argv_array_pushf(&child.args, "--strategy-opts=%s",
707 opts->strategy_opts);
708 if (opts->switch_to)
709 argv_array_pushf(&child.args, "--switch-to=%s",
710 opts->switch_to);
711 if (opts->cmd)
712 argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
713 if (opts->allow_empty_message)
714 argv_array_push(&child.args, "--allow-empty-message");
715 if (opts->allow_rerere_autoupdate > 0)
716 argv_array_push(&child.args, "--rerere-autoupdate");
717 else if (opts->allow_rerere_autoupdate == 0)
718 argv_array_push(&child.args, "--no-rerere-autoupdate");
719 if (opts->gpg_sign_opt)
720 argv_array_push(&child.args, opts->gpg_sign_opt);
721 if (opts->signoff)
722 argv_array_push(&child.args, "--signoff");
723
724 status = run_command(&child);
725 goto finished_rebase;
726 }
727
728 if (opts->type == REBASE_AM) {
729 status = run_am(opts);
730 goto finished_rebase;
731 }
732
733 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
734 add_var(&script_snippet, "state_dir", opts->state_dir);
735
736 add_var(&script_snippet, "upstream_name", opts->upstream_name);
737 add_var(&script_snippet, "upstream", opts->upstream ?
738 oid_to_hex(&opts->upstream->object.oid) : NULL);
739 add_var(&script_snippet, "head_name",
740 opts->head_name ? opts->head_name : "detached HEAD");
741 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
742 add_var(&script_snippet, "onto", opts->onto ?
743 oid_to_hex(&opts->onto->object.oid) : NULL);
744 add_var(&script_snippet, "onto_name", opts->onto_name);
745 add_var(&script_snippet, "revisions", opts->revisions);
746 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
747 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
748 add_var(&script_snippet, "GIT_QUIET",
749 opts->flags & REBASE_NO_QUIET ? "" : "t");
750 sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
751 add_var(&script_snippet, "git_am_opt", buf.buf);
752 strbuf_release(&buf);
753 add_var(&script_snippet, "verbose",
754 opts->flags & REBASE_VERBOSE ? "t" : "");
755 add_var(&script_snippet, "diffstat",
756 opts->flags & REBASE_DIFFSTAT ? "t" : "");
757 add_var(&script_snippet, "force_rebase",
758 opts->flags & REBASE_FORCE ? "t" : "");
759 if (opts->switch_to)
760 add_var(&script_snippet, "switch_to", opts->switch_to);
761 add_var(&script_snippet, "action", opts->action ? opts->action : "");
762 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
763 add_var(&script_snippet, "allow_rerere_autoupdate",
764 opts->allow_rerere_autoupdate < 0 ? "" :
765 opts->allow_rerere_autoupdate ?
766 "--rerere-autoupdate" : "--no-rerere-autoupdate");
767 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
768 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
769 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
770 add_var(&script_snippet, "cmd", opts->cmd);
771 add_var(&script_snippet, "allow_empty_message",
772 opts->allow_empty_message ? "--allow-empty-message" : "");
773 add_var(&script_snippet, "rebase_merges",
774 opts->rebase_merges ? "t" : "");
775 add_var(&script_snippet, "rebase_cousins",
776 opts->rebase_cousins ? "t" : "");
777 add_var(&script_snippet, "strategy", opts->strategy);
778 add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
779 add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
780 add_var(&script_snippet, "squash_onto",
781 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
782 add_var(&script_snippet, "git_format_patch_opt",
783 opts->git_format_patch_opt.buf);
784
785 if (is_interactive(opts) &&
786 !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
787 strbuf_addstr(&script_snippet,
788 "GIT_EDITOR=:; export GIT_EDITOR; ");
789 opts->autosquash = 0;
790 }
791
792 switch (opts->type) {
793 case REBASE_AM:
794 backend = "git-rebase--am";
795 backend_func = "git_rebase__am";
796 break;
797 case REBASE_MERGE:
798 backend = "git-rebase--merge";
799 backend_func = "git_rebase__merge";
800 break;
801 case REBASE_PRESERVE_MERGES:
802 backend = "git-rebase--preserve-merges";
803 backend_func = "git_rebase__preserve_merges";
804 break;
805 default:
806 BUG("Unhandled rebase type %d", opts->type);
807 break;
808 }
809
810 strbuf_addf(&script_snippet,
811 ". git-sh-setup && . git-rebase--common &&"
812 " . %s && %s", backend, backend_func);
813 argv[0] = script_snippet.buf;
814
815 status = run_command_v_opt(argv, RUN_USING_SHELL);
816 finished_rebase:
817 if (opts->dont_finish_rebase)
818 ; /* do nothing */
819 else if (opts->type == REBASE_INTERACTIVE)
820 ; /* interactive rebase cleans up after itself */
821 else if (status == 0) {
822 if (!file_exists(state_dir_path("stopped-sha", opts)))
823 finish_rebase(opts);
824 } else if (status == 2) {
825 struct strbuf dir = STRBUF_INIT;
826
827 apply_autostash(opts);
828 strbuf_addstr(&dir, opts->state_dir);
829 remove_dir_recursively(&dir, 0);
830 strbuf_release(&dir);
831 die("Nothing to do");
832 }
833
834 strbuf_release(&script_snippet);
835
836 return status ? -1 : 0;
837 }
838
839 static int rebase_config(const char *var, const char *value, void *data)
840 {
841 struct rebase_options *opts = data;
842
843 if (!strcmp(var, "rebase.stat")) {
844 if (git_config_bool(var, value))
845 opts->flags |= REBASE_DIFFSTAT;
846 else
847 opts->flags &= !REBASE_DIFFSTAT;
848 return 0;
849 }
850
851 if (!strcmp(var, "rebase.autosquash")) {
852 opts->autosquash = git_config_bool(var, value);
853 return 0;
854 }
855
856 if (!strcmp(var, "commit.gpgsign")) {
857 free(opts->gpg_sign_opt);
858 opts->gpg_sign_opt = git_config_bool(var, value) ?
859 xstrdup("-S") : NULL;
860 return 0;
861 }
862
863 if (!strcmp(var, "rebase.autostash")) {
864 opts->autostash = git_config_bool(var, value);
865 return 0;
866 }
867
868 return git_default_config(var, value, data);
869 }
870
871 /*
872 * Determines whether the commits in from..to are linear, i.e. contain
873 * no merge commits. This function *expects* `from` to be an ancestor of
874 * `to`.
875 */
876 static int is_linear_history(struct commit *from, struct commit *to)
877 {
878 while (to && to != from) {
879 parse_commit(to);
880 if (!to->parents)
881 return 1;
882 if (to->parents->next)
883 return 0;
884 to = to->parents->item;
885 }
886 return 1;
887 }
888
889 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
890 struct object_id *merge_base)
891 {
892 struct commit *head = lookup_commit(the_repository, head_oid);
893 struct commit_list *merge_bases;
894 int res;
895
896 if (!head)
897 return 0;
898
899 merge_bases = get_merge_bases(onto, head);
900 if (merge_bases && !merge_bases->next) {
901 oidcpy(merge_base, &merge_bases->item->object.oid);
902 res = oideq(merge_base, &onto->object.oid);
903 } else {
904 oidcpy(merge_base, &null_oid);
905 res = 0;
906 }
907 free_commit_list(merge_bases);
908 return res && is_linear_history(onto, head);
909 }
910
911 /* -i followed by -m is still -i */
912 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
913 {
914 struct rebase_options *opts = opt->value;
915
916 BUG_ON_OPT_NEG(unset);
917 BUG_ON_OPT_ARG(arg);
918
919 if (!is_interactive(opts))
920 opts->type = REBASE_MERGE;
921
922 return 0;
923 }
924
925 /* -i followed by -p is still explicitly interactive, but -p alone is not */
926 static int parse_opt_interactive(const struct option *opt, const char *arg,
927 int unset)
928 {
929 struct rebase_options *opts = opt->value;
930
931 BUG_ON_OPT_NEG(unset);
932 BUG_ON_OPT_ARG(arg);
933
934 opts->type = REBASE_INTERACTIVE;
935 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
936
937 return 0;
938 }
939
940 static void NORETURN error_on_missing_default_upstream(void)
941 {
942 struct branch *current_branch = branch_get(NULL);
943
944 printf(_("%s\n"
945 "Please specify which branch you want to rebase against.\n"
946 "See git-rebase(1) for details.\n"
947 "\n"
948 " git rebase '<branch>'\n"
949 "\n"),
950 current_branch ? _("There is no tracking information for "
951 "the current branch.") :
952 _("You are not currently on a branch."));
953
954 if (current_branch) {
955 const char *remote = current_branch->remote_name;
956
957 if (!remote)
958 remote = _("<remote>");
959
960 printf(_("If you wish to set tracking information for this "
961 "branch you can do so with:\n"
962 "\n"
963 " git branch --set-upstream-to=%s/<branch> %s\n"
964 "\n"),
965 remote, current_branch->name);
966 }
967 exit(1);
968 }
969
970 static void set_reflog_action(struct rebase_options *options)
971 {
972 const char *env;
973 struct strbuf buf = STRBUF_INIT;
974
975 if (!is_interactive(options))
976 return;
977
978 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
979 if (env && strcmp("rebase", env))
980 return; /* only override it if it is "rebase" */
981
982 strbuf_addf(&buf, "rebase -i (%s)", options->action);
983 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
984 strbuf_release(&buf);
985 }
986
987 int cmd_rebase(int argc, const char **argv, const char *prefix)
988 {
989 struct rebase_options options = {
990 .type = REBASE_UNSPECIFIED,
991 .flags = REBASE_NO_QUIET,
992 .git_am_opts = ARGV_ARRAY_INIT,
993 .allow_rerere_autoupdate = -1,
994 .allow_empty_message = 1,
995 .git_format_patch_opt = STRBUF_INIT,
996 };
997 const char *branch_name;
998 int ret, flags, total_argc, in_progress = 0;
999 int ok_to_skip_pre_rebase = 0;
1000 struct strbuf msg = STRBUF_INIT;
1001 struct strbuf revisions = STRBUF_INIT;
1002 struct strbuf buf = STRBUF_INIT;
1003 struct object_id merge_base;
1004 enum {
1005 NO_ACTION,
1006 ACTION_CONTINUE,
1007 ACTION_SKIP,
1008 ACTION_ABORT,
1009 ACTION_QUIT,
1010 ACTION_EDIT_TODO,
1011 ACTION_SHOW_CURRENT_PATCH,
1012 } action = NO_ACTION;
1013 const char *gpg_sign = NULL;
1014 struct string_list exec = STRING_LIST_INIT_NODUP;
1015 const char *rebase_merges = NULL;
1016 int fork_point = -1;
1017 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
1018 struct object_id squash_onto;
1019 char *squash_onto_name = NULL;
1020 struct option builtin_rebase_options[] = {
1021 OPT_STRING(0, "onto", &options.onto_name,
1022 N_("revision"),
1023 N_("rebase onto given branch instead of upstream")),
1024 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1025 N_("allow pre-rebase hook to run")),
1026 OPT_NEGBIT('q', "quiet", &options.flags,
1027 N_("be quiet. implies --no-stat"),
1028 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
1029 OPT_BIT('v', "verbose", &options.flags,
1030 N_("display a diffstat of what changed upstream"),
1031 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1032 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1033 N_("do not show diffstat of what changed upstream"),
1034 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
1035 OPT_BOOL(0, "signoff", &options.signoff,
1036 N_("add a Signed-off-by: line to each commit")),
1037 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
1038 NULL, N_("passed to 'git am'"),
1039 PARSE_OPT_NOARG),
1040 OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
1041 &options.git_am_opts, NULL,
1042 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1043 OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
1044 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1045 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1046 N_("passed to 'git apply'"), 0),
1047 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1048 N_("action"), N_("passed to 'git apply'"), 0),
1049 OPT_BIT('f', "force-rebase", &options.flags,
1050 N_("cherry-pick all commits, even if unchanged"),
1051 REBASE_FORCE),
1052 OPT_BIT(0, "no-ff", &options.flags,
1053 N_("cherry-pick all commits, even if unchanged"),
1054 REBASE_FORCE),
1055 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1056 ACTION_CONTINUE),
1057 OPT_CMDMODE(0, "skip", &action,
1058 N_("skip current patch and continue"), ACTION_SKIP),
1059 OPT_CMDMODE(0, "abort", &action,
1060 N_("abort and check out the original branch"),
1061 ACTION_ABORT),
1062 OPT_CMDMODE(0, "quit", &action,
1063 N_("abort but keep HEAD where it is"), ACTION_QUIT),
1064 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1065 "during an interactive rebase"), ACTION_EDIT_TODO),
1066 OPT_CMDMODE(0, "show-current-patch", &action,
1067 N_("show the patch file being applied or merged"),
1068 ACTION_SHOW_CURRENT_PATCH),
1069 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
1070 N_("use merging strategies to rebase"),
1071 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1072 parse_opt_merge },
1073 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
1074 N_("let the user edit the list of commits to rebase"),
1075 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1076 parse_opt_interactive },
1077 OPT_SET_INT('p', "preserve-merges", &options.type,
1078 N_("try to recreate merges instead of ignoring "
1079 "them"), REBASE_PRESERVE_MERGES),
1080 OPT_BOOL(0, "rerere-autoupdate",
1081 &options.allow_rerere_autoupdate,
1082 N_("allow rerere to update index with resolved "
1083 "conflict")),
1084 OPT_BOOL('k', "keep-empty", &options.keep_empty,
1085 N_("preserve empty commits during rebase")),
1086 OPT_BOOL(0, "autosquash", &options.autosquash,
1087 N_("move commits that begin with "
1088 "squash!/fixup! under -i")),
1089 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1090 N_("GPG-sign commits"),
1091 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1092 OPT_BOOL(0, "autostash", &options.autostash,
1093 N_("automatically stash/stash pop before and after")),
1094 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1095 N_("add exec lines after each commit of the "
1096 "editable list")),
1097 OPT_BOOL(0, "allow-empty-message",
1098 &options.allow_empty_message,
1099 N_("allow rebasing commits with empty messages")),
1100 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1101 N_("mode"),
1102 N_("try to rebase merges instead of skipping them"),
1103 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
1104 OPT_BOOL(0, "fork-point", &fork_point,
1105 N_("use 'merge-base --fork-point' to refine upstream")),
1106 OPT_STRING('s', "strategy", &options.strategy,
1107 N_("strategy"), N_("use the given merge strategy")),
1108 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1109 N_("option"),
1110 N_("pass the argument through to the merge "
1111 "strategy")),
1112 OPT_BOOL(0, "root", &options.root,
1113 N_("rebase all reachable commits up to the root(s)")),
1114 OPT_END(),
1115 };
1116 int i;
1117
1118 /*
1119 * NEEDSWORK: Once the builtin rebase has been tested enough
1120 * and git-legacy-rebase.sh is retired to contrib/, this preamble
1121 * can be removed.
1122 */
1123
1124 if (!use_builtin_rebase()) {
1125 const char *path = mkpath("%s/git-legacy-rebase",
1126 git_exec_path());
1127
1128 if (sane_execvp(path, (char **)argv) < 0)
1129 die_errno(_("could not exec %s"), path);
1130 else
1131 BUG("sane_execvp() returned???");
1132 }
1133
1134 if (argc == 2 && !strcmp(argv[1], "-h"))
1135 usage_with_options(builtin_rebase_usage,
1136 builtin_rebase_options);
1137
1138 prefix = setup_git_directory();
1139 trace_repo_setup(prefix);
1140 setup_work_tree();
1141
1142 git_config(rebase_config, &options);
1143
1144 strbuf_reset(&buf);
1145 strbuf_addf(&buf, "%s/applying", apply_dir());
1146 if(file_exists(buf.buf))
1147 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1148
1149 if (is_directory(apply_dir())) {
1150 options.type = REBASE_AM;
1151 options.state_dir = apply_dir();
1152 } else if (is_directory(merge_dir())) {
1153 strbuf_reset(&buf);
1154 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1155 if (is_directory(buf.buf)) {
1156 options.type = REBASE_PRESERVE_MERGES;
1157 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1158 } else {
1159 strbuf_reset(&buf);
1160 strbuf_addf(&buf, "%s/interactive", merge_dir());
1161 if(file_exists(buf.buf)) {
1162 options.type = REBASE_INTERACTIVE;
1163 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1164 } else
1165 options.type = REBASE_MERGE;
1166 }
1167 options.state_dir = merge_dir();
1168 }
1169
1170 if (options.type != REBASE_UNSPECIFIED)
1171 in_progress = 1;
1172
1173 total_argc = argc;
1174 argc = parse_options(argc, argv, prefix,
1175 builtin_rebase_options,
1176 builtin_rebase_usage, 0);
1177
1178 if (action != NO_ACTION && total_argc != 2) {
1179 usage_with_options(builtin_rebase_usage,
1180 builtin_rebase_options);
1181 }
1182
1183 if (argc > 2)
1184 usage_with_options(builtin_rebase_usage,
1185 builtin_rebase_options);
1186
1187 if (action != NO_ACTION && !in_progress)
1188 die(_("No rebase in progress?"));
1189 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
1190
1191 if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1192 die(_("The --edit-todo action can only be used during "
1193 "interactive rebase."));
1194
1195 switch (action) {
1196 case ACTION_CONTINUE: {
1197 struct object_id head;
1198 struct lock_file lock_file = LOCK_INIT;
1199 int fd;
1200
1201 options.action = "continue";
1202 set_reflog_action(&options);
1203
1204 /* Sanity check */
1205 if (get_oid("HEAD", &head))
1206 die(_("Cannot read HEAD"));
1207
1208 fd = hold_locked_index(&lock_file, 0);
1209 if (read_index(the_repository->index) < 0)
1210 die(_("could not read index"));
1211 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1212 NULL);
1213 if (0 <= fd)
1214 update_index_if_able(the_repository->index,
1215 &lock_file);
1216 rollback_lock_file(&lock_file);
1217
1218 if (has_unstaged_changes(1)) {
1219 puts(_("You must edit all merge conflicts and then\n"
1220 "mark them as resolved using git add"));
1221 exit(1);
1222 }
1223 if (read_basic_state(&options))
1224 exit(1);
1225 goto run_rebase;
1226 }
1227 case ACTION_SKIP: {
1228 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1229
1230 options.action = "skip";
1231 set_reflog_action(&options);
1232
1233 rerere_clear(&merge_rr);
1234 string_list_clear(&merge_rr, 1);
1235
1236 if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1237 NULL, NULL) < 0)
1238 die(_("could not discard worktree changes"));
1239 remove_branch_state();
1240 if (read_basic_state(&options))
1241 exit(1);
1242 goto run_rebase;
1243 }
1244 case ACTION_ABORT: {
1245 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1246 options.action = "abort";
1247 set_reflog_action(&options);
1248
1249 rerere_clear(&merge_rr);
1250 string_list_clear(&merge_rr, 1);
1251
1252 if (read_basic_state(&options))
1253 exit(1);
1254 if (reset_head(&options.orig_head, "reset",
1255 options.head_name, RESET_HEAD_HARD,
1256 NULL, NULL) < 0)
1257 die(_("could not move back to %s"),
1258 oid_to_hex(&options.orig_head));
1259 remove_branch_state();
1260 ret = finish_rebase(&options);
1261 goto cleanup;
1262 }
1263 case ACTION_QUIT: {
1264 strbuf_reset(&buf);
1265 strbuf_addstr(&buf, options.state_dir);
1266 ret = !!remove_dir_recursively(&buf, 0);
1267 if (ret)
1268 die(_("could not remove '%s'"), options.state_dir);
1269 goto cleanup;
1270 }
1271 case ACTION_EDIT_TODO:
1272 options.action = "edit-todo";
1273 options.dont_finish_rebase = 1;
1274 goto run_rebase;
1275 case ACTION_SHOW_CURRENT_PATCH:
1276 options.action = "show-current-patch";
1277 options.dont_finish_rebase = 1;
1278 goto run_rebase;
1279 case NO_ACTION:
1280 break;
1281 default:
1282 BUG("action: %d", action);
1283 }
1284
1285 /* Make sure no rebase is in progress */
1286 if (in_progress) {
1287 const char *last_slash = strrchr(options.state_dir, '/');
1288 const char *state_dir_base =
1289 last_slash ? last_slash + 1 : options.state_dir;
1290 const char *cmd_live_rebase =
1291 "git rebase (--continue | --abort | --skip)";
1292 strbuf_reset(&buf);
1293 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1294 die(_("It seems that there is already a %s directory, and\n"
1295 "I wonder if you are in the middle of another rebase. "
1296 "If that is the\n"
1297 "case, please try\n\t%s\n"
1298 "If that is not the case, please\n\t%s\n"
1299 "and run me again. I am stopping in case you still "
1300 "have something\n"
1301 "valuable there.\n"),
1302 state_dir_base, cmd_live_rebase, buf.buf);
1303 }
1304
1305 for (i = 0; i < options.git_am_opts.argc; i++) {
1306 const char *option = options.git_am_opts.argv[i], *p;
1307 if (!strcmp(option, "--committer-date-is-author-date") ||
1308 !strcmp(option, "--ignore-date") ||
1309 !strcmp(option, "--whitespace=fix") ||
1310 !strcmp(option, "--whitespace=strip"))
1311 options.flags |= REBASE_FORCE;
1312 else if (skip_prefix(option, "-C", &p)) {
1313 while (*p)
1314 if (!isdigit(*(p++)))
1315 die(_("switch `C' expects a "
1316 "numerical value"));
1317 } else if (skip_prefix(option, "--whitespace=", &p)) {
1318 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1319 strcmp(p, "error") && strcmp(p, "error-all"))
1320 die("Invalid whitespace option: '%s'", p);
1321 }
1322 }
1323
1324 if (!(options.flags & REBASE_NO_QUIET))
1325 argv_array_push(&options.git_am_opts, "-q");
1326
1327 if (options.keep_empty)
1328 imply_interactive(&options, "--keep-empty");
1329
1330 if (gpg_sign) {
1331 free(options.gpg_sign_opt);
1332 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1333 }
1334
1335 if (exec.nr) {
1336 int i;
1337
1338 imply_interactive(&options, "--exec");
1339
1340 strbuf_reset(&buf);
1341 for (i = 0; i < exec.nr; i++)
1342 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1343 options.cmd = xstrdup(buf.buf);
1344 }
1345
1346 if (rebase_merges) {
1347 if (!*rebase_merges)
1348 ; /* default mode; do nothing */
1349 else if (!strcmp("rebase-cousins", rebase_merges))
1350 options.rebase_cousins = 1;
1351 else if (strcmp("no-rebase-cousins", rebase_merges))
1352 die(_("Unknown mode: %s"), rebase_merges);
1353 options.rebase_merges = 1;
1354 imply_interactive(&options, "--rebase-merges");
1355 }
1356
1357 if (strategy_options.nr) {
1358 int i;
1359
1360 if (!options.strategy)
1361 options.strategy = "recursive";
1362
1363 strbuf_reset(&buf);
1364 for (i = 0; i < strategy_options.nr; i++)
1365 strbuf_addf(&buf, " --%s",
1366 strategy_options.items[i].string);
1367 options.strategy_opts = xstrdup(buf.buf);
1368 }
1369
1370 if (options.strategy) {
1371 options.strategy = xstrdup(options.strategy);
1372 switch (options.type) {
1373 case REBASE_AM:
1374 die(_("--strategy requires --merge or --interactive"));
1375 case REBASE_MERGE:
1376 case REBASE_INTERACTIVE:
1377 case REBASE_PRESERVE_MERGES:
1378 /* compatible */
1379 break;
1380 case REBASE_UNSPECIFIED:
1381 options.type = REBASE_MERGE;
1382 break;
1383 default:
1384 BUG("unhandled rebase type (%d)", options.type);
1385 }
1386 }
1387
1388 if (options.root && !options.onto_name)
1389 imply_interactive(&options, "--root without --onto");
1390
1391 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1392 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1393
1394 switch (options.type) {
1395 case REBASE_MERGE:
1396 case REBASE_INTERACTIVE:
1397 case REBASE_PRESERVE_MERGES:
1398 options.state_dir = merge_dir();
1399 break;
1400 case REBASE_AM:
1401 options.state_dir = apply_dir();
1402 break;
1403 default:
1404 /* the default rebase backend is `--am` */
1405 options.type = REBASE_AM;
1406 options.state_dir = apply_dir();
1407 break;
1408 }
1409
1410 if (options.git_am_opts.argc) {
1411 /* all am options except -q are compatible only with --am */
1412 for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1413 if (strcmp(options.git_am_opts.argv[i], "-q"))
1414 break;
1415
1416 if (is_interactive(&options) && i >= 0)
1417 die(_("error: cannot combine interactive options "
1418 "(--interactive, --exec, --rebase-merges, "
1419 "--preserve-merges, --keep-empty, --root + "
1420 "--onto) with am options (%s)"), buf.buf);
1421 if (options.type == REBASE_MERGE && i >= 0)
1422 die(_("error: cannot combine merge options (--merge, "
1423 "--strategy, --strategy-option) with am options "
1424 "(%s)"), buf.buf);
1425 }
1426
1427 if (options.signoff) {
1428 if (options.type == REBASE_PRESERVE_MERGES)
1429 die("cannot combine '--signoff' with "
1430 "'--preserve-merges'");
1431 argv_array_push(&options.git_am_opts, "--signoff");
1432 options.flags |= REBASE_FORCE;
1433 }
1434
1435 if (options.type == REBASE_PRESERVE_MERGES)
1436 /*
1437 * Note: incompatibility with --signoff handled in signoff block above
1438 * Note: incompatibility with --interactive is just a strong warning;
1439 * git-rebase.txt caveats with "unless you know what you are doing"
1440 */
1441 if (options.rebase_merges)
1442 die(_("error: cannot combine '--preserve-merges' with "
1443 "'--rebase-merges'"));
1444
1445 if (options.rebase_merges) {
1446 if (strategy_options.nr)
1447 die(_("error: cannot combine '--rebase-merges' with "
1448 "'--strategy-option'"));
1449 if (options.strategy)
1450 die(_("error: cannot combine '--rebase-merges' with "
1451 "'--strategy'"));
1452 }
1453
1454 if (!options.root) {
1455 if (argc < 1) {
1456 struct branch *branch;
1457
1458 branch = branch_get(NULL);
1459 options.upstream_name = branch_get_upstream(branch,
1460 NULL);
1461 if (!options.upstream_name)
1462 error_on_missing_default_upstream();
1463 if (fork_point < 0)
1464 fork_point = 1;
1465 } else {
1466 options.upstream_name = argv[0];
1467 argc--;
1468 argv++;
1469 if (!strcmp(options.upstream_name, "-"))
1470 options.upstream_name = "@{-1}";
1471 }
1472 options.upstream = peel_committish(options.upstream_name);
1473 if (!options.upstream)
1474 die(_("invalid upstream '%s'"), options.upstream_name);
1475 options.upstream_arg = options.upstream_name;
1476 } else {
1477 if (!options.onto_name) {
1478 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1479 &squash_onto, NULL, NULL) < 0)
1480 die(_("Could not create new root commit"));
1481 options.squash_onto = &squash_onto;
1482 options.onto_name = squash_onto_name =
1483 xstrdup(oid_to_hex(&squash_onto));
1484 }
1485 options.upstream_name = NULL;
1486 options.upstream = NULL;
1487 if (argc > 1)
1488 usage_with_options(builtin_rebase_usage,
1489 builtin_rebase_options);
1490 options.upstream_arg = "--root";
1491 }
1492
1493 /* Make sure the branch to rebase onto is valid. */
1494 if (!options.onto_name)
1495 options.onto_name = options.upstream_name;
1496 if (strstr(options.onto_name, "...")) {
1497 if (get_oid_mb(options.onto_name, &merge_base) < 0)
1498 die(_("'%s': need exactly one merge base"),
1499 options.onto_name);
1500 options.onto = lookup_commit_or_die(&merge_base,
1501 options.onto_name);
1502 } else {
1503 options.onto = peel_committish(options.onto_name);
1504 if (!options.onto)
1505 die(_("Does not point to a valid commit '%s'"),
1506 options.onto_name);
1507 }
1508
1509 /*
1510 * If the branch to rebase is given, that is the branch we will rebase
1511 * branch_name -- branch/commit being rebased, or
1512 * HEAD (already detached)
1513 * orig_head -- commit object name of tip of the branch before rebasing
1514 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1515 */
1516 if (argc == 1) {
1517 /* Is it "rebase other branchname" or "rebase other commit"? */
1518 branch_name = argv[0];
1519 options.switch_to = argv[0];
1520
1521 /* Is it a local branch? */
1522 strbuf_reset(&buf);
1523 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1524 if (!read_ref(buf.buf, &options.orig_head))
1525 options.head_name = xstrdup(buf.buf);
1526 /* If not is it a valid ref (branch or commit)? */
1527 else if (!get_oid(branch_name, &options.orig_head))
1528 options.head_name = NULL;
1529 else
1530 die(_("fatal: no such branch/commit '%s'"),
1531 branch_name);
1532 } else if (argc == 0) {
1533 /* Do not need to switch branches, we are already on it. */
1534 options.head_name =
1535 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1536 &flags));
1537 if (!options.head_name)
1538 die(_("No such ref: %s"), "HEAD");
1539 if (flags & REF_ISSYMREF) {
1540 if (!skip_prefix(options.head_name,
1541 "refs/heads/", &branch_name))
1542 branch_name = options.head_name;
1543
1544 } else {
1545 free(options.head_name);
1546 options.head_name = NULL;
1547 branch_name = "HEAD";
1548 }
1549 if (get_oid("HEAD", &options.orig_head))
1550 die(_("Could not resolve HEAD to a revision"));
1551 } else
1552 BUG("unexpected number of arguments left to parse");
1553
1554 if (fork_point > 0) {
1555 struct commit *head =
1556 lookup_commit_reference(the_repository,
1557 &options.orig_head);
1558 options.restrict_revision =
1559 get_fork_point(options.upstream_name, head);
1560 }
1561
1562 if (read_index(the_repository->index) < 0)
1563 die(_("could not read index"));
1564
1565 if (options.autostash) {
1566 struct lock_file lock_file = LOCK_INIT;
1567 int fd;
1568
1569 fd = hold_locked_index(&lock_file, 0);
1570 refresh_cache(REFRESH_QUIET);
1571 if (0 <= fd)
1572 update_index_if_able(&the_index, &lock_file);
1573 rollback_lock_file(&lock_file);
1574
1575 if (has_unstaged_changes(1) || has_uncommitted_changes(1)) {
1576 const char *autostash =
1577 state_dir_path("autostash", &options);
1578 struct child_process stash = CHILD_PROCESS_INIT;
1579 struct object_id oid;
1580 struct commit *head =
1581 lookup_commit_reference(the_repository,
1582 &options.orig_head);
1583
1584 argv_array_pushl(&stash.args,
1585 "stash", "create", "autostash", NULL);
1586 stash.git_cmd = 1;
1587 stash.no_stdin = 1;
1588 strbuf_reset(&buf);
1589 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1590 die(_("Cannot autostash"));
1591 strbuf_trim_trailing_newline(&buf);
1592 if (get_oid(buf.buf, &oid))
1593 die(_("Unexpected stash response: '%s'"),
1594 buf.buf);
1595 strbuf_reset(&buf);
1596 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1597
1598 if (safe_create_leading_directories_const(autostash))
1599 die(_("Could not create directory for '%s'"),
1600 options.state_dir);
1601 write_file(autostash, "%s", oid_to_hex(&oid));
1602 printf(_("Created autostash: %s\n"), buf.buf);
1603 if (reset_head(&head->object.oid, "reset --hard",
1604 NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
1605 die(_("could not reset --hard"));
1606 printf(_("HEAD is now at %s"),
1607 find_unique_abbrev(&head->object.oid,
1608 DEFAULT_ABBREV));
1609 strbuf_reset(&buf);
1610 pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1611 if (buf.len > 0)
1612 printf(" %s", buf.buf);
1613 putchar('\n');
1614
1615 if (discard_index(the_repository->index) < 0 ||
1616 read_index(the_repository->index) < 0)
1617 die(_("could not read index"));
1618 }
1619 }
1620
1621 if (require_clean_work_tree("rebase",
1622 _("Please commit or stash them."), 1, 1)) {
1623 ret = 1;
1624 goto cleanup;
1625 }
1626
1627 /*
1628 * Now we are rebasing commits upstream..orig_head (or with --root,
1629 * everything leading up to orig_head) on top of onto.
1630 */
1631
1632 /*
1633 * Check if we are already based on onto with linear history,
1634 * but this should be done only when upstream and onto are the same
1635 * and if this is not an interactive rebase.
1636 */
1637 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1638 !is_interactive(&options) && !options.restrict_revision &&
1639 options.upstream &&
1640 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1641 int flag;
1642
1643 if (!(options.flags & REBASE_FORCE)) {
1644 /* Lazily switch to the target branch if needed... */
1645 if (options.switch_to) {
1646 struct object_id oid;
1647
1648 if (get_oid(options.switch_to, &oid) < 0) {
1649 ret = !!error(_("could not parse '%s'"),
1650 options.switch_to);
1651 goto cleanup;
1652 }
1653
1654 strbuf_reset(&buf);
1655 strbuf_addf(&buf, "%s: checkout %s",
1656 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
1657 options.switch_to);
1658 if (reset_head(&oid, "checkout",
1659 options.head_name, 0,
1660 NULL, buf.buf) < 0) {
1661 ret = !!error(_("could not switch to "
1662 "%s"),
1663 options.switch_to);
1664 goto cleanup;
1665 }
1666 }
1667
1668 if (!(options.flags & REBASE_NO_QUIET))
1669 ; /* be quiet */
1670 else if (!strcmp(branch_name, "HEAD") &&
1671 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1672 puts(_("HEAD is up to date."));
1673 else
1674 printf(_("Current branch %s is up to date.\n"),
1675 branch_name);
1676 ret = !!finish_rebase(&options);
1677 goto cleanup;
1678 } else if (!(options.flags & REBASE_NO_QUIET))
1679 ; /* be quiet */
1680 else if (!strcmp(branch_name, "HEAD") &&
1681 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1682 puts(_("HEAD is up to date, rebase forced."));
1683 else
1684 printf(_("Current branch %s is up to date, rebase "
1685 "forced.\n"), branch_name);
1686 }
1687
1688 /* If a hook exists, give it a chance to interrupt*/
1689 if (!ok_to_skip_pre_rebase &&
1690 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1691 argc ? argv[0] : NULL, NULL))
1692 die(_("The pre-rebase hook refused to rebase."));
1693
1694 if (options.flags & REBASE_DIFFSTAT) {
1695 struct diff_options opts;
1696
1697 if (options.flags & REBASE_VERBOSE) {
1698 if (is_null_oid(&merge_base))
1699 printf(_("Changes to %s:\n"),
1700 oid_to_hex(&options.onto->object.oid));
1701 else
1702 printf(_("Changes from %s to %s:\n"),
1703 oid_to_hex(&merge_base),
1704 oid_to_hex(&options.onto->object.oid));
1705 }
1706
1707 /* We want color (if set), but no pager */
1708 diff_setup(&opts);
1709 opts.stat_width = -1; /* use full terminal width */
1710 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1711 opts.output_format |=
1712 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1713 opts.detect_rename = DIFF_DETECT_RENAME;
1714 diff_setup_done(&opts);
1715 diff_tree_oid(is_null_oid(&merge_base) ?
1716 the_hash_algo->empty_tree : &merge_base,
1717 &options.onto->object.oid, "", &opts);
1718 diffcore_std(&opts);
1719 diff_flush(&opts);
1720 }
1721
1722 if (is_interactive(&options))
1723 goto run_rebase;
1724
1725 /* Detach HEAD and reset the tree */
1726 if (options.flags & REBASE_NO_QUIET)
1727 printf(_("First, rewinding head to replay your work on top of "
1728 "it...\n"));
1729
1730 strbuf_addf(&msg, "%s: checkout %s",
1731 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
1732 if (reset_head(&options.onto->object.oid, "checkout", NULL,
1733 RESET_HEAD_DETACH | RESET_ORIG_HEAD, NULL, msg.buf))
1734 die(_("Could not detach HEAD"));
1735 strbuf_release(&msg);
1736
1737 /*
1738 * If the onto is a proper descendant of the tip of the branch, then
1739 * we just fast-forwarded.
1740 */
1741 strbuf_reset(&msg);
1742 if (!oidcmp(&merge_base, &options.orig_head)) {
1743 printf(_("Fast-forwarded %s to %s.\n"),
1744 branch_name, options.onto_name);
1745 strbuf_addf(&msg, "rebase finished: %s onto %s",
1746 options.head_name ? options.head_name : "detached HEAD",
1747 oid_to_hex(&options.onto->object.oid));
1748 reset_head(NULL, "Fast-forwarded", options.head_name,
1749 RESET_HEAD_REFS_ONLY, "HEAD", msg.buf);
1750 strbuf_release(&msg);
1751 ret = !!finish_rebase(&options);
1752 goto cleanup;
1753 }
1754
1755 strbuf_addf(&revisions, "%s..%s",
1756 options.root ? oid_to_hex(&options.onto->object.oid) :
1757 (options.restrict_revision ?
1758 oid_to_hex(&options.restrict_revision->object.oid) :
1759 oid_to_hex(&options.upstream->object.oid)),
1760 oid_to_hex(&options.orig_head));
1761
1762 options.revisions = revisions.buf;
1763
1764 run_rebase:
1765 ret = !!run_specific_rebase(&options);
1766
1767 cleanup:
1768 strbuf_release(&revisions);
1769 free(options.head_name);
1770 free(options.gpg_sign_opt);
1771 free(options.cmd);
1772 free(squash_onto_name);
1773 return ret;
1774 }