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