]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/rebase.c
rebase -i: use struct rebase_options to parse args
[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"
0609b741
PW
28#include "sequencer.h"
29#include "rebase-interactive.h"
f28d40d3
PK
30
31static char const * const builtin_rebase_usage[] = {
32 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
33 "[<upstream>] [<branch>]"),
34 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
35 "--root [<branch>]"),
36 N_("git rebase --continue | --abort | --skip | --edit-todo"),
37 NULL
38};
ac7f467f 39
0609b741
PW
40static GIT_PATH_FUNC(path_squash_onto, "rebase-merge/squash-onto")
41static GIT_PATH_FUNC(path_interactive, "rebase-merge/interactive")
ac7f467f
PK
42static GIT_PATH_FUNC(apply_dir, "rebase-apply")
43static GIT_PATH_FUNC(merge_dir, "rebase-merge")
44
45enum rebase_type {
46 REBASE_UNSPECIFIED = -1,
47 REBASE_AM,
48 REBASE_MERGE,
49 REBASE_INTERACTIVE,
50 REBASE_PRESERVE_MERGES
51};
55071ea2 52
73fdc535
PW
53struct rebase_options {
54 enum rebase_type type;
55 const char *state_dir;
56 struct commit *upstream;
57 const char *upstream_name;
58 const char *upstream_arg;
59 char *head_name;
60 struct object_id orig_head;
61 struct commit *onto;
62 const char *onto_name;
63 const char *revisions;
64 const char *switch_to;
65 int root;
66 struct object_id *squash_onto;
67 struct commit *restrict_revision;
68 int dont_finish_rebase;
69 enum {
70 REBASE_NO_QUIET = 1<<0,
71 REBASE_VERBOSE = 1<<1,
72 REBASE_DIFFSTAT = 1<<2,
73 REBASE_FORCE = 1<<3,
74 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
75 } flags;
76 struct argv_array git_am_opts;
77 const char *action;
78 int signoff;
79 int allow_rerere_autoupdate;
80 int keep_empty;
81 int autosquash;
82 char *gpg_sign_opt;
83 int autostash;
84 char *cmd;
85 int allow_empty_message;
86 int rebase_merges, rebase_cousins;
87 char *strategy, *strategy_opts;
88 struct strbuf git_format_patch_opt;
89 int reschedule_failed_exec;
90};
91
92#define REBASE_OPTIONS_INIT { \
93 .type = REBASE_UNSPECIFIED, \
94 .flags = REBASE_NO_QUIET, \
95 .git_am_opts = ARGV_ARRAY_INIT, \
96 .git_format_patch_opt = STRBUF_INIT \
97 }
98
99static struct replay_opts get_replay_opts(const struct rebase_options *opts)
100{
101 struct replay_opts replay = REPLAY_OPTS_INIT;
102
103 replay.action = REPLAY_INTERACTIVE_REBASE;
104 sequencer_init_config(&replay);
105
106 replay.signoff = opts->signoff;
107 replay.allow_ff = !(opts->flags & REBASE_FORCE);
108 if (opts->allow_rerere_autoupdate)
109 replay.allow_rerere_auto = opts->allow_rerere_autoupdate;
110 replay.allow_empty = 1;
111 replay.allow_empty_message = opts->allow_empty_message;
112 replay.verbose = opts->flags & REBASE_VERBOSE;
113 replay.reschedule_failed_exec = opts->reschedule_failed_exec;
114 replay.gpg_sign = xstrdup_or_null(opts->gpg_sign_opt);
115 replay.strategy = opts->strategy;
116
117 return replay;
118}
119
0609b741
PW
120static int add_exec_commands(struct string_list *commands)
121{
122 const char *todo_file = rebase_path_todo();
123 struct todo_list todo_list = TODO_LIST_INIT;
124 int res;
125
126 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
127 return error_errno(_("could not read '%s'."), todo_file);
128
129 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
130 &todo_list)) {
131 todo_list_release(&todo_list);
132 return error(_("unusable todo list: '%s'"), todo_file);
133 }
134
135 todo_list_add_exec_commands(&todo_list, commands);
136 res = todo_list_write_to_file(the_repository, &todo_list,
137 todo_file, NULL, NULL, -1, 0);
138 todo_list_release(&todo_list);
139
140 if (res)
141 return error_errno(_("could not write '%s'."), todo_file);
142 return 0;
143}
144
145static int rearrange_squash_in_todo_file(void)
146{
147 const char *todo_file = rebase_path_todo();
148 struct todo_list todo_list = TODO_LIST_INIT;
149 int res = 0;
150
151 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
152 return error_errno(_("could not read '%s'."), todo_file);
153 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
154 &todo_list)) {
155 todo_list_release(&todo_list);
156 return error(_("unusable todo list: '%s'"), todo_file);
157 }
158
159 res = todo_list_rearrange_squash(&todo_list);
160 if (!res)
161 res = todo_list_write_to_file(the_repository, &todo_list,
162 todo_file, NULL, NULL, -1, 0);
163
164 todo_list_release(&todo_list);
165
166 if (res)
167 return error_errno(_("could not write '%s'."), todo_file);
168 return 0;
169}
170
171static int transform_todo_file(unsigned flags)
172{
173 const char *todo_file = rebase_path_todo();
174 struct todo_list todo_list = TODO_LIST_INIT;
175 int res;
176
177 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
178 return error_errno(_("could not read '%s'."), todo_file);
179
180 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
181 &todo_list)) {
182 todo_list_release(&todo_list);
183 return error(_("unusable todo list: '%s'"), todo_file);
184 }
185
186 res = todo_list_write_to_file(the_repository, &todo_list, todo_file,
187 NULL, NULL, -1, flags);
188 todo_list_release(&todo_list);
189
190 if (res)
191 return error_errno(_("could not write '%s'."), todo_file);
192 return 0;
193}
194
195static int edit_todo_file(unsigned flags)
196{
197 const char *todo_file = rebase_path_todo();
198 struct todo_list todo_list = TODO_LIST_INIT,
199 new_todo = TODO_LIST_INIT;
200 int res = 0;
201
202 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
203 return error_errno(_("could not read '%s'."), todo_file);
204
205 strbuf_stripspace(&todo_list.buf, 1);
206 res = edit_todo_list(the_repository, &todo_list, &new_todo, NULL, NULL, flags);
207 if (!res && todo_list_write_to_file(the_repository, &new_todo, todo_file,
208 NULL, NULL, -1, flags & ~(TODO_LIST_SHORTEN_IDS)))
209 res = error_errno(_("could not write '%s'"), todo_file);
210
211 todo_list_release(&todo_list);
212 todo_list_release(&new_todo);
213
214 return res;
215}
216
7d3488eb 217static int get_revision_ranges(struct commit *upstream, struct commit *onto,
0609b741
PW
218 const char **head_hash,
219 char **revisions, char **shortrevisions)
220{
7d3488eb
PW
221 struct commit *base_rev = upstream ? upstream : onto;
222 const char *shorthead;
0609b741
PW
223 struct object_id orig_head;
224
225 if (get_oid("HEAD", &orig_head))
226 return error(_("no HEAD?"));
227
228 *head_hash = find_unique_abbrev(&orig_head, GIT_MAX_HEXSZ);
7d3488eb
PW
229 *revisions = xstrfmt("%s...%s", oid_to_hex(&base_rev->object.oid),
230 *head_hash);
0609b741
PW
231
232 shorthead = find_unique_abbrev(&orig_head, DEFAULT_ABBREV);
233
234 if (upstream) {
235 const char *shortrev;
0609b741 236
7d3488eb
PW
237 shortrev = find_unique_abbrev(&base_rev->object.oid,
238 DEFAULT_ABBREV);
0609b741
PW
239
240 *shortrevisions = xstrfmt("%s..%s", shortrev, shorthead);
241 } else
242 *shortrevisions = xstrdup(shorthead);
243
244 return 0;
245}
246
247static int init_basic_state(struct replay_opts *opts, const char *head_name,
7d3488eb 248 struct commit *onto, const char *orig_head)
0609b741
PW
249{
250 FILE *interactive;
251
c44c2462
PW
252 if (!is_directory(merge_dir()) && mkdir_in_gitdir(merge_dir()))
253 return error_errno(_("could not create temporary %s"), merge_dir());
0609b741
PW
254
255 delete_reflog("REBASE_HEAD");
256
257 interactive = fopen(path_interactive(), "w");
258 if (!interactive)
259 return error_errno(_("could not mark as interactive"));
260 fclose(interactive);
261
262 return write_basic_state(opts, head_name, onto, orig_head);
263}
264
265static int do_interactive_rebase(struct replay_opts *opts, unsigned flags,
7d3488eb
PW
266 const char *switch_to, struct commit *upstream,
267 struct commit *onto, const char *onto_name,
33898531 268 struct object_id *squash_onto, const char *head_name,
7d3488eb 269 struct commit *restrict_revision, char *raw_strategies,
0609b741
PW
270 struct string_list *commands, unsigned autosquash)
271{
272 int ret;
273 const char *head_hash = NULL;
274 char *revisions = NULL, *shortrevisions = NULL;
275 struct argv_array make_script_args = ARGV_ARRAY_INIT;
276 struct todo_list todo_list = TODO_LIST_INIT;
277
278 if (prepare_branch_to_be_rebased(the_repository, opts, switch_to))
279 return -1;
280
281 if (get_revision_ranges(upstream, onto, &head_hash,
282 &revisions, &shortrevisions))
283 return -1;
284
285 if (raw_strategies)
286 parse_strategy_opts(opts, raw_strategies);
287
288 if (init_basic_state(opts, head_name, onto, head_hash)) {
289 free(revisions);
290 free(shortrevisions);
291
292 return -1;
293 }
294
295 if (!upstream && squash_onto)
33898531
PW
296 write_file(path_squash_onto(), "%s\n",
297 oid_to_hex(squash_onto));
0609b741
PW
298
299 argv_array_pushl(&make_script_args, "", revisions, NULL);
300 if (restrict_revision)
7d3488eb
PW
301 argv_array_push(&make_script_args,
302 oid_to_hex(&restrict_revision->object.oid));
0609b741
PW
303
304 ret = sequencer_make_script(the_repository, &todo_list.buf,
305 make_script_args.argc, make_script_args.argv,
306 flags);
307
308 if (ret)
309 error(_("could not generate todo list"));
310 else {
311 discard_cache();
312 if (todo_list_parse_insn_buffer(the_repository, todo_list.buf.buf,
313 &todo_list))
314 BUG("unusable todo list");
315
316 ret = complete_action(the_repository, opts, flags, shortrevisions, onto_name,
317 onto, head_hash, commands, autosquash, &todo_list);
318 }
319
320 free(revisions);
321 free(shortrevisions);
322 todo_list_release(&todo_list);
323 argv_array_clear(&make_script_args);
324
325 return ret;
326}
327
328static const char * const builtin_rebase_interactive_usage[] = {
329 N_("git rebase--interactive [<options>]"),
330 NULL
331};
332
333int cmd_rebase__interactive(int argc, const char **argv, const char *prefix)
334{
73fdc535
PW
335 struct rebase_options opts = REBASE_OPTIONS_INIT;
336 unsigned flags = 0;
337 int abbreviate_commands = 0, ret = 0;
33898531 338 struct object_id squash_onto = null_oid;
0609b741 339 struct string_list commands = STRING_LIST_INIT_DUP;
0609b741
PW
340 enum {
341 NONE = 0, CONTINUE, SKIP, EDIT_TODO, SHOW_CURRENT_PATCH,
342 SHORTEN_OIDS, EXPAND_OIDS, CHECK_TODO_LIST, REARRANGE_SQUASH, ADD_EXEC
343 } command = 0;
344 struct option options[] = {
73fdc535
PW
345 OPT_NEGBIT(0, "ff", &opts.flags, N_("allow fast-forward"),
346 REBASE_FORCE),
347 OPT_BOOL(0, "keep-empty", &opts.keep_empty, N_("keep empty commits")),
0609b741
PW
348 OPT_BOOL(0, "allow-empty-message", &opts.allow_empty_message,
349 N_("allow commits with empty messages")),
73fdc535
PW
350 OPT_BOOL(0, "rebase-merges", &opts.rebase_merges, N_("rebase merge commits")),
351 OPT_BOOL(0, "rebase-cousins", &opts.rebase_cousins,
0609b741 352 N_("keep original branch points of cousins")),
73fdc535 353 OPT_BOOL(0, "autosquash", &opts.autosquash,
0609b741
PW
354 N_("move commits that begin with squash!/fixup!")),
355 OPT_BOOL(0, "signoff", &opts.signoff, N_("sign commits")),
73fdc535
PW
356 OPT_BIT('v', "verbose", &opts.flags,
357 N_("display a diffstat of what changed upstream"),
358 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
0609b741
PW
359 OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),
360 CONTINUE),
361 OPT_CMDMODE(0, "skip", &command, N_("skip commit"), SKIP),
362 OPT_CMDMODE(0, "edit-todo", &command, N_("edit the todo list"),
363 EDIT_TODO),
364 OPT_CMDMODE(0, "show-current-patch", &command, N_("show the current patch"),
365 SHOW_CURRENT_PATCH),
366 OPT_CMDMODE(0, "shorten-ids", &command,
367 N_("shorten commit ids in the todo list"), SHORTEN_OIDS),
368 OPT_CMDMODE(0, "expand-ids", &command,
369 N_("expand commit ids in the todo list"), EXPAND_OIDS),
370 OPT_CMDMODE(0, "check-todo-list", &command,
371 N_("check the todo list"), CHECK_TODO_LIST),
372 OPT_CMDMODE(0, "rearrange-squash", &command,
373 N_("rearrange fixup/squash lines"), REARRANGE_SQUASH),
374 OPT_CMDMODE(0, "add-exec-commands", &command,
375 N_("insert exec commands in todo list"), ADD_EXEC),
73fdc535 376 { OPTION_CALLBACK, 0, "onto", &opts.onto, N_("onto"), N_("onto"),
7d3488eb 377 PARSE_OPT_NONEG, parse_opt_commit, 0 },
73fdc535 378 { OPTION_CALLBACK, 0, "restrict-revision", &opts.restrict_revision,
7d3488eb
PW
379 N_("restrict-revision"), N_("restrict revision"),
380 PARSE_OPT_NONEG, parse_opt_commit, 0 },
33898531
PW
381 { OPTION_CALLBACK, 0, "squash-onto", &squash_onto, N_("squash-onto"),
382 N_("squash onto"), PARSE_OPT_NONEG, parse_opt_object_id, 0 },
73fdc535 383 { OPTION_CALLBACK, 0, "upstream", &opts.upstream, N_("upstream"),
7d3488eb
PW
384 N_("the upstream commit"), PARSE_OPT_NONEG, parse_opt_commit,
385 0 },
73fdc535
PW
386 OPT_STRING(0, "head-name", &opts.head_name, N_("head-name"), N_("head name")),
387 { OPTION_STRING, 'S', "gpg-sign", &opts.gpg_sign_opt, N_("key-id"),
0609b741
PW
388 N_("GPG-sign commits"),
389 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
390 OPT_STRING(0, "strategy", &opts.strategy, N_("strategy"),
391 N_("rebase strategy")),
73fdc535 392 OPT_STRING(0, "strategy-opts", &opts.strategy_opts, N_("strategy-opts"),
0609b741 393 N_("strategy options")),
73fdc535 394 OPT_STRING(0, "switch-to", &opts.switch_to, N_("switch-to"),
0609b741 395 N_("the branch or commit to checkout")),
73fdc535
PW
396 OPT_STRING(0, "onto-name", &opts.onto_name, N_("onto-name"), N_("onto name")),
397 OPT_STRING(0, "cmd", &opts.cmd, N_("cmd"), N_("the command to run")),
398 OPT_RERERE_AUTOUPDATE(&opts.allow_rerere_autoupdate),
0609b741
PW
399 OPT_BOOL(0, "reschedule-failed-exec", &opts.reschedule_failed_exec,
400 N_("automatically re-schedule any `exec` that fails")),
401 OPT_END()
402 };
403
73fdc535 404 opts.rebase_cousins = -1;
0609b741 405
73fdc535 406 git_config_get_bool("rebase.abbreviatecommands", &abbreviate_commands);
0609b741
PW
407
408 if (argc == 1)
409 usage_with_options(builtin_rebase_interactive_usage, options);
410
411 argc = parse_options(argc, argv, NULL, options,
412 builtin_rebase_interactive_usage, PARSE_OPT_KEEP_ARGV0);
413
33898531 414 if (!is_null_oid(&squash_onto))
73fdc535 415 opts.squash_onto = &squash_onto;
33898531 416
73fdc535 417 flags |= opts.keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
0609b741 418 flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
73fdc535
PW
419 flags |= opts.rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
420 flags |= opts.rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
0609b741
PW
421 flags |= command == SHORTEN_OIDS ? TODO_LIST_SHORTEN_IDS : 0;
422
73fdc535 423 if (opts.rebase_cousins >= 0 && !opts.rebase_merges)
0609b741
PW
424 warning(_("--[no-]rebase-cousins has no effect without "
425 "--rebase-merges"));
426
73fdc535
PW
427 if (opts.cmd && *opts.cmd) {
428 string_list_split(&commands, opts.cmd, '\n', -1);
0609b741
PW
429
430 /* rebase.c adds a new line to cmd after every command,
431 * so here the last command is always empty */
432 string_list_remove_empty_items(&commands, 0);
433 }
434
435 switch (command) {
73fdc535
PW
436 case NONE: {
437 struct replay_opts replay_opts = get_replay_opts(&opts);
438 if (!opts.onto && !opts.upstream)
0609b741
PW
439 die(_("a base commit must be provided with --upstream or --onto"));
440
73fdc535
PW
441 ret = do_interactive_rebase(&replay_opts, flags, opts.switch_to, opts.upstream, opts.onto,
442 opts.onto_name, opts.squash_onto, opts.head_name, opts.restrict_revision,
443 opts.strategy_opts, &commands, opts.autosquash);
0609b741 444 break;
73fdc535 445 }
0609b741
PW
446 case SKIP: {
447 struct string_list merge_rr = STRING_LIST_INIT_DUP;
448
449 rerere_clear(the_repository, &merge_rr);
73fdc535 450 }
0609b741 451 /* fallthrough */
73fdc535
PW
452 case CONTINUE: {
453 struct replay_opts replay_opts = get_replay_opts(&opts);
454
455 ret = sequencer_continue(the_repository, &replay_opts);
0609b741
PW
456 break;
457 }
458 case EDIT_TODO:
459 ret = edit_todo_file(flags);
460 break;
461 case SHOW_CURRENT_PATCH: {
462 struct child_process cmd = CHILD_PROCESS_INIT;
463
464 cmd.git_cmd = 1;
465 argv_array_pushl(&cmd.args, "show", "REBASE_HEAD", "--", NULL);
466 ret = run_command(&cmd);
467
468 break;
469 }
470 case SHORTEN_OIDS:
471 case EXPAND_OIDS:
472 ret = transform_todo_file(flags);
473 break;
474 case CHECK_TODO_LIST:
475 ret = check_todo_list_from_file(the_repository);
476 break;
477 case REARRANGE_SQUASH:
478 ret = rearrange_squash_in_todo_file();
479 break;
480 case ADD_EXEC:
481 ret = add_exec_commands(&commands);
482 break;
483 default:
484 BUG("invalid command '%d'", command);
485 }
486
487 string_list_clear(&commands, 0);
488 return !!ret;
489}
490
55071ea2
PK
491static int use_builtin_rebase(void)
492{
493 struct child_process cp = CHILD_PROCESS_INIT;
494 struct strbuf out = STRBUF_INIT;
62c23938
ÆAB
495 int ret, env = git_env_bool("GIT_TEST_REBASE_USE_BUILTIN", -1);
496
497 if (env != -1)
498 return env;
55071ea2
PK
499
500 argv_array_pushl(&cp.args,
501 "config", "--bool", "rebase.usebuiltin", NULL);
502 cp.git_cmd = 1;
503 if (capture_command(&cp, &out, 6)) {
504 strbuf_release(&out);
5541bd5b 505 return 1;
55071ea2
PK
506 }
507
508 strbuf_trim(&out);
509 ret = !strcmp("true", out.buf);
510 strbuf_release(&out);
511 return ret;
512}
513
9a48a615
PK
514static int is_interactive(struct rebase_options *opts)
515{
516 return opts->type == REBASE_INTERACTIVE ||
517 opts->type == REBASE_PRESERVE_MERGES;
518}
519
002ee2fe
PK
520static void imply_interactive(struct rebase_options *opts, const char *option)
521{
522 switch (opts->type) {
523 case REBASE_AM:
524 die(_("%s requires an interactive rebase"), option);
525 break;
526 case REBASE_INTERACTIVE:
527 case REBASE_PRESERVE_MERGES:
528 break;
529 case REBASE_MERGE:
68aa495b 530 /* we now implement --merge via --interactive */
002ee2fe
PK
531 default:
532 opts->type = REBASE_INTERACTIVE; /* implied */
533 break;
534 }
535}
536
ac7f467f
PK
537/* Returns the filename prefixed by the state_dir */
538static const char *state_dir_path(const char *filename, struct rebase_options *opts)
539{
540 static struct strbuf path = STRBUF_INIT;
541 static size_t prefix_len;
542
543 if (!prefix_len) {
544 strbuf_addf(&path, "%s/", opts->state_dir);
545 prefix_len = path.len;
546 }
547
548 strbuf_setlen(&path, prefix_len);
549 strbuf_addstr(&path, filename);
550 return path.buf;
551}
552
f9573628
PK
553/* Read one file, then strip line endings */
554static int read_one(const char *path, struct strbuf *buf)
555{
556 if (strbuf_read_file(buf, path, 0) < 0)
557 return error_errno(_("could not read '%s'"), path);
558 strbuf_trim_trailing_newline(buf);
559 return 0;
560}
561
562/* Initialize the rebase options from the state directory. */
563static int read_basic_state(struct rebase_options *opts)
564{
565 struct strbuf head_name = STRBUF_INIT;
566 struct strbuf buf = STRBUF_INIT;
567 struct object_id oid;
568
569 if (read_one(state_dir_path("head-name", opts), &head_name) ||
570 read_one(state_dir_path("onto", opts), &buf))
571 return -1;
572 opts->head_name = starts_with(head_name.buf, "refs/") ?
573 xstrdup(head_name.buf) : NULL;
574 strbuf_release(&head_name);
575 if (get_oid(buf.buf, &oid))
576 return error(_("could not get 'onto': '%s'"), buf.buf);
577 opts->onto = lookup_commit_or_die(&oid, buf.buf);
578
579 /*
580 * We always write to orig-head, but interactive rebase used to write to
581 * head. Fall back to reading from head to cover for the case that the
582 * user upgraded git with an ongoing interactive rebase.
583 */
584 strbuf_reset(&buf);
585 if (file_exists(state_dir_path("orig-head", opts))) {
586 if (read_one(state_dir_path("orig-head", opts), &buf))
587 return -1;
588 } else if (read_one(state_dir_path("head", opts), &buf))
589 return -1;
590 if (get_oid(buf.buf, &opts->orig_head))
591 return error(_("invalid orig-head: '%s'"), buf.buf);
592
899b49c4 593 if (file_exists(state_dir_path("quiet", opts)))
f9573628
PK
594 opts->flags &= ~REBASE_NO_QUIET;
595 else
596 opts->flags |= REBASE_NO_QUIET;
597
598 if (file_exists(state_dir_path("verbose", opts)))
599 opts->flags |= REBASE_VERBOSE;
600
73d51ed0
PK
601 if (file_exists(state_dir_path("signoff", opts))) {
602 opts->signoff = 1;
603 opts->flags |= REBASE_FORCE;
604 }
605
ead98c11
PK
606 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
607 strbuf_reset(&buf);
608 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
609 &buf))
610 return -1;
611 if (!strcmp(buf.buf, "--rerere-autoupdate"))
6023c928 612 opts->allow_rerere_autoupdate = RERERE_AUTOUPDATE;
ead98c11 613 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
6023c928 614 opts->allow_rerere_autoupdate = RERERE_NOAUTOUPDATE;
ead98c11
PK
615 else
616 warning(_("ignoring invalid allow_rerere_autoupdate: "
617 "'%s'"), buf.buf);
6023c928 618 }
ead98c11 619
12026a41
PK
620 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
621 strbuf_reset(&buf);
622 if (read_one(state_dir_path("gpg_sign_opt", opts),
623 &buf))
624 return -1;
625 free(opts->gpg_sign_opt);
626 opts->gpg_sign_opt = xstrdup(buf.buf);
627 }
628
ba1905a5
PK
629 if (file_exists(state_dir_path("strategy", opts))) {
630 strbuf_reset(&buf);
631 if (read_one(state_dir_path("strategy", opts), &buf))
632 return -1;
633 free(opts->strategy);
634 opts->strategy = xstrdup(buf.buf);
635 }
636
637 if (file_exists(state_dir_path("strategy_opts", opts))) {
638 strbuf_reset(&buf);
639 if (read_one(state_dir_path("strategy_opts", opts), &buf))
640 return -1;
641 free(opts->strategy_opts);
642 opts->strategy_opts = xstrdup(buf.buf);
643 }
644
f9573628
PK
645 strbuf_release(&buf);
646
647 return 0;
648}
649
28dc09de 650static int rebase_write_basic_state(struct rebase_options *opts)
21853626
JS
651{
652 write_file(state_dir_path("head-name", opts), "%s",
653 opts->head_name ? opts->head_name : "detached HEAD");
654 write_file(state_dir_path("onto", opts), "%s",
655 opts->onto ? oid_to_hex(&opts->onto->object.oid) : "");
656 write_file(state_dir_path("orig-head", opts), "%s",
657 oid_to_hex(&opts->orig_head));
658 write_file(state_dir_path("quiet", opts), "%s",
659 opts->flags & REBASE_NO_QUIET ? "" : "t");
660 if (opts->flags & REBASE_VERBOSE)
661 write_file(state_dir_path("verbose", opts), "%s", "");
662 if (opts->strategy)
663 write_file(state_dir_path("strategy", opts), "%s",
664 opts->strategy);
665 if (opts->strategy_opts)
666 write_file(state_dir_path("strategy_opts", opts), "%s",
667 opts->strategy_opts);
6023c928 668 if (opts->allow_rerere_autoupdate > 0)
21853626
JS
669 write_file(state_dir_path("allow_rerere_autoupdate", opts),
670 "-%s-rerere-autoupdate",
6023c928
PW
671 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
672 "" : "-no");
21853626
JS
673 if (opts->gpg_sign_opt)
674 write_file(state_dir_path("gpg_sign_opt", opts), "%s",
675 opts->gpg_sign_opt);
676 if (opts->signoff)
677 write_file(state_dir_path("strategy", opts), "--signoff");
678
679 return 0;
680}
681
6defce2b
PK
682static int apply_autostash(struct rebase_options *opts)
683{
684 const char *path = state_dir_path("autostash", opts);
685 struct strbuf autostash = STRBUF_INIT;
686 struct child_process stash_apply = CHILD_PROCESS_INIT;
687
688 if (!file_exists(path))
689 return 0;
690
71064e60 691 if (read_one(path, &autostash))
6defce2b 692 return error(_("Could not read '%s'"), path);
b98e914e
JS
693 /* Ensure that the hash is not mistaken for a number */
694 strbuf_addstr(&autostash, "^0");
6defce2b
PK
695 argv_array_pushl(&stash_apply.args,
696 "stash", "apply", autostash.buf, NULL);
697 stash_apply.git_cmd = 1;
698 stash_apply.no_stderr = stash_apply.no_stdout =
699 stash_apply.no_stdin = 1;
700 if (!run_command(&stash_apply))
701 printf(_("Applied autostash.\n"));
702 else {
703 struct argv_array args = ARGV_ARRAY_INIT;
704 int res = 0;
705
706 argv_array_pushl(&args,
707 "stash", "store", "-m", "autostash", "-q",
708 autostash.buf, NULL);
709 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
710 res = error(_("Cannot store %s"), autostash.buf);
711 argv_array_clear(&args);
712 strbuf_release(&autostash);
713 if (res)
714 return res;
715
716 fprintf(stderr,
717 _("Applying autostash resulted in conflicts.\n"
718 "Your changes are safe in the stash.\n"
719 "You can run \"git stash pop\" or \"git stash drop\" "
720 "at any time.\n"));
721 }
722
723 strbuf_release(&autostash);
724 return 0;
725}
726
ac7f467f
PK
727static int finish_rebase(struct rebase_options *opts)
728{
729 struct strbuf dir = STRBUF_INIT;
730 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
731
732 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
6defce2b 733 apply_autostash(opts);
ac7f467f
PK
734 close_all_packs(the_repository->objects);
735 /*
736 * We ignore errors in 'gc --auto', since the
737 * user should see them.
738 */
739 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
740 strbuf_addstr(&dir, opts->state_dir);
741 remove_dir_recursively(&dir, 0);
742 strbuf_release(&dir);
743
744 return 0;
745}
746
747static struct commit *peel_committish(const char *name)
748{
749 struct object *obj;
750 struct object_id oid;
751
752 if (get_oid(name, &oid))
753 return NULL;
754 obj = parse_object(the_repository, &oid);
755 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
756}
757
758static void add_var(struct strbuf *buf, const char *name, const char *value)
759{
760 if (!value)
761 strbuf_addf(buf, "unset %s; ", name);
762 else {
763 strbuf_addf(buf, "%s=", name);
764 sq_quote_buf(buf, value);
765 strbuf_addstr(buf, "; ");
766 }
767}
768
c5233708
JS
769#define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
770
771#define RESET_HEAD_DETACH (1<<0)
772#define RESET_HEAD_HARD (1<<1)
e52c6bbd
JH
773#define RESET_HEAD_RUN_POST_CHECKOUT_HOOK (1<<2)
774#define RESET_HEAD_REFS_ONLY (1<<3)
c5233708
JS
775
776static int reset_head(struct object_id *oid, const char *action,
777 const char *switch_to_branch, unsigned flags,
778 const char *reflog_orig_head, const char *reflog_head)
779{
780 unsigned detach_head = flags & RESET_HEAD_DETACH;
781 unsigned reset_hard = flags & RESET_HEAD_HARD;
e52c6bbd 782 unsigned run_hook = flags & RESET_HEAD_RUN_POST_CHECKOUT_HOOK;
414f3360 783 unsigned refs_only = flags & RESET_HEAD_REFS_ONLY;
c5233708
JS
784 struct object_id head_oid;
785 struct tree_desc desc[2] = { { NULL }, { NULL } };
786 struct lock_file lock = LOCK_INIT;
787 struct unpack_trees_options unpack_tree_opts;
788 struct tree *tree;
789 const char *reflog_action;
790 struct strbuf msg = STRBUF_INIT;
791 size_t prefix_len;
792 struct object_id *orig = NULL, oid_orig,
793 *old_orig = NULL, oid_old_orig;
794 int ret = 0, nr = 0;
795
796 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
797 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
798
414f3360 799 if (!refs_only && hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
c5233708
JS
800 ret = -1;
801 goto leave_reset_head;
802 }
803
804 if ((!oid || !reset_hard) && get_oid("HEAD", &head_oid)) {
805 ret = error(_("could not determine HEAD revision"));
806 goto leave_reset_head;
807 }
808
809 if (!oid)
810 oid = &head_oid;
811
414f3360
JS
812 if (refs_only)
813 goto reset_head_refs;
814
c5233708
JS
815 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
816 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
817 unpack_tree_opts.head_idx = 1;
818 unpack_tree_opts.src_index = the_repository->index;
819 unpack_tree_opts.dst_index = the_repository->index;
820 unpack_tree_opts.fn = reset_hard ? oneway_merge : twoway_merge;
821 unpack_tree_opts.update = 1;
822 unpack_tree_opts.merge = 1;
823 if (!detach_head)
824 unpack_tree_opts.reset = 1;
825
7589e636 826 if (repo_read_index_unmerged(the_repository) < 0) {
c5233708
JS
827 ret = error(_("could not read index"));
828 goto leave_reset_head;
829 }
830
831 if (!reset_hard && !fill_tree_descriptor(&desc[nr++], &head_oid)) {
832 ret = error(_("failed to find tree of %s"),
833 oid_to_hex(&head_oid));
834 goto leave_reset_head;
835 }
836
837 if (!fill_tree_descriptor(&desc[nr++], oid)) {
838 ret = error(_("failed to find tree of %s"), oid_to_hex(oid));
839 goto leave_reset_head;
840 }
841
842 if (unpack_trees(nr, desc, &unpack_tree_opts)) {
843 ret = -1;
844 goto leave_reset_head;
845 }
846
847 tree = parse_tree_indirect(oid);
e52c6bbd 848 prime_cache_tree(the_repository, the_repository->index, tree);
c5233708
JS
849
850 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0) {
851 ret = error(_("could not write index"));
852 goto leave_reset_head;
853 }
854
414f3360 855reset_head_refs:
c5233708
JS
856 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
857 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
858 prefix_len = msg.len;
859
860 if (!get_oid("ORIG_HEAD", &oid_old_orig))
861 old_orig = &oid_old_orig;
862 if (!get_oid("HEAD", &oid_orig)) {
863 orig = &oid_orig;
864 if (!reflog_orig_head) {
865 strbuf_addstr(&msg, "updating ORIG_HEAD");
866 reflog_orig_head = msg.buf;
867 }
868 update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
869 UPDATE_REFS_MSG_ON_ERR);
870 } else if (old_orig)
871 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
872 if (!reflog_head) {
873 strbuf_setlen(&msg, prefix_len);
874 strbuf_addstr(&msg, "updating HEAD");
875 reflog_head = msg.buf;
876 }
877 if (!switch_to_branch)
878 ret = update_ref(reflog_head, "HEAD", oid, orig,
879 detach_head ? REF_NO_DEREF : 0,
880 UPDATE_REFS_MSG_ON_ERR);
881 else {
5b2237a8
JS
882 ret = update_ref(reflog_orig_head, switch_to_branch, oid,
883 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
c5233708 884 if (!ret)
5b2237a8
JS
885 ret = create_symref("HEAD", switch_to_branch,
886 reflog_head);
c5233708 887 }
e52c6bbd
JH
888 if (run_hook)
889 run_hook_le(NULL, "post-checkout",
890 oid_to_hex(orig ? orig : &null_oid),
891 oid_to_hex(oid), "1", NULL);
c5233708
JS
892
893leave_reset_head:
894 strbuf_release(&msg);
895 rollback_lock_file(&lock);
896 while (nr)
897 free((void *)desc[--nr].buffer);
898 return ret;
899}
900
21853626
JS
901static int move_to_original_branch(struct rebase_options *opts)
902{
903 struct strbuf orig_head_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT;
904 int ret;
905
906 if (!opts->head_name)
907 return 0; /* nothing to move back to */
908
909 if (!opts->onto)
910 BUG("move_to_original_branch without onto");
911
912 strbuf_addf(&orig_head_reflog, "rebase finished: %s onto %s",
913 opts->head_name, oid_to_hex(&opts->onto->object.oid));
914 strbuf_addf(&head_reflog, "rebase finished: returning to %s",
915 opts->head_name);
916 ret = reset_head(NULL, "", opts->head_name, RESET_HEAD_REFS_ONLY,
917 orig_head_reflog.buf, head_reflog.buf);
918
919 strbuf_release(&orig_head_reflog);
920 strbuf_release(&head_reflog);
921 return ret;
922}
923
bc24382c
JS
924static const char *resolvemsg =
925N_("Resolve all conflicts manually, mark them as resolved with\n"
926"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
927"You can instead skip this commit: run \"git rebase --skip\".\n"
928"To abort and get back to the state before \"git rebase\", run "
929"\"git rebase --abort\".");
930
21853626
JS
931static int run_am(struct rebase_options *opts)
932{
933 struct child_process am = CHILD_PROCESS_INIT;
934 struct child_process format_patch = CHILD_PROCESS_INIT;
935 struct strbuf revisions = STRBUF_INIT;
936 int status;
937 char *rebased_patches;
938
939 am.git_cmd = 1;
940 argv_array_push(&am.args, "am");
941
942 if (opts->action && !strcmp("continue", opts->action)) {
943 argv_array_push(&am.args, "--resolved");
944 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
945 if (opts->gpg_sign_opt)
946 argv_array_push(&am.args, opts->gpg_sign_opt);
947 status = run_command(&am);
948 if (status)
949 return status;
950
951 return move_to_original_branch(opts);
952 }
953 if (opts->action && !strcmp("skip", opts->action)) {
954 argv_array_push(&am.args, "--skip");
955 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
956 status = run_command(&am);
957 if (status)
958 return status;
959
960 return move_to_original_branch(opts);
961 }
962 if (opts->action && !strcmp("show-current-patch", opts->action)) {
963 argv_array_push(&am.args, "--show-current-patch");
964 return run_command(&am);
965 }
966
967 strbuf_addf(&revisions, "%s...%s",
968 oid_to_hex(opts->root ?
969 /* this is now equivalent to !opts->upstream */
970 &opts->onto->object.oid :
971 &opts->upstream->object.oid),
972 oid_to_hex(&opts->orig_head));
973
974 rebased_patches = xstrdup(git_path("rebased-patches"));
975 format_patch.out = open(rebased_patches,
976 O_WRONLY | O_CREAT | O_TRUNC, 0666);
977 if (format_patch.out < 0) {
978 status = error_errno(_("could not open '%s' for writing"),
979 rebased_patches);
980 free(rebased_patches);
981 argv_array_clear(&am.args);
982 return status;
983 }
984
985 format_patch.git_cmd = 1;
986 argv_array_pushl(&format_patch.args, "format-patch", "-k", "--stdout",
987 "--full-index", "--cherry-pick", "--right-only",
988 "--src-prefix=a/", "--dst-prefix=b/", "--no-renames",
e52c6bbd 989 "--no-cover-letter", "--pretty=mboxrd", "--topo-order", NULL);
21853626
JS
990 if (opts->git_format_patch_opt.len)
991 argv_array_split(&format_patch.args,
992 opts->git_format_patch_opt.buf);
993 argv_array_push(&format_patch.args, revisions.buf);
994 if (opts->restrict_revision)
995 argv_array_pushf(&format_patch.args, "^%s",
996 oid_to_hex(&opts->restrict_revision->object.oid));
997
998 status = run_command(&format_patch);
999 if (status) {
1000 unlink(rebased_patches);
1001 free(rebased_patches);
1002 argv_array_clear(&am.args);
1003
1004 reset_head(&opts->orig_head, "checkout", opts->head_name, 0,
1005 "HEAD", NULL);
1006 error(_("\ngit encountered an error while preparing the "
1007 "patches to replay\n"
1008 "these revisions:\n"
1009 "\n %s\n\n"
1010 "As a result, git cannot rebase them."),
1011 opts->revisions);
1012
1013 strbuf_release(&revisions);
1014 return status;
1015 }
1016 strbuf_release(&revisions);
1017
1018 am.in = open(rebased_patches, O_RDONLY);
1019 if (am.in < 0) {
1020 status = error_errno(_("could not open '%s' for reading"),
1021 rebased_patches);
1022 free(rebased_patches);
1023 argv_array_clear(&am.args);
1024 return status;
1025 }
1026
1027 argv_array_pushv(&am.args, opts->git_am_opts.argv);
1028 argv_array_push(&am.args, "--rebasing");
1029 argv_array_pushf(&am.args, "--resolvemsg=%s", resolvemsg);
1030 argv_array_push(&am.args, "--patch-format=mboxrd");
6023c928 1031 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
21853626 1032 argv_array_push(&am.args, "--rerere-autoupdate");
6023c928 1033 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
21853626
JS
1034 argv_array_push(&am.args, "--no-rerere-autoupdate");
1035 if (opts->gpg_sign_opt)
1036 argv_array_push(&am.args, opts->gpg_sign_opt);
1037 status = run_command(&am);
1038 unlink(rebased_patches);
1039 free(rebased_patches);
1040
1041 if (!status) {
1042 return move_to_original_branch(opts);
1043 }
1044
1045 if (is_directory(opts->state_dir))
28dc09de 1046 rebase_write_basic_state(opts);
21853626
JS
1047
1048 return status;
1049}
1050
ac7f467f
PK
1051static int run_specific_rebase(struct rebase_options *opts)
1052{
1053 const char *argv[] = { NULL, NULL };
f5769680 1054 struct strbuf script_snippet = STRBUF_INIT, buf = STRBUF_INIT;
ac7f467f
PK
1055 int status;
1056 const char *backend, *backend_func;
1057
bc24382c
JS
1058 if (opts->type == REBASE_INTERACTIVE) {
1059 /* Run builtin interactive rebase */
1060 struct child_process child = CHILD_PROCESS_INIT;
1061
1062 argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
1063 resolvemsg);
1064 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
891d4a03
PW
1065 argv_array_push(&child.env_array,
1066 "GIT_SEQUENCE_EDITOR=:");
bc24382c
JS
1067 opts->autosquash = 0;
1068 }
1069
1070 child.git_cmd = 1;
1071 argv_array_push(&child.args, "rebase--interactive");
1072
1073 if (opts->action)
1074 argv_array_pushf(&child.args, "--%s", opts->action);
1075 if (opts->keep_empty)
1076 argv_array_push(&child.args, "--keep-empty");
1077 if (opts->rebase_merges)
1078 argv_array_push(&child.args, "--rebase-merges");
1079 if (opts->rebase_cousins)
1080 argv_array_push(&child.args, "--rebase-cousins");
1081 if (opts->autosquash)
1082 argv_array_push(&child.args, "--autosquash");
1083 if (opts->flags & REBASE_VERBOSE)
1084 argv_array_push(&child.args, "--verbose");
1085 if (opts->flags & REBASE_FORCE)
1086 argv_array_push(&child.args, "--no-ff");
1087 if (opts->restrict_revision)
1088 argv_array_pushf(&child.args,
1089 "--restrict-revision=^%s",
1090 oid_to_hex(&opts->restrict_revision->object.oid));
1091 if (opts->upstream)
1092 argv_array_pushf(&child.args, "--upstream=%s",
1093 oid_to_hex(&opts->upstream->object.oid));
1094 if (opts->onto)
1095 argv_array_pushf(&child.args, "--onto=%s",
1096 oid_to_hex(&opts->onto->object.oid));
1097 if (opts->squash_onto)
1098 argv_array_pushf(&child.args, "--squash-onto=%s",
1099 oid_to_hex(opts->squash_onto));
1100 if (opts->onto_name)
1101 argv_array_pushf(&child.args, "--onto-name=%s",
1102 opts->onto_name);
1103 argv_array_pushf(&child.args, "--head-name=%s",
1104 opts->head_name ?
1105 opts->head_name : "detached HEAD");
1106 if (opts->strategy)
1107 argv_array_pushf(&child.args, "--strategy=%s",
1108 opts->strategy);
1109 if (opts->strategy_opts)
1110 argv_array_pushf(&child.args, "--strategy-opts=%s",
1111 opts->strategy_opts);
1112 if (opts->switch_to)
1113 argv_array_pushf(&child.args, "--switch-to=%s",
1114 opts->switch_to);
1115 if (opts->cmd)
1116 argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
1117 if (opts->allow_empty_message)
1118 argv_array_push(&child.args, "--allow-empty-message");
6023c928 1119 if (opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE)
bc24382c 1120 argv_array_push(&child.args, "--rerere-autoupdate");
6023c928 1121 else if (opts->allow_rerere_autoupdate == RERERE_NOAUTOUPDATE)
bc24382c
JS
1122 argv_array_push(&child.args, "--no-rerere-autoupdate");
1123 if (opts->gpg_sign_opt)
1124 argv_array_push(&child.args, opts->gpg_sign_opt);
1125 if (opts->signoff)
1126 argv_array_push(&child.args, "--signoff");
d421afa0
JS
1127 if (opts->reschedule_failed_exec)
1128 argv_array_push(&child.args, "--reschedule-failed-exec");
bc24382c
JS
1129
1130 status = run_command(&child);
1131 goto finished_rebase;
1132 }
1133
21853626
JS
1134 if (opts->type == REBASE_AM) {
1135 status = run_am(opts);
1136 goto finished_rebase;
1137 }
1138
ac7f467f
PK
1139 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
1140 add_var(&script_snippet, "state_dir", opts->state_dir);
1141
1142 add_var(&script_snippet, "upstream_name", opts->upstream_name);
f9573628
PK
1143 add_var(&script_snippet, "upstream", opts->upstream ?
1144 oid_to_hex(&opts->upstream->object.oid) : NULL);
d4c569f8
PK
1145 add_var(&script_snippet, "head_name",
1146 opts->head_name ? opts->head_name : "detached HEAD");
ac7f467f 1147 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
f9573628
PK
1148 add_var(&script_snippet, "onto", opts->onto ?
1149 oid_to_hex(&opts->onto->object.oid) : NULL);
ac7f467f
PK
1150 add_var(&script_snippet, "onto_name", opts->onto_name);
1151 add_var(&script_snippet, "revisions", opts->revisions);
1152 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
1153 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
b4c8eb02
PK
1154 add_var(&script_snippet, "GIT_QUIET",
1155 opts->flags & REBASE_NO_QUIET ? "" : "t");
f5769680
JS
1156 sq_quote_argv_pretty(&buf, opts->git_am_opts.argv);
1157 add_var(&script_snippet, "git_am_opt", buf.buf);
1158 strbuf_release(&buf);
bff014da
PK
1159 add_var(&script_snippet, "verbose",
1160 opts->flags & REBASE_VERBOSE ? "t" : "");
1161 add_var(&script_snippet, "diffstat",
1162 opts->flags & REBASE_DIFFSTAT ? "t" : "");
1ed9c14f
PK
1163 add_var(&script_snippet, "force_rebase",
1164 opts->flags & REBASE_FORCE ? "t" : "");
e65123a7
PK
1165 if (opts->switch_to)
1166 add_var(&script_snippet, "switch_to", opts->switch_to);
f9573628 1167 add_var(&script_snippet, "action", opts->action ? opts->action : "");
73d51ed0 1168 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
ead98c11 1169 add_var(&script_snippet, "allow_rerere_autoupdate",
ead98c11 1170 opts->allow_rerere_autoupdate ?
6023c928
PW
1171 opts->allow_rerere_autoupdate == RERERE_AUTOUPDATE ?
1172 "--rerere-autoupdate" : "--no-rerere-autoupdate" : "");
002ee2fe 1173 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
051910a9 1174 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
12026a41 1175 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
68e46d78 1176 add_var(&script_snippet, "cmd", opts->cmd);
9b3a448b
PK
1177 add_var(&script_snippet, "allow_empty_message",
1178 opts->allow_empty_message ? "--allow-empty-message" : "");
3c3588c7
PK
1179 add_var(&script_snippet, "rebase_merges",
1180 opts->rebase_merges ? "t" : "");
1181 add_var(&script_snippet, "rebase_cousins",
1182 opts->rebase_cousins ? "t" : "");
ba1905a5
PK
1183 add_var(&script_snippet, "strategy", opts->strategy);
1184 add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
9dba809a
PK
1185 add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
1186 add_var(&script_snippet, "squash_onto",
1187 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
cda614e4
PK
1188 add_var(&script_snippet, "git_format_patch_opt",
1189 opts->git_format_patch_opt.buf);
ac7f467f 1190
3dba9d08
PK
1191 if (is_interactive(opts) &&
1192 !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
1193 strbuf_addstr(&script_snippet,
891d4a03 1194 "GIT_SEQUENCE_EDITOR=:; export GIT_SEQUENCE_EDITOR; ");
3dba9d08
PK
1195 opts->autosquash = 0;
1196 }
ac7f467f
PK
1197
1198 switch (opts->type) {
1199 case REBASE_AM:
1200 backend = "git-rebase--am";
1201 backend_func = "git_rebase__am";
1202 break;
ac7f467f
PK
1203 case REBASE_PRESERVE_MERGES:
1204 backend = "git-rebase--preserve-merges";
1205 backend_func = "git_rebase__preserve_merges";
1206 break;
1207 default:
1208 BUG("Unhandled rebase type %d", opts->type);
1209 break;
1210 }
1211
1212 strbuf_addf(&script_snippet,
1213 ". git-sh-setup && . git-rebase--common &&"
1214 " . %s && %s", backend, backend_func);
1215 argv[0] = script_snippet.buf;
1216
1217 status = run_command_v_opt(argv, RUN_USING_SHELL);
bc24382c 1218finished_rebase:
ac7f467f
PK
1219 if (opts->dont_finish_rebase)
1220 ; /* do nothing */
bc24382c
JS
1221 else if (opts->type == REBASE_INTERACTIVE)
1222 ; /* interactive rebase cleans up after itself */
ac7f467f
PK
1223 else if (status == 0) {
1224 if (!file_exists(state_dir_path("stopped-sha", opts)))
1225 finish_rebase(opts);
1226 } else if (status == 2) {
1227 struct strbuf dir = STRBUF_INIT;
1228
6defce2b 1229 apply_autostash(opts);
ac7f467f
PK
1230 strbuf_addstr(&dir, opts->state_dir);
1231 remove_dir_recursively(&dir, 0);
1232 strbuf_release(&dir);
1233 die("Nothing to do");
1234 }
1235
1236 strbuf_release(&script_snippet);
1237
1238 return status ? -1 : 0;
1239}
1240
bff014da
PK
1241static int rebase_config(const char *var, const char *value, void *data)
1242{
1243 struct rebase_options *opts = data;
1244
1245 if (!strcmp(var, "rebase.stat")) {
1246 if (git_config_bool(var, value))
1247 opts->flags |= REBASE_DIFFSTAT;
1248 else
1249 opts->flags &= !REBASE_DIFFSTAT;
1250 return 0;
1251 }
1252
051910a9
PK
1253 if (!strcmp(var, "rebase.autosquash")) {
1254 opts->autosquash = git_config_bool(var, value);
1255 return 0;
1256 }
1257
12026a41
PK
1258 if (!strcmp(var, "commit.gpgsign")) {
1259 free(opts->gpg_sign_opt);
1260 opts->gpg_sign_opt = git_config_bool(var, value) ?
1261 xstrdup("-S") : NULL;
1262 return 0;
1263 }
1264
6defce2b
PK
1265 if (!strcmp(var, "rebase.autostash")) {
1266 opts->autostash = git_config_bool(var, value);
1267 return 0;
1268 }
1269
969de3ff
JS
1270 if (!strcmp(var, "rebase.reschedulefailedexec")) {
1271 opts->reschedule_failed_exec = git_config_bool(var, value);
1272 return 0;
1273 }
1274
bff014da
PK
1275 return git_default_config(var, value, data);
1276}
1277
9a48a615
PK
1278/*
1279 * Determines whether the commits in from..to are linear, i.e. contain
1280 * no merge commits. This function *expects* `from` to be an ancestor of
1281 * `to`.
1282 */
1283static int is_linear_history(struct commit *from, struct commit *to)
1284{
1285 while (to && to != from) {
1286 parse_commit(to);
1287 if (!to->parents)
1288 return 1;
1289 if (to->parents->next)
1290 return 0;
1291 to = to->parents->item;
1292 }
1293 return 1;
1294}
1295
1296static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
1297 struct object_id *merge_base)
1298{
1299 struct commit *head = lookup_commit(the_repository, head_oid);
1300 struct commit_list *merge_bases;
1301 int res;
1302
1303 if (!head)
1304 return 0;
1305
1306 merge_bases = get_merge_bases(onto, head);
1307 if (merge_bases && !merge_bases->next) {
1308 oidcpy(merge_base, &merge_bases->item->object.oid);
b17ca8f9 1309 res = oideq(merge_base, &onto->object.oid);
9a48a615
PK
1310 } else {
1311 oidcpy(merge_base, &null_oid);
1312 res = 0;
1313 }
1314 free_commit_list(merge_bases);
1315 return res && is_linear_history(onto, head);
1316}
1317
361badd3
PK
1318/* -i followed by -m is still -i */
1319static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
1320{
1321 struct rebase_options *opts = opt->value;
1322
517fe807
JK
1323 BUG_ON_OPT_NEG(unset);
1324 BUG_ON_OPT_ARG(arg);
1325
361badd3
PK
1326 if (!is_interactive(opts))
1327 opts->type = REBASE_MERGE;
1328
1329 return 0;
1330}
1331
1332/* -i followed by -p is still explicitly interactive, but -p alone is not */
1333static int parse_opt_interactive(const struct option *opt, const char *arg,
1334 int unset)
1335{
1336 struct rebase_options *opts = opt->value;
1337
517fe807
JK
1338 BUG_ON_OPT_NEG(unset);
1339 BUG_ON_OPT_ARG(arg);
1340
361badd3
PK
1341 opts->type = REBASE_INTERACTIVE;
1342 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
1343
1344 return 0;
1345}
1346
8f5986d9
PK
1347static void NORETURN error_on_missing_default_upstream(void)
1348{
1349 struct branch *current_branch = branch_get(NULL);
1350
1351 printf(_("%s\n"
1352 "Please specify which branch you want to rebase against.\n"
1353 "See git-rebase(1) for details.\n"
1354 "\n"
1355 " git rebase '<branch>'\n"
1356 "\n"),
1357 current_branch ? _("There is no tracking information for "
1358 "the current branch.") :
1359 _("You are not currently on a branch."));
1360
1361 if (current_branch) {
1362 const char *remote = current_branch->remote_name;
1363
1364 if (!remote)
1365 remote = _("<remote>");
1366
1367 printf(_("If you wish to set tracking information for this "
1368 "branch you can do so with:\n"
1369 "\n"
1370 " git branch --set-upstream-to=%s/<branch> %s\n"
1371 "\n"),
1372 remote, current_branch->name);
1373 }
1374 exit(1);
1375}
1376
13a5a9f0
JS
1377static void set_reflog_action(struct rebase_options *options)
1378{
1379 const char *env;
1380 struct strbuf buf = STRBUF_INIT;
1381
1382 if (!is_interactive(options))
1383 return;
1384
1385 env = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
1386 if (env && strcmp("rebase", env))
1387 return; /* only override it if it is "rebase" */
1388
1389 strbuf_addf(&buf, "rebase -i (%s)", options->action);
1390 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, buf.buf, 1);
1391 strbuf_release(&buf);
1392}
1393
c762aada
PW
1394static int check_exec_cmd(const char *cmd)
1395{
1396 if (strchr(cmd, '\n'))
1397 return error(_("exec commands cannot contain newlines"));
1398
1399 /* Does the command consist purely of whitespace? */
1400 if (!cmd[strspn(cmd, " \t\r\f\v")])
1401 return error(_("empty exec command"));
1402
1403 return 0;
1404}
1405
1406
55071ea2
PK
1407int cmd_rebase(int argc, const char **argv, const char *prefix)
1408{
73fdc535 1409 struct rebase_options options = REBASE_OPTIONS_INIT;
ac7f467f 1410 const char *branch_name;
f9573628 1411 int ret, flags, total_argc, in_progress = 0;
06e4775a 1412 int ok_to_skip_pre_rebase = 0;
ac7f467f
PK
1413 struct strbuf msg = STRBUF_INIT;
1414 struct strbuf revisions = STRBUF_INIT;
c54dacb5 1415 struct strbuf buf = STRBUF_INIT;
075bc852 1416 struct object_id merge_base;
f9573628
PK
1417 enum {
1418 NO_ACTION,
1419 ACTION_CONTINUE,
122420c2 1420 ACTION_SKIP,
5e5d9619 1421 ACTION_ABORT,
5a614945 1422 ACTION_QUIT,
51e9ea6d
PK
1423 ACTION_EDIT_TODO,
1424 ACTION_SHOW_CURRENT_PATCH,
f9573628 1425 } action = NO_ACTION;
146839c4
PW
1426 static const char *action_names[] = { "undefined",
1427 "continue",
1428 "skip",
1429 "abort",
1430 "quit",
1431 "edit_todo",
1432 "show_current_patch" };
12026a41 1433 const char *gpg_sign = NULL;
68e46d78 1434 struct string_list exec = STRING_LIST_INIT_NODUP;
3c3588c7 1435 const char *rebase_merges = NULL;
92d0d74e 1436 int fork_point = -1;
ba1905a5 1437 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
9dba809a
PK
1438 struct object_id squash_onto;
1439 char *squash_onto_name = NULL;
f28d40d3
PK
1440 struct option builtin_rebase_options[] = {
1441 OPT_STRING(0, "onto", &options.onto_name,
1442 N_("revision"),
1443 N_("rebase onto given branch instead of upstream")),
06e4775a
PK
1444 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
1445 N_("allow pre-rebase hook to run")),
b4c8eb02
PK
1446 OPT_NEGBIT('q', "quiet", &options.flags,
1447 N_("be quiet. implies --no-stat"),
bff014da
PK
1448 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
1449 OPT_BIT('v', "verbose", &options.flags,
1450 N_("display a diffstat of what changed upstream"),
1451 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
1452 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
1453 N_("do not show diffstat of what changed upstream"),
1454 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
73d51ed0
PK
1455 OPT_BOOL(0, "signoff", &options.signoff,
1456 N_("add a Signed-off-by: line to each commit")),
f5769680
JS
1457 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &options.git_am_opts,
1458 NULL, N_("passed to 'git am'"),
1459 PARSE_OPT_NOARG),
1460 OPT_PASSTHRU_ARGV(0, "committer-date-is-author-date",
1461 &options.git_am_opts, NULL,
1462 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1463 OPT_PASSTHRU_ARGV(0, "ignore-date", &options.git_am_opts, NULL,
1464 N_("passed to 'git am'"), PARSE_OPT_NOARG),
1465 OPT_PASSTHRU_ARGV('C', NULL, &options.git_am_opts, N_("n"),
1466 N_("passed to 'git apply'"), 0),
1467 OPT_PASSTHRU_ARGV(0, "whitespace", &options.git_am_opts,
1468 N_("action"), N_("passed to 'git apply'"), 0),
1ed9c14f
PK
1469 OPT_BIT('f', "force-rebase", &options.flags,
1470 N_("cherry-pick all commits, even if unchanged"),
1471 REBASE_FORCE),
1472 OPT_BIT(0, "no-ff", &options.flags,
1473 N_("cherry-pick all commits, even if unchanged"),
1474 REBASE_FORCE),
f9573628
PK
1475 OPT_CMDMODE(0, "continue", &action, N_("continue"),
1476 ACTION_CONTINUE),
122420c2
PK
1477 OPT_CMDMODE(0, "skip", &action,
1478 N_("skip current patch and continue"), ACTION_SKIP),
5e5d9619
PK
1479 OPT_CMDMODE(0, "abort", &action,
1480 N_("abort and check out the original branch"),
1481 ACTION_ABORT),
5a614945
PK
1482 OPT_CMDMODE(0, "quit", &action,
1483 N_("abort but keep HEAD where it is"), ACTION_QUIT),
51e9ea6d
PK
1484 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
1485 "during an interactive rebase"), ACTION_EDIT_TODO),
1486 OPT_CMDMODE(0, "show-current-patch", &action,
1487 N_("show the patch file being applied or merged"),
1488 ACTION_SHOW_CURRENT_PATCH),
361badd3
PK
1489 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
1490 N_("use merging strategies to rebase"),
1491 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1492 parse_opt_merge },
1493 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
1494 N_("let the user edit the list of commits to rebase"),
1495 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1496 parse_opt_interactive },
1497 OPT_SET_INT('p', "preserve-merges", &options.type,
1498 N_("try to recreate merges instead of ignoring "
1499 "them"), REBASE_PRESERVE_MERGES),
6023c928 1500 OPT_RERERE_AUTOUPDATE(&options.allow_rerere_autoupdate),
002ee2fe
PK
1501 OPT_BOOL('k', "keep-empty", &options.keep_empty,
1502 N_("preserve empty commits during rebase")),
051910a9
PK
1503 OPT_BOOL(0, "autosquash", &options.autosquash,
1504 N_("move commits that begin with "
1505 "squash!/fixup! under -i")),
12026a41
PK
1506 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
1507 N_("GPG-sign commits"),
1508 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
6defce2b
PK
1509 OPT_BOOL(0, "autostash", &options.autostash,
1510 N_("automatically stash/stash pop before and after")),
68e46d78
PK
1511 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
1512 N_("add exec lines after each commit of the "
1513 "editable list")),
9b3a448b
PK
1514 OPT_BOOL(0, "allow-empty-message",
1515 &options.allow_empty_message,
1516 N_("allow rebasing commits with empty messages")),
3c3588c7
PK
1517 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
1518 N_("mode"),
1519 N_("try to rebase merges instead of skipping them"),
1520 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
92d0d74e
PK
1521 OPT_BOOL(0, "fork-point", &fork_point,
1522 N_("use 'merge-base --fork-point' to refine upstream")),
ba1905a5
PK
1523 OPT_STRING('s', "strategy", &options.strategy,
1524 N_("strategy"), N_("use the given merge strategy")),
1525 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
1526 N_("option"),
1527 N_("pass the argument through to the merge "
1528 "strategy")),
9dba809a
PK
1529 OPT_BOOL(0, "root", &options.root,
1530 N_("rebase all reachable commits up to the root(s)")),
d421afa0
JS
1531 OPT_BOOL(0, "reschedule-failed-exec",
1532 &options.reschedule_failed_exec,
1533 N_("automatically re-schedule any `exec` that fails")),
f28d40d3
PK
1534 OPT_END(),
1535 };
f5769680 1536 int i;
ac7f467f 1537
55071ea2
PK
1538 /*
1539 * NEEDSWORK: Once the builtin rebase has been tested enough
1540 * and git-legacy-rebase.sh is retired to contrib/, this preamble
1541 * can be removed.
1542 */
1543
1544 if (!use_builtin_rebase()) {
1545 const char *path = mkpath("%s/git-legacy-rebase",
1546 git_exec_path());
1547
1548 if (sane_execvp(path, (char **)argv) < 0)
1549 die_errno(_("could not exec %s"), path);
1550 else
1551 BUG("sane_execvp() returned???");
1552 }
1553
f28d40d3
PK
1554 if (argc == 2 && !strcmp(argv[1], "-h"))
1555 usage_with_options(builtin_rebase_usage,
1556 builtin_rebase_options);
1557
55071ea2
PK
1558 prefix = setup_git_directory();
1559 trace_repo_setup(prefix);
1560 setup_work_tree();
1561
73fdc535 1562 options.allow_empty_message = 1;
bff014da
PK
1563 git_config(rebase_config, &options);
1564
0eabf4b9
PK
1565 strbuf_reset(&buf);
1566 strbuf_addf(&buf, "%s/applying", apply_dir());
1567 if(file_exists(buf.buf))
1568 die(_("It looks like 'git am' is in progress. Cannot rebase."));
1569
c54dacb5
PK
1570 if (is_directory(apply_dir())) {
1571 options.type = REBASE_AM;
1572 options.state_dir = apply_dir();
1573 } else if (is_directory(merge_dir())) {
1574 strbuf_reset(&buf);
1575 strbuf_addf(&buf, "%s/rewritten", merge_dir());
1576 if (is_directory(buf.buf)) {
1577 options.type = REBASE_PRESERVE_MERGES;
1578 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1579 } else {
1580 strbuf_reset(&buf);
1581 strbuf_addf(&buf, "%s/interactive", merge_dir());
1582 if(file_exists(buf.buf)) {
1583 options.type = REBASE_INTERACTIVE;
1584 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
1585 } else
1586 options.type = REBASE_MERGE;
1587 }
1588 options.state_dir = merge_dir();
1589 }
1590
1591 if (options.type != REBASE_UNSPECIFIED)
1592 in_progress = 1;
1593
f9573628 1594 total_argc = argc;
f28d40d3
PK
1595 argc = parse_options(argc, argv, prefix,
1596 builtin_rebase_options,
1597 builtin_rebase_usage, 0);
1598
f9573628
PK
1599 if (action != NO_ACTION && total_argc != 2) {
1600 usage_with_options(builtin_rebase_usage,
1601 builtin_rebase_options);
1602 }
1603
f28d40d3
PK
1604 if (argc > 2)
1605 usage_with_options(builtin_rebase_usage,
1606 builtin_rebase_options);
ac7f467f 1607
d732a570
PK
1608 if (action != NO_ACTION && !in_progress)
1609 die(_("No rebase in progress?"));
13a5a9f0 1610 setenv(GIT_REFLOG_ACTION_ENVIRONMENT, "rebase", 0);
d732a570 1611
51e9ea6d
PK
1612 if (action == ACTION_EDIT_TODO && !is_interactive(&options))
1613 die(_("The --edit-todo action can only be used during "
1614 "interactive rebase."));
1615
b3a5d5a8
JH
1616 if (trace2_is_enabled()) {
1617 if (is_interactive(&options))
1618 trace2_cmd_mode("interactive");
1619 else if (exec.nr)
1620 trace2_cmd_mode("interactive-exec");
1621 else
1622 trace2_cmd_mode(action_names[action]);
1623 }
1624
f9573628
PK
1625 switch (action) {
1626 case ACTION_CONTINUE: {
1627 struct object_id head;
1628 struct lock_file lock_file = LOCK_INIT;
1629 int fd;
1630
1631 options.action = "continue";
13a5a9f0 1632 set_reflog_action(&options);
f9573628
PK
1633
1634 /* Sanity check */
1635 if (get_oid("HEAD", &head))
1636 die(_("Cannot read HEAD"));
1637
1638 fd = hold_locked_index(&lock_file, 0);
e1ff0a32 1639 if (repo_read_index(the_repository) < 0)
f9573628
PK
1640 die(_("could not read index"));
1641 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
1642 NULL);
1643 if (0 <= fd)
1b0d968b 1644 repo_update_index_if_able(the_repository, &lock_file);
f9573628
PK
1645 rollback_lock_file(&lock_file);
1646
5b02ca38 1647 if (has_unstaged_changes(the_repository, 1)) {
f9573628
PK
1648 puts(_("You must edit all merge conflicts and then\n"
1649 "mark them as resolved using git add"));
1650 exit(1);
1651 }
1652 if (read_basic_state(&options))
1653 exit(1);
1654 goto run_rebase;
1655 }
122420c2
PK
1656 case ACTION_SKIP: {
1657 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1658
1659 options.action = "skip";
13a5a9f0 1660 set_reflog_action(&options);
122420c2 1661
55e6b354 1662 rerere_clear(the_repository, &merge_rr);
122420c2
PK
1663 string_list_clear(&merge_rr, 1);
1664
bac2a1e3
JS
1665 if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
1666 NULL, NULL) < 0)
122420c2 1667 die(_("could not discard worktree changes"));
cde55548 1668 remove_branch_state(the_repository);
122420c2
PK
1669 if (read_basic_state(&options))
1670 exit(1);
1671 goto run_rebase;
1672 }
5e5d9619
PK
1673 case ACTION_ABORT: {
1674 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1675 options.action = "abort";
13a5a9f0 1676 set_reflog_action(&options);
5e5d9619 1677
55e6b354 1678 rerere_clear(the_repository, &merge_rr);
5e5d9619
PK
1679 string_list_clear(&merge_rr, 1);
1680
1681 if (read_basic_state(&options))
1682 exit(1);
1683 if (reset_head(&options.orig_head, "reset",
bac2a1e3
JS
1684 options.head_name, RESET_HEAD_HARD,
1685 NULL, NULL) < 0)
5e5d9619
PK
1686 die(_("could not move back to %s"),
1687 oid_to_hex(&options.orig_head));
cde55548 1688 remove_branch_state(the_repository);
5e5d9619
PK
1689 ret = finish_rebase(&options);
1690 goto cleanup;
1691 }
5a614945
PK
1692 case ACTION_QUIT: {
1693 strbuf_reset(&buf);
1694 strbuf_addstr(&buf, options.state_dir);
1695 ret = !!remove_dir_recursively(&buf, 0);
1696 if (ret)
1697 die(_("could not remove '%s'"), options.state_dir);
1698 goto cleanup;
1699 }
51e9ea6d
PK
1700 case ACTION_EDIT_TODO:
1701 options.action = "edit-todo";
1702 options.dont_finish_rebase = 1;
1703 goto run_rebase;
1704 case ACTION_SHOW_CURRENT_PATCH:
1705 options.action = "show-current-patch";
1706 options.dont_finish_rebase = 1;
1707 goto run_rebase;
1708 case NO_ACTION:
1709 break;
f9573628 1710 default:
51e9ea6d 1711 BUG("action: %d", action);
f9573628
PK
1712 }
1713
c54dacb5
PK
1714 /* Make sure no rebase is in progress */
1715 if (in_progress) {
1716 const char *last_slash = strrchr(options.state_dir, '/');
1717 const char *state_dir_base =
1718 last_slash ? last_slash + 1 : options.state_dir;
1719 const char *cmd_live_rebase =
1720 "git rebase (--continue | --abort | --skip)";
1721 strbuf_reset(&buf);
1722 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1723 die(_("It seems that there is already a %s directory, and\n"
1724 "I wonder if you are in the middle of another rebase. "
1725 "If that is the\n"
1726 "case, please try\n\t%s\n"
1727 "If that is not the case, please\n\t%s\n"
1728 "and run me again. I am stopping in case you still "
1729 "have something\n"
1730 "valuable there.\n"),
1731 state_dir_base, cmd_live_rebase, buf.buf);
1732 }
1733
f5769680 1734 for (i = 0; i < options.git_am_opts.argc; i++) {
04519d72 1735 const char *option = options.git_am_opts.argv[i], *p;
f5769680
JS
1736 if (!strcmp(option, "--committer-date-is-author-date") ||
1737 !strcmp(option, "--ignore-date") ||
1738 !strcmp(option, "--whitespace=fix") ||
1739 !strcmp(option, "--whitespace=strip"))
1740 options.flags |= REBASE_FORCE;
04519d72
JS
1741 else if (skip_prefix(option, "-C", &p)) {
1742 while (*p)
1743 if (!isdigit(*(p++)))
1744 die(_("switch `C' expects a "
1745 "numerical value"));
1746 } else if (skip_prefix(option, "--whitespace=", &p)) {
1747 if (*p && strcmp(p, "warn") && strcmp(p, "nowarn") &&
1748 strcmp(p, "error") && strcmp(p, "error-all"))
1749 die("Invalid whitespace option: '%s'", p);
1750 }
38dbcef2
PK
1751 }
1752
c762aada
PW
1753 for (i = 0; i < exec.nr; i++)
1754 if (check_exec_cmd(exec.items[i].string))
1755 exit(1);
1756
f5769680
JS
1757 if (!(options.flags & REBASE_NO_QUIET))
1758 argv_array_push(&options.git_am_opts, "-q");
53f9e5be 1759
002ee2fe
PK
1760 if (options.keep_empty)
1761 imply_interactive(&options, "--keep-empty");
1762
12026a41
PK
1763 if (gpg_sign) {
1764 free(options.gpg_sign_opt);
1765 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1766 }
1767
68e46d78
PK
1768 if (exec.nr) {
1769 int i;
1770
1771 imply_interactive(&options, "--exec");
1772
1773 strbuf_reset(&buf);
1774 for (i = 0; i < exec.nr; i++)
1775 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1776 options.cmd = xstrdup(buf.buf);
1777 }
1778
3c3588c7
PK
1779 if (rebase_merges) {
1780 if (!*rebase_merges)
1781 ; /* default mode; do nothing */
1782 else if (!strcmp("rebase-cousins", rebase_merges))
1783 options.rebase_cousins = 1;
1784 else if (strcmp("no-rebase-cousins", rebase_merges))
1785 die(_("Unknown mode: %s"), rebase_merges);
1786 options.rebase_merges = 1;
1787 imply_interactive(&options, "--rebase-merges");
1788 }
1789
ba1905a5
PK
1790 if (strategy_options.nr) {
1791 int i;
1792
1793 if (!options.strategy)
1794 options.strategy = "recursive";
1795
1796 strbuf_reset(&buf);
1797 for (i = 0; i < strategy_options.nr; i++)
1798 strbuf_addf(&buf, " --%s",
1799 strategy_options.items[i].string);
1800 options.strategy_opts = xstrdup(buf.buf);
1801 }
1802
1803 if (options.strategy) {
1804 options.strategy = xstrdup(options.strategy);
1805 switch (options.type) {
1806 case REBASE_AM:
1807 die(_("--strategy requires --merge or --interactive"));
1808 case REBASE_MERGE:
1809 case REBASE_INTERACTIVE:
1810 case REBASE_PRESERVE_MERGES:
1811 /* compatible */
1812 break;
1813 case REBASE_UNSPECIFIED:
1814 options.type = REBASE_MERGE;
1815 break;
1816 default:
1817 BUG("unhandled rebase type (%d)", options.type);
1818 }
1819 }
1820
68aa495b
EN
1821 if (options.type == REBASE_MERGE)
1822 imply_interactive(&options, "--merge");
1823
9dba809a
PK
1824 if (options.root && !options.onto_name)
1825 imply_interactive(&options, "--root without --onto");
1826
cda614e4
PK
1827 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1828 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1829
ac7f467f
PK
1830 switch (options.type) {
1831 case REBASE_MERGE:
1832 case REBASE_INTERACTIVE:
1833 case REBASE_PRESERVE_MERGES:
1834 options.state_dir = merge_dir();
1835 break;
1836 case REBASE_AM:
1837 options.state_dir = apply_dir();
1838 break;
1839 default:
1840 /* the default rebase backend is `--am` */
1841 options.type = REBASE_AM;
1842 options.state_dir = apply_dir();
1843 break;
1844 }
1845
d421afa0 1846 if (options.reschedule_failed_exec && !is_interactive(&options))
32ceace3 1847 die(_("%s requires an interactive rebase"), "--reschedule-failed-exec");
d421afa0 1848
f5769680 1849 if (options.git_am_opts.argc) {
b361bd75 1850 /* all am options except -q are compatible only with --am */
f5769680
JS
1851 for (i = options.git_am_opts.argc - 1; i >= 0; i--)
1852 if (strcmp(options.git_am_opts.argv[i], "-q"))
1853 break;
b361bd75 1854
f5769680 1855 if (is_interactive(&options) && i >= 0)
68aa495b
EN
1856 die(_("cannot combine am options with either "
1857 "interactive or merge options"));
b361bd75
PK
1858 }
1859
73d51ed0
PK
1860 if (options.signoff) {
1861 if (options.type == REBASE_PRESERVE_MERGES)
1862 die("cannot combine '--signoff' with "
1863 "'--preserve-merges'");
f5769680 1864 argv_array_push(&options.git_am_opts, "--signoff");
73d51ed0
PK
1865 options.flags |= REBASE_FORCE;
1866 }
1867
d421afa0 1868 if (options.type == REBASE_PRESERVE_MERGES) {
b361bd75
PK
1869 /*
1870 * Note: incompatibility with --signoff handled in signoff block above
1871 * Note: incompatibility with --interactive is just a strong warning;
1872 * git-rebase.txt caveats with "unless you know what you are doing"
1873 */
1874 if (options.rebase_merges)
c913c596 1875 die(_("cannot combine '--preserve-merges' with "
b361bd75
PK
1876 "'--rebase-merges'"));
1877
d421afa0
JS
1878 if (options.reschedule_failed_exec)
1879 die(_("error: cannot combine '--preserve-merges' with "
1880 "'--reschedule-failed-exec'"));
1881 }
1882
b361bd75
PK
1883 if (options.rebase_merges) {
1884 if (strategy_options.nr)
c913c596 1885 die(_("cannot combine '--rebase-merges' with "
b361bd75
PK
1886 "'--strategy-option'"));
1887 if (options.strategy)
c913c596 1888 die(_("cannot combine '--rebase-merges' with "
b361bd75
PK
1889 "'--strategy'"));
1890 }
1891
ac7f467f 1892 if (!options.root) {
8f5986d9
PK
1893 if (argc < 1) {
1894 struct branch *branch;
1895
1896 branch = branch_get(NULL);
1897 options.upstream_name = branch_get_upstream(branch,
1898 NULL);
1899 if (!options.upstream_name)
1900 error_on_missing_default_upstream();
1901 if (fork_point < 0)
1902 fork_point = 1;
1903 } else {
f28d40d3 1904 options.upstream_name = argv[0];
ac7f467f
PK
1905 argc--;
1906 argv++;
1907 if (!strcmp(options.upstream_name, "-"))
1908 options.upstream_name = "@{-1}";
1909 }
1910 options.upstream = peel_committish(options.upstream_name);
1911 if (!options.upstream)
1912 die(_("invalid upstream '%s'"), options.upstream_name);
06e4775a 1913 options.upstream_arg = options.upstream_name;
9dba809a
PK
1914 } else {
1915 if (!options.onto_name) {
1916 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1917 &squash_onto, NULL, NULL) < 0)
1918 die(_("Could not create new root commit"));
1919 options.squash_onto = &squash_onto;
1920 options.onto_name = squash_onto_name =
1921 xstrdup(oid_to_hex(&squash_onto));
1922 }
1923 options.upstream_name = NULL;
1924 options.upstream = NULL;
1925 if (argc > 1)
1926 usage_with_options(builtin_rebase_usage,
1927 builtin_rebase_options);
1928 options.upstream_arg = "--root";
1929 }
ac7f467f
PK
1930
1931 /* Make sure the branch to rebase onto is valid. */
1932 if (!options.onto_name)
1933 options.onto_name = options.upstream_name;
1934 if (strstr(options.onto_name, "...")) {
075bc852
PK
1935 if (get_oid_mb(options.onto_name, &merge_base) < 0)
1936 die(_("'%s': need exactly one merge base"),
1937 options.onto_name);
1938 options.onto = lookup_commit_or_die(&merge_base,
1939 options.onto_name);
ac7f467f
PK
1940 } else {
1941 options.onto = peel_committish(options.onto_name);
1942 if (!options.onto)
1943 die(_("Does not point to a valid commit '%s'"),
1944 options.onto_name);
1945 }
1946
1947 /*
1948 * If the branch to rebase is given, that is the branch we will rebase
1949 * branch_name -- branch/commit being rebased, or
1950 * HEAD (already detached)
1951 * orig_head -- commit object name of tip of the branch before rebasing
d4c569f8 1952 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
ac7f467f 1953 */
e65123a7
PK
1954 if (argc == 1) {
1955 /* Is it "rebase other branchname" or "rebase other commit"? */
1956 branch_name = argv[0];
1957 options.switch_to = argv[0];
1958
1959 /* Is it a local branch? */
1960 strbuf_reset(&buf);
1961 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1962 if (!read_ref(buf.buf, &options.orig_head))
1963 options.head_name = xstrdup(buf.buf);
1964 /* If not is it a valid ref (branch or commit)? */
1965 else if (!get_oid(branch_name, &options.orig_head))
1966 options.head_name = NULL;
1967 else
1968 die(_("fatal: no such branch/commit '%s'"),
1969 branch_name);
1970 } else if (argc == 0) {
ac7f467f
PK
1971 /* Do not need to switch branches, we are already on it. */
1972 options.head_name =
1973 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1974 &flags));
1975 if (!options.head_name)
1976 die(_("No such ref: %s"), "HEAD");
1977 if (flags & REF_ISSYMREF) {
1978 if (!skip_prefix(options.head_name,
1979 "refs/heads/", &branch_name))
1980 branch_name = options.head_name;
1981
1982 } else {
d4c569f8
PK
1983 free(options.head_name);
1984 options.head_name = NULL;
ac7f467f
PK
1985 branch_name = "HEAD";
1986 }
1987 if (get_oid("HEAD", &options.orig_head))
1988 die(_("Could not resolve HEAD to a revision"));
e65123a7
PK
1989 } else
1990 BUG("unexpected number of arguments left to parse");
ac7f467f 1991
92d0d74e
PK
1992 if (fork_point > 0) {
1993 struct commit *head =
1994 lookup_commit_reference(the_repository,
1995 &options.orig_head);
1996 options.restrict_revision =
1997 get_fork_point(options.upstream_name, head);
1998 }
1999
e1ff0a32 2000 if (repo_read_index(the_repository) < 0)
e0333e5c
PK
2001 die(_("could not read index"));
2002
6defce2b
PK
2003 if (options.autostash) {
2004 struct lock_file lock_file = LOCK_INIT;
2005 int fd;
2006
2007 fd = hold_locked_index(&lock_file, 0);
2008 refresh_cache(REFRESH_QUIET);
2009 if (0 <= fd)
1b0d968b 2010 repo_update_index_if_able(the_repository, &lock_file);
6defce2b
PK
2011 rollback_lock_file(&lock_file);
2012
5b02ca38
NTND
2013 if (has_unstaged_changes(the_repository, 1) ||
2014 has_uncommitted_changes(the_repository, 1)) {
6defce2b
PK
2015 const char *autostash =
2016 state_dir_path("autostash", &options);
2017 struct child_process stash = CHILD_PROCESS_INIT;
2018 struct object_id oid;
2019 struct commit *head =
2020 lookup_commit_reference(the_repository,
2021 &options.orig_head);
2022
2023 argv_array_pushl(&stash.args,
2024 "stash", "create", "autostash", NULL);
2025 stash.git_cmd = 1;
2026 stash.no_stdin = 1;
2027 strbuf_reset(&buf);
2028 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
2029 die(_("Cannot autostash"));
2030 strbuf_trim_trailing_newline(&buf);
2031 if (get_oid(buf.buf, &oid))
2032 die(_("Unexpected stash response: '%s'"),
2033 buf.buf);
2034 strbuf_reset(&buf);
2035 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
2036
2037 if (safe_create_leading_directories_const(autostash))
2038 die(_("Could not create directory for '%s'"),
2039 options.state_dir);
12aeb00a 2040 write_file(autostash, "%s", oid_to_hex(&oid));
6defce2b
PK
2041 printf(_("Created autostash: %s\n"), buf.buf);
2042 if (reset_head(&head->object.oid, "reset --hard",
bac2a1e3 2043 NULL, RESET_HEAD_HARD, NULL, NULL) < 0)
6defce2b
PK
2044 die(_("could not reset --hard"));
2045 printf(_("HEAD is now at %s"),
2046 find_unique_abbrev(&head->object.oid,
2047 DEFAULT_ABBREV));
2048 strbuf_reset(&buf);
2049 pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
2050 if (buf.len > 0)
2051 printf(" %s", buf.buf);
2052 putchar('\n');
2053
2054 if (discard_index(the_repository->index) < 0 ||
e1ff0a32 2055 repo_read_index(the_repository) < 0)
6defce2b
PK
2056 die(_("could not read index"));
2057 }
2058 }
2059
5b02ca38 2060 if (require_clean_work_tree(the_repository, "rebase",
e0333e5c
PK
2061 _("Please commit or stash them."), 1, 1)) {
2062 ret = 1;
2063 goto cleanup;
ac7f467f
PK
2064 }
2065
9a48a615
PK
2066 /*
2067 * Now we are rebasing commits upstream..orig_head (or with --root,
2068 * everything leading up to orig_head) on top of onto.
2069 */
2070
2071 /*
2072 * Check if we are already based on onto with linear history,
2073 * but this should be done only when upstream and onto are the same
2074 * and if this is not an interactive rebase.
2075 */
2076 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
2077 !is_interactive(&options) && !options.restrict_revision &&
9dba809a 2078 options.upstream &&
9a48a615
PK
2079 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
2080 int flag;
2081
1ed9c14f 2082 if (!(options.flags & REBASE_FORCE)) {
e65123a7
PK
2083 /* Lazily switch to the target branch if needed... */
2084 if (options.switch_to) {
2085 struct object_id oid;
2086
2087 if (get_oid(options.switch_to, &oid) < 0) {
2088 ret = !!error(_("could not parse '%s'"),
2089 options.switch_to);
2090 goto cleanup;
2091 }
2092
2093 strbuf_reset(&buf);
13a5a9f0
JS
2094 strbuf_addf(&buf, "%s: checkout %s",
2095 getenv(GIT_REFLOG_ACTION_ENVIRONMENT),
e65123a7
PK
2096 options.switch_to);
2097 if (reset_head(&oid, "checkout",
8581df65
OS
2098 options.head_name,
2099 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
13a5a9f0 2100 NULL, buf.buf) < 0) {
e65123a7
PK
2101 ret = !!error(_("could not switch to "
2102 "%s"),
2103 options.switch_to);
2104 goto cleanup;
2105 }
2106 }
2107
1ed9c14f
PK
2108 if (!(options.flags & REBASE_NO_QUIET))
2109 ; /* be quiet */
2110 else if (!strcmp(branch_name, "HEAD") &&
2111 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2112 puts(_("HEAD is up to date."));
2113 else
2114 printf(_("Current branch %s is up to date.\n"),
2115 branch_name);
2116 ret = !!finish_rebase(&options);
2117 goto cleanup;
2118 } else if (!(options.flags & REBASE_NO_QUIET))
9a48a615
PK
2119 ; /* be quiet */
2120 else if (!strcmp(branch_name, "HEAD") &&
2121 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
2122 puts(_("HEAD is up to date, rebase forced."));
2123 else
2124 printf(_("Current branch %s is up to date, rebase "
2125 "forced.\n"), branch_name);
2126 }
2127
06e4775a
PK
2128 /* If a hook exists, give it a chance to interrupt*/
2129 if (!ok_to_skip_pre_rebase &&
2130 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
2131 argc ? argv[0] : NULL, NULL))
2132 die(_("The pre-rebase hook refused to rebase."));
2133
bff014da
PK
2134 if (options.flags & REBASE_DIFFSTAT) {
2135 struct diff_options opts;
2136
8797f0f0
JS
2137 if (options.flags & REBASE_VERBOSE) {
2138 if (is_null_oid(&merge_base))
2139 printf(_("Changes to %s:\n"),
2140 oid_to_hex(&options.onto->object.oid));
2141 else
2142 printf(_("Changes from %s to %s:\n"),
2143 oid_to_hex(&merge_base),
2144 oid_to_hex(&options.onto->object.oid));
2145 }
bff014da
PK
2146
2147 /* We want color (if set), but no pager */
2148 diff_setup(&opts);
2149 opts.stat_width = -1; /* use full terminal width */
2150 opts.stat_graph_width = -1; /* respect statGraphWidth config */
2151 opts.output_format |=
2152 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
2153 opts.detect_rename = DIFF_DETECT_RENAME;
2154 diff_setup_done(&opts);
8797f0f0
JS
2155 diff_tree_oid(is_null_oid(&merge_base) ?
2156 the_hash_algo->empty_tree : &merge_base,
2157 &options.onto->object.oid, "", &opts);
bff014da
PK
2158 diffcore_std(&opts);
2159 diff_flush(&opts);
2160 }
2161
361badd3
PK
2162 if (is_interactive(&options))
2163 goto run_rebase;
2164
bff014da
PK
2165 /* Detach HEAD and reset the tree */
2166 if (options.flags & REBASE_NO_QUIET)
2167 printf(_("First, rewinding head to replay your work on top of "
2168 "it...\n"));
2169
13a5a9f0
JS
2170 strbuf_addf(&msg, "%s: checkout %s",
2171 getenv(GIT_REFLOG_ACTION_ENVIRONMENT), options.onto_name);
73d6d7b2 2172 if (reset_head(&options.onto->object.oid, "checkout", NULL,
8581df65
OS
2173 RESET_HEAD_DETACH | RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
2174 NULL, msg.buf))
ac7f467f
PK
2175 die(_("Could not detach HEAD"));
2176 strbuf_release(&msg);
2177
7eecfa56
PK
2178 /*
2179 * If the onto is a proper descendant of the tip of the branch, then
2180 * we just fast-forwarded.
2181 */
2182 strbuf_reset(&msg);
2183 if (!oidcmp(&merge_base, &options.orig_head)) {
eff199a6 2184 printf(_("Fast-forwarded %s to %s.\n"),
7eecfa56
PK
2185 branch_name, options.onto_name);
2186 strbuf_addf(&msg, "rebase finished: %s onto %s",
2187 options.head_name ? options.head_name : "detached HEAD",
2188 oid_to_hex(&options.onto->object.oid));
2189 reset_head(NULL, "Fast-forwarded", options.head_name, 0,
2190 "HEAD", msg.buf);
2191 strbuf_release(&msg);
2192 ret = !!finish_rebase(&options);
2193 goto cleanup;
2194 }
2195
ac7f467f
PK
2196 strbuf_addf(&revisions, "%s..%s",
2197 options.root ? oid_to_hex(&options.onto->object.oid) :
2198 (options.restrict_revision ?
2199 oid_to_hex(&options.restrict_revision->object.oid) :
2200 oid_to_hex(&options.upstream->object.oid)),
2201 oid_to_hex(&options.orig_head));
2202
2203 options.revisions = revisions.buf;
2204
f9573628 2205run_rebase:
ac7f467f
PK
2206 ret = !!run_specific_rebase(&options);
2207
e0333e5c 2208cleanup:
ac7f467f
PK
2209 strbuf_release(&revisions);
2210 free(options.head_name);
12026a41 2211 free(options.gpg_sign_opt);
68e46d78 2212 free(options.cmd);
9dba809a 2213 free(squash_onto_name);
ac7f467f 2214 return ret;
55071ea2 2215}