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