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