]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
sequencer (rebase -i): respect the rebase.autostash setting
[thirdparty/git.git] / sequencer.c
CommitLineData
26ae337b 1#include "cache.h"
697cc8ef 2#include "lockfile.h"
26ae337b 3#include "sequencer.h"
26ae337b 4#include "dir.h"
043a4492
RR
5#include "object.h"
6#include "commit.h"
7#include "tag.h"
8#include "run-command.h"
9#include "exec_cmd.h"
10#include "utf8.h"
11#include "cache-tree.h"
12#include "diff.h"
13#include "revision.h"
14#include "rerere.h"
15#include "merge-recursive.h"
16#include "refs.h"
b27cfb0d 17#include "argv-array.h"
a1c75762 18#include "quote.h"
967dfd4d 19#include "trailer.h"
56dc3ab0 20#include "log-tree.h"
311af526 21#include "wt-status.h"
043a4492
RR
22
23#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 24
5ed75e2a 25const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 26static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 27
8a2a0f53
JS
28GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
29
30static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
31static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
32static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 33static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 34
84583957
JS
35static GIT_PATH_FUNC(rebase_path, "rebase-merge")
36/*
37 * The file containing rebase commands, comments, and empty lines.
38 * This file is created by "git rebase -i" then edited by the user. As
39 * the lines are processed, they are removed from the front of this
40 * file and written to the tail of 'done'.
41 */
42static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
1df6df0c
JS
43/*
44 * The rebase command lines that have already been processed. A line
45 * is moved here when it is first handled, before any associated user
46 * actions.
47 */
48static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
6e98de72
JS
49/*
50 * The commit message that is planned to be used for any changes that
51 * need to be committed following a user interaction.
52 */
53static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
54/*
55 * The file into which is accumulated the suggested commit message for
56 * squash/fixup commands. When the first of a series of squash/fixups
57 * is seen, the file is created and the commit message from the
58 * previous commit and from the first squash/fixup commit are written
59 * to it. The commit message for each subsequent squash/fixup commit
60 * is appended to the file as it is processed.
61 *
62 * The first line of the file is of the form
63 * # This is a combination of $count commits.
64 * where $count is the number of commits whose messages have been
65 * written to the file so far (including the initial "pick" commit).
66 * Each time that a commit message is processed, this line is read and
67 * updated. It is deleted just before the combined commit is made.
68 */
69static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
70/*
71 * If the current series of squash/fixups has not yet included a squash
72 * command, then this file exists and holds the commit message of the
73 * original "pick" commit. (If the series ends without a "squash"
74 * command, then this can be used as the commit message of the combined
75 * commit without opening the editor.)
76 */
77static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
b5a67045
JS
78/*
79 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
80 * GIT_AUTHOR_DATE that will be used for the commit that is currently
81 * being rebased.
82 */
83static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
84/*
85 * When an "edit" rebase command is being processed, the SHA1 of the
86 * commit to be edited is recorded in this file. When "git rebase
87 * --continue" is executed, if there are any staged changes then they
88 * will be amended to the HEAD commit, but only provided the HEAD
89 * commit is still the commit to be edited. When any other rebase
90 * command is processed, this file is deleted.
91 */
92static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
93/*
94 * When we stop at a given patch via the "edit" command, this file contains
95 * the abbreviated commit name of the corresponding patch.
96 */
97static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
98/*
99 * For the post-rewrite hook, we make a list of rewritten commits and
100 * their new sha1s. The rewritten-pending list keeps the sha1s of
101 * commits that have been processed, but not committed yet,
102 * e.g. because they are waiting for a 'squash' command.
103 */
104static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
105static GIT_PATH_FUNC(rebase_path_rewritten_pending,
106 "rebase-merge/rewritten-pending")
a1c75762
JS
107/*
108 * The following files are written by git-rebase just after parsing the
109 * command-line (and are only consumed, not modified, by the sequencer).
110 */
111static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
556907f1
JS
112static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
113static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
4b83ce9f
JS
114static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
115static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 116static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
b5a67045 117
b5a67045
JS
118static inline int is_rebase_i(const struct replay_opts *opts)
119{
84583957 120 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
121}
122
285abf56
JS
123static const char *get_dir(const struct replay_opts *opts)
124{
84583957
JS
125 if (is_rebase_i(opts))
126 return rebase_path();
285abf56
JS
127 return git_path_seq_dir();
128}
129
c0246501
JS
130static const char *get_todo_path(const struct replay_opts *opts)
131{
84583957
JS
132 if (is_rebase_i(opts))
133 return rebase_path_todo();
c0246501
JS
134 return git_path_todo_file();
135}
136
bab4d109
BC
137/*
138 * Returns 0 for non-conforming footer
139 * Returns 1 for conforming footer
140 * Returns 2 when sob exists within conforming footer
141 * Returns 3 when sob exists within conforming footer as last entry
142 */
143static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
144 int ignore_footer)
b971e04f 145{
967dfd4d
JT
146 struct trailer_info info;
147 int i;
148 int found_sob = 0, found_sob_last = 0;
b971e04f 149
967dfd4d 150 trailer_info_get(&info, sb->buf);
b971e04f 151
967dfd4d 152 if (info.trailer_start == info.trailer_end)
b971e04f
BC
153 return 0;
154
967dfd4d
JT
155 for (i = 0; i < info.trailer_nr; i++)
156 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
157 found_sob = 1;
158 if (i == info.trailer_nr - 1)
159 found_sob_last = 1;
160 }
b971e04f 161
967dfd4d 162 trailer_info_release(&info);
bab4d109 163
967dfd4d 164 if (found_sob_last)
bab4d109
BC
165 return 3;
166 if (found_sob)
167 return 2;
b971e04f
BC
168 return 1;
169}
5ed75e2a 170
a1c75762
JS
171static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
172{
173 static struct strbuf buf = STRBUF_INIT;
174
175 strbuf_reset(&buf);
176 if (opts->gpg_sign)
177 sq_quotef(&buf, "-S%s", opts->gpg_sign);
178 return buf.buf;
179}
180
2863584f 181int sequencer_remove_state(struct replay_opts *opts)
26ae337b 182{
285abf56 183 struct strbuf dir = STRBUF_INIT;
03a4e260
JS
184 int i;
185
186 free(opts->gpg_sign);
187 free(opts->strategy);
188 for (i = 0; i < opts->xopts_nr; i++)
189 free(opts->xopts[i]);
190 free(opts->xopts);
26ae337b 191
285abf56
JS
192 strbuf_addf(&dir, "%s", get_dir(opts));
193 remove_dir_recursively(&dir, 0);
194 strbuf_release(&dir);
2863584f
JS
195
196 return 0;
26ae337b 197}
043a4492
RR
198
199static const char *action_name(const struct replay_opts *opts)
200{
84583957
JS
201 switch (opts->action) {
202 case REPLAY_REVERT:
203 return N_("revert");
204 case REPLAY_PICK:
205 return N_("cherry-pick");
206 case REPLAY_INTERACTIVE_REBASE:
207 return N_("rebase -i");
208 }
209 die(_("Unknown action: %d"), opts->action);
043a4492
RR
210}
211
043a4492
RR
212struct commit_message {
213 char *parent_label;
7b35eaf8
JK
214 char *label;
215 char *subject;
043a4492
RR
216 const char *message;
217};
218
39755964
JS
219static const char *short_commit_name(struct commit *commit)
220{
221 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
222}
223
043a4492
RR
224static int get_message(struct commit *commit, struct commit_message *out)
225{
043a4492 226 const char *abbrev, *subject;
7b35eaf8 227 int subject_len;
043a4492 228
7b35eaf8 229 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 230 abbrev = short_commit_name(commit);
043a4492
RR
231
232 subject_len = find_commit_subject(out->message, &subject);
233
7b35eaf8
JK
234 out->subject = xmemdupz(subject, subject_len);
235 out->label = xstrfmt("%s... %s", abbrev, out->subject);
236 out->parent_label = xstrfmt("parent of %s", out->label);
237
043a4492
RR
238 return 0;
239}
240
d74a4e57 241static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
242{
243 free(msg->parent_label);
7b35eaf8
JK
244 free(msg->label);
245 free(msg->subject);
b66103c3 246 unuse_commit_buffer(commit, msg->message);
043a4492
RR
247}
248
ed727b19 249static void print_advice(int show_hint, struct replay_opts *opts)
043a4492
RR
250{
251 char *msg = getenv("GIT_CHERRY_PICK_HELP");
252
253 if (msg) {
254 fprintf(stderr, "%s\n", msg);
255 /*
41ccfdd9 256 * A conflict has occurred but the porcelain
043a4492
RR
257 * (typically rebase --interactive) wants to take care
258 * of the commit itself so remove CHERRY_PICK_HEAD
259 */
f932729c 260 unlink(git_path_cherry_pick_head());
043a4492
RR
261 return;
262 }
263
ed727b19
PH
264 if (show_hint) {
265 if (opts->no_commit)
266 advise(_("after resolving the conflicts, mark the corrected paths\n"
267 "with 'git add <paths>' or 'git rm <paths>'"));
268 else
269 advise(_("after resolving the conflicts, mark the corrected paths\n"
270 "with 'git add <paths>' or 'git rm <paths>'\n"
271 "and commit the result with 'git commit'"));
272 }
043a4492
RR
273}
274
f56fffef
JS
275static int write_message(const void *buf, size_t len, const char *filename,
276 int append_eol)
043a4492
RR
277{
278 static struct lock_file msg_file;
279
4ef3d8f0
JS
280 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
281 if (msg_fd < 0)
93b3df6f 282 return error_errno(_("could not lock '%s'"), filename);
75871495 283 if (write_in_full(msg_fd, buf, len) < 0) {
4f66c837 284 rollback_lock_file(&msg_file);
93b3df6f 285 return error_errno(_("could not write to '%s'"), filename);
4f66c837 286 }
f56fffef
JS
287 if (append_eol && write(msg_fd, "\n", 1) < 0) {
288 rollback_lock_file(&msg_file);
35871806 289 return error_errno(_("could not write eol to '%s'"), filename);
f56fffef 290 }
4f66c837
JS
291 if (commit_lock_file(&msg_file) < 0) {
292 rollback_lock_file(&msg_file);
93b3df6f 293 return error(_("failed to finalize '%s'."), filename);
4f66c837 294 }
4ef3d8f0
JS
295
296 return 0;
043a4492
RR
297}
298
1dfc84e9
JS
299/*
300 * Reads a file that was presumably written by a shell script, i.e. with an
301 * end-of-line marker that needs to be stripped.
302 *
303 * Note that only the last end-of-line marker is stripped, consistent with the
304 * behavior of "$(cat path)" in a shell script.
305 *
306 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
307 */
308static int read_oneliner(struct strbuf *buf,
309 const char *path, int skip_if_empty)
310{
311 int orig_len = buf->len;
312
313 if (!file_exists(path))
314 return 0;
315
316 if (strbuf_read_file(buf, path, 0) < 0) {
317 warning_errno(_("could not read '%s'"), path);
318 return 0;
319 }
320
321 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
322 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
323 --buf->len;
324 buf->buf[buf->len] = '\0';
325 }
326
327 if (skip_if_empty && buf->len == orig_len)
328 return 0;
329
330 return 1;
331}
332
043a4492
RR
333static struct tree *empty_tree(void)
334{
cba595bd 335 return lookup_tree(EMPTY_TREE_SHA1_BIN);
043a4492
RR
336}
337
338static int error_dirty_index(struct replay_opts *opts)
339{
340 if (read_cache_unmerged())
c28cbc5e 341 return error_resolve_conflict(_(action_name(opts)));
043a4492 342
93b3df6f 343 error(_("your local changes would be overwritten by %s."),
c28cbc5e 344 _(action_name(opts)));
043a4492
RR
345
346 if (advice_commit_before_merge)
93b3df6f 347 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
348 return -1;
349}
350
1e41229d
SB
351static void update_abort_safety_file(void)
352{
353 struct object_id head;
354
355 /* Do nothing on a single-pick */
356 if (!file_exists(git_path_seq_dir()))
357 return;
358
359 if (!get_oid("HEAD", &head))
360 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
361 else
362 write_file(git_path_abort_safety_file(), "%s", "");
363}
364
334ae397 365static int fast_forward_to(const unsigned char *to, const unsigned char *from,
eb4be1cb 366 int unborn, struct replay_opts *opts)
043a4492 367{
d668d16c 368 struct ref_transaction *transaction;
eb4be1cb 369 struct strbuf sb = STRBUF_INIT;
d668d16c 370 struct strbuf err = STRBUF_INIT;
043a4492
RR
371
372 read_cache();
db699a8a 373 if (checkout_fast_forward(from, to, 1))
0e408fc3 374 return -1; /* the callee should have complained already */
651ab9f5 375
c28cbc5e 376 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
377
378 transaction = ref_transaction_begin(&err);
379 if (!transaction ||
380 ref_transaction_update(transaction, "HEAD",
381 to, unborn ? null_sha1 : from,
1d147bdf 382 0, sb.buf, &err) ||
db7516ab 383 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
384 ref_transaction_free(transaction);
385 error("%s", err.buf);
386 strbuf_release(&sb);
387 strbuf_release(&err);
388 return -1;
389 }
651ab9f5 390
eb4be1cb 391 strbuf_release(&sb);
d668d16c
RS
392 strbuf_release(&err);
393 ref_transaction_free(transaction);
1e41229d 394 update_abort_safety_file();
d668d16c 395 return 0;
043a4492
RR
396}
397
75c961b7
JH
398void append_conflicts_hint(struct strbuf *msgbuf)
399{
400 int i;
401
261f315b
JH
402 strbuf_addch(msgbuf, '\n');
403 strbuf_commented_addf(msgbuf, "Conflicts:\n");
75c961b7
JH
404 for (i = 0; i < active_nr;) {
405 const struct cache_entry *ce = active_cache[i++];
406 if (ce_stage(ce)) {
261f315b 407 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
75c961b7
JH
408 while (i < active_nr && !strcmp(ce->name,
409 active_cache[i]->name))
410 i++;
411 }
412 }
413}
414
043a4492
RR
415static int do_recursive_merge(struct commit *base, struct commit *next,
416 const char *base_label, const char *next_label,
417 unsigned char *head, struct strbuf *msgbuf,
418 struct replay_opts *opts)
419{
420 struct merge_options o;
421 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 422 int clean;
03a4e260 423 char **xopt;
043a4492
RR
424 static struct lock_file index_lock;
425
b3e83cc7 426 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
043a4492
RR
427
428 read_cache();
429
430 init_merge_options(&o);
431 o.ancestor = base ? base_label : "(empty tree)";
432 o.branch1 = "HEAD";
433 o.branch2 = next ? next_label : "(empty tree)";
434
435 head_tree = parse_tree_indirect(head);
436 next_tree = next ? next->tree : empty_tree();
437 base_tree = base ? base->tree : empty_tree();
438
439 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
440 parse_merge_opt(&o, *xopt);
441
442 clean = merge_trees(&o,
443 head_tree,
444 next_tree, base_tree, &result);
548009c0 445 strbuf_release(&o.obuf);
f241ff0d
JS
446 if (clean < 0)
447 return clean;
043a4492
RR
448
449 if (active_cache_changed &&
03b86647 450 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
84583957
JS
451 /* TRANSLATORS: %s will be "revert", "cherry-pick" or
452 * "rebase -i".
453 */
c527b55e 454 return error(_("%s: Unable to write new index file"),
c28cbc5e 455 _(action_name(opts)));
043a4492
RR
456 rollback_lock_file(&index_lock);
457
5ed75e2a 458 if (opts->signoff)
bab4d109 459 append_signoff(msgbuf, 0, 0);
5ed75e2a 460
75c961b7
JH
461 if (!clean)
462 append_conflicts_hint(msgbuf);
043a4492
RR
463
464 return !clean;
465}
466
b27cfb0d
NH
467static int is_index_unchanged(void)
468{
469 unsigned char head_sha1[20];
470 struct commit *head_commit;
471
7695d118 472 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
93b3df6f 473 return error(_("could not resolve HEAD commit\n"));
b27cfb0d
NH
474
475 head_commit = lookup_commit(head_sha1);
4b580061
NH
476
477 /*
478 * If head_commit is NULL, check_commit, called from
479 * lookup_commit, would have indicated that head_commit is not
480 * a commit object already. parse_commit() will return failure
481 * without further complaints in such a case. Otherwise, if
482 * the commit is invalid, parse_commit() will complain. So
483 * there is nothing for us to say here. Just return failure.
484 */
485 if (parse_commit(head_commit))
486 return -1;
b27cfb0d
NH
487
488 if (!active_cache_tree)
489 active_cache_tree = cache_tree();
490
491 if (!cache_tree_fully_valid(active_cache_tree))
d0cfc3e8 492 if (cache_tree_update(&the_index, 0))
93b3df6f 493 return error(_("unable to update cache tree\n"));
b27cfb0d 494
ed1c9977 495 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
b27cfb0d
NH
496}
497
0473f28a
JS
498static int write_author_script(const char *message)
499{
500 struct strbuf buf = STRBUF_INIT;
501 const char *eol;
502 int res;
503
504 for (;;)
505 if (!*message || starts_with(message, "\n")) {
506missing_author:
507 /* Missing 'author' line? */
508 unlink(rebase_path_author_script());
509 return 0;
510 } else if (skip_prefix(message, "author ", &message))
511 break;
512 else if ((eol = strchr(message, '\n')))
513 message = eol + 1;
514 else
515 goto missing_author;
516
517 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
518 while (*message && *message != '\n' && *message != '\r')
519 if (skip_prefix(message, " <", &message))
520 break;
521 else if (*message != '\'')
522 strbuf_addch(&buf, *(message++));
523 else
524 strbuf_addf(&buf, "'\\\\%c'", *(message++));
525 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
526 while (*message && *message != '\n' && *message != '\r')
527 if (skip_prefix(message, "> ", &message))
528 break;
529 else if (*message != '\'')
530 strbuf_addch(&buf, *(message++));
531 else
532 strbuf_addf(&buf, "'\\\\%c'", *(message++));
533 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
534 while (*message && *message != '\n' && *message != '\r')
535 if (*message != '\'')
536 strbuf_addch(&buf, *(message++));
537 else
538 strbuf_addf(&buf, "'\\\\%c'", *(message++));
539 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
540 strbuf_release(&buf);
541 return res;
542}
543
b5a67045
JS
544/*
545 * Read the author-script file into an environment block, ready for use in
546 * run_command(), that can be free()d afterwards.
547 */
548static char **read_author_script(void)
549{
550 struct strbuf script = STRBUF_INIT;
551 int i, count = 0;
552 char *p, *p2, **env;
553 size_t env_size;
554
555 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
556 return NULL;
557
558 for (p = script.buf; *p; p++)
559 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
560 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
561 else if (*p == '\'')
562 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
563 else if (*p == '\n') {
564 *p = '\0';
565 count++;
566 }
567
568 env_size = (count + 1) * sizeof(*env);
569 strbuf_grow(&script, env_size);
570 memmove(script.buf + env_size, script.buf, script.len);
571 p = script.buf + env_size;
572 env = (char **)strbuf_detach(&script, NULL);
573
574 for (i = 0; i < count; i++) {
575 env[i] = p;
576 p += strlen(p) + 1;
577 }
578 env[count] = NULL;
579
580 return env;
581}
582
791eb870
JS
583static const char staged_changes_advice[] =
584N_("you have staged changes in your working tree\n"
585"If these changes are meant to be squashed into the previous commit, run:\n"
586"\n"
587" git commit --amend %s\n"
588"\n"
589"If they are meant to go into a new commit, run:\n"
590"\n"
591" git commit %s\n"
592"\n"
593"In both cases, once you're done, continue with:\n"
594"\n"
595" git rebase --continue\n");
596
043a4492
RR
597/*
598 * If we are cherry-pick, and if the merge did not result in
599 * hand-editing, we will hit this commit and inherit the original
600 * author date and name.
b5a67045 601 *
043a4492
RR
602 * If we are revert, or if our cherry-pick results in a hand merge,
603 * we had better say that the current user is responsible for that.
b5a67045
JS
604 *
605 * An exception is when run_git_commit() is called during an
606 * interactive rebase: in that case, we will want to retain the
607 * author metadata.
043a4492 608 */
ac2b0e8f 609static int run_git_commit(const char *defmsg, struct replay_opts *opts,
0009426d
JS
610 int allow_empty, int edit, int amend,
611 int cleanup_commit_message)
043a4492 612{
b5a67045 613 char **env = NULL;
b27cfb0d
NH
614 struct argv_array array;
615 int rc;
17d65f03 616 const char *value;
b27cfb0d 617
b5a67045
JS
618 if (is_rebase_i(opts)) {
619 env = read_author_script();
a1c75762
JS
620 if (!env) {
621 const char *gpg_opt = gpg_sign_opt_quoted(opts);
622
791eb870
JS
623 return error(_(staged_changes_advice),
624 gpg_opt, gpg_opt);
a1c75762 625 }
b5a67045
JS
626 }
627
b27cfb0d
NH
628 argv_array_init(&array);
629 argv_array_push(&array, "commit");
630 argv_array_push(&array, "-n");
043a4492 631
9240beda
JS
632 if (amend)
633 argv_array_push(&array, "--amend");
3bdd5522
JK
634 if (opts->gpg_sign)
635 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
043a4492 636 if (opts->signoff)
b27cfb0d 637 argv_array_push(&array, "-s");
b5a67045
JS
638 if (defmsg)
639 argv_array_pushl(&array, "-F", defmsg, NULL);
0009426d
JS
640 if (cleanup_commit_message)
641 argv_array_push(&array, "--cleanup=strip");
a1c75762 642 if (edit)
b5a67045 643 argv_array_push(&array, "-e");
0009426d
JS
644 else if (!cleanup_commit_message &&
645 !opts->signoff && !opts->record_origin &&
b5a67045
JS
646 git_config_get_value("commit.cleanup", &value))
647 argv_array_push(&array, "--cleanup=verbatim");
b27cfb0d 648
ac2b0e8f 649 if (allow_empty)
b27cfb0d 650 argv_array_push(&array, "--allow-empty");
df478b74 651
4bee9584
CW
652 if (opts->allow_empty_message)
653 argv_array_push(&array, "--allow-empty-message");
654
b5a67045
JS
655 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
656 (const char *const *)env);
b27cfb0d 657 argv_array_clear(&array);
b5a67045
JS
658 free(env);
659
b27cfb0d
NH
660 return rc;
661}
662
663static int is_original_commit_empty(struct commit *commit)
664{
665 const unsigned char *ptree_sha1;
666
667 if (parse_commit(commit))
93b3df6f 668 return error(_("could not parse commit %s\n"),
f2fd0760 669 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
670 if (commit->parents) {
671 struct commit *parent = commit->parents->item;
672 if (parse_commit(parent))
93b3df6f 673 return error(_("could not parse parent commit %s\n"),
f2fd0760 674 oid_to_hex(&parent->object.oid));
ed1c9977 675 ptree_sha1 = parent->tree->object.oid.hash;
b27cfb0d
NH
676 } else {
677 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
043a4492 678 }
043a4492 679
ed1c9977 680 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
043a4492
RR
681}
682
ac2b0e8f
JH
683/*
684 * Do we run "git commit" with "--allow-empty"?
685 */
686static int allow_empty(struct replay_opts *opts, struct commit *commit)
687{
688 int index_unchanged, empty_commit;
689
690 /*
691 * Three cases:
692 *
693 * (1) we do not allow empty at all and error out.
694 *
695 * (2) we allow ones that were initially empty, but
696 * forbid the ones that become empty;
697 *
698 * (3) we allow both.
699 */
700 if (!opts->allow_empty)
701 return 0; /* let "git commit" barf as necessary */
702
703 index_unchanged = is_index_unchanged();
704 if (index_unchanged < 0)
705 return index_unchanged;
706 if (!index_unchanged)
707 return 0; /* we do not have to say --allow-empty */
708
709 if (opts->keep_redundant_commits)
710 return 1;
711
712 empty_commit = is_original_commit_empty(commit);
713 if (empty_commit < 0)
714 return empty_commit;
715 if (!empty_commit)
716 return 0;
717 else
718 return 1;
719}
720
25c43667
JS
721/*
722 * Note that ordering matters in this enum. Not only must it match the mapping
723 * below, it is also divided into several sections that matter. When adding
724 * new commands, make sure you add it in the right section.
725 */
004fefa7 726enum todo_command {
25c43667 727 /* commands that handle commits */
004fefa7 728 TODO_PICK = 0,
25c43667 729 TODO_REVERT,
56dc3ab0 730 TODO_EDIT,
04efc8b5 731 TODO_REWORD,
6e98de72
JS
732 TODO_FIXUP,
733 TODO_SQUASH,
311af526
JS
734 /* commands that do something else than handling a single commit */
735 TODO_EXEC,
25c43667
JS
736 /* commands that do nothing but are counted for reporting progress */
737 TODO_NOOP
004fefa7
JS
738};
739
414697a9
JS
740static struct {
741 char c;
742 const char *str;
743} todo_command_info[] = {
744 { 'p', "pick" },
745 { 0, "revert" },
746 { 'e', "edit" },
04efc8b5 747 { 'r', "reword" },
414697a9
JS
748 { 'f', "fixup" },
749 { 's', "squash" },
750 { 'x', "exec" },
751 { 0, "noop" }
004fefa7
JS
752};
753
754static const char *command_to_string(const enum todo_command command)
755{
414697a9
JS
756 if ((size_t)command < ARRAY_SIZE(todo_command_info))
757 return todo_command_info[command].str;
004fefa7
JS
758 die("Unknown command: %d", command);
759}
760
25c43667
JS
761static int is_noop(const enum todo_command command)
762{
763 return TODO_NOOP <= (size_t)command;
764}
004fefa7 765
6e98de72
JS
766static int is_fixup(enum todo_command command)
767{
768 return command == TODO_FIXUP || command == TODO_SQUASH;
769}
770
771static int update_squash_messages(enum todo_command command,
772 struct commit *commit, struct replay_opts *opts)
773{
774 struct strbuf buf = STRBUF_INIT;
775 int count, res;
776 const char *message, *body;
777
778 if (file_exists(rebase_path_squash_msg())) {
779 struct strbuf header = STRBUF_INIT;
780 char *eol, *p;
781
782 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
783 return error(_("could not read '%s'"),
784 rebase_path_squash_msg());
785
786 p = buf.buf + 1;
787 eol = strchrnul(buf.buf, '\n');
788 if (buf.buf[0] != comment_line_char ||
789 (p += strcspn(p, "0123456789\n")) == eol)
790 return error(_("unexpected 1st line of squash message:"
791 "\n\n\t%.*s"),
792 (int)(eol - buf.buf), buf.buf);
793 count = strtol(p, NULL, 10);
794
795 if (count < 1)
796 return error(_("invalid 1st line of squash message:\n"
797 "\n\t%.*s"),
798 (int)(eol - buf.buf), buf.buf);
799
800 strbuf_addf(&header, "%c ", comment_line_char);
801 strbuf_addf(&header,
802 _("This is a combination of %d commits."), ++count);
803 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
804 strbuf_release(&header);
805 } else {
806 unsigned char head[20];
807 struct commit *head_commit;
808 const char *head_message, *body;
809
810 if (get_sha1("HEAD", head))
811 return error(_("need a HEAD to fixup"));
812 if (!(head_commit = lookup_commit_reference(head)))
813 return error(_("could not read HEAD"));
814 if (!(head_message = get_commit_buffer(head_commit, NULL)))
815 return error(_("could not read HEAD's commit message"));
816
817 find_commit_subject(head_message, &body);
818 if (write_message(body, strlen(body),
819 rebase_path_fixup_msg(), 0)) {
820 unuse_commit_buffer(head_commit, head_message);
821 return error(_("cannot write '%s'"),
822 rebase_path_fixup_msg());
823 }
824
825 count = 2;
826 strbuf_addf(&buf, "%c ", comment_line_char);
827 strbuf_addf(&buf, _("This is a combination of %d commits."),
828 count);
829 strbuf_addf(&buf, "\n%c ", comment_line_char);
830 strbuf_addstr(&buf, _("This is the 1st commit message:"));
831 strbuf_addstr(&buf, "\n\n");
832 strbuf_addstr(&buf, body);
833
834 unuse_commit_buffer(head_commit, head_message);
835 }
836
837 if (!(message = get_commit_buffer(commit, NULL)))
838 return error(_("could not read commit message of %s"),
839 oid_to_hex(&commit->object.oid));
840 find_commit_subject(message, &body);
841
842 if (command == TODO_SQUASH) {
843 unlink(rebase_path_fixup_msg());
844 strbuf_addf(&buf, "\n%c ", comment_line_char);
845 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
846 strbuf_addstr(&buf, "\n\n");
847 strbuf_addstr(&buf, body);
848 } else if (command == TODO_FIXUP) {
849 strbuf_addf(&buf, "\n%c ", comment_line_char);
850 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
851 count);
852 strbuf_addstr(&buf, "\n\n");
853 strbuf_add_commented_lines(&buf, body, strlen(body));
854 } else
855 return error(_("unknown command: %d"), command);
856 unuse_commit_buffer(commit, message);
857
858 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
859 strbuf_release(&buf);
860 return res;
861}
862
25cb8df9
JS
863static void flush_rewritten_pending(void) {
864 struct strbuf buf = STRBUF_INIT;
865 unsigned char newsha1[20];
866 FILE *out;
867
868 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), 82) > 0 &&
869 !get_sha1("HEAD", newsha1) &&
870 (out = fopen(rebase_path_rewritten_list(), "a"))) {
871 char *bol = buf.buf, *eol;
872
873 while (*bol) {
874 eol = strchrnul(bol, '\n');
875 fprintf(out, "%.*s %s\n", (int)(eol - bol),
876 bol, sha1_to_hex(newsha1));
877 if (!*eol)
878 break;
879 bol = eol + 1;
880 }
881 fclose(out);
882 unlink(rebase_path_rewritten_pending());
883 }
884 strbuf_release(&buf);
885}
886
887static void record_in_rewritten(struct object_id *oid,
888 enum todo_command next_command) {
889 FILE *out = fopen(rebase_path_rewritten_pending(), "a");
890
891 if (!out)
892 return;
893
894 fprintf(out, "%s\n", oid_to_hex(oid));
895 fclose(out);
896
897 if (!is_fixup(next_command))
898 flush_rewritten_pending();
899}
900
004fefa7 901static int do_pick_commit(enum todo_command command, struct commit *commit,
6e98de72 902 struct replay_opts *opts, int final_fixup)
043a4492 903{
6e98de72
JS
904 int edit = opts->edit, cleanup_commit_message = 0;
905 const char *msg_file = edit ? NULL : git_path_merge_msg();
043a4492
RR
906 unsigned char head[20];
907 struct commit *base, *next, *parent;
908 const char *base_label, *next_label;
d74a4e57 909 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 910 struct strbuf msgbuf = STRBUF_INIT;
bcbb68be 911 int res, unborn = 0, amend = 0, allow = 0;
043a4492
RR
912
913 if (opts->no_commit) {
914 /*
915 * We do not intend to commit immediately. We just want to
916 * merge the differences in, so let's compute the tree
917 * that represents the "current" state for merge-recursive
918 * to work on.
919 */
920 if (write_cache_as_tree(head, 0, NULL))
93b3df6f 921 return error(_("your index file is unmerged."));
043a4492 922 } else {
334ae397
MZ
923 unborn = get_sha1("HEAD", head);
924 if (unborn)
925 hashcpy(head, EMPTY_TREE_SHA1_BIN);
018ec3c8 926 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
043a4492
RR
927 return error_dirty_index(opts);
928 }
929 discard_cache();
930
637666c8 931 if (!commit->parents)
043a4492 932 parent = NULL;
043a4492
RR
933 else if (commit->parents->next) {
934 /* Reverting or cherry-picking a merge commit */
935 int cnt;
936 struct commit_list *p;
937
938 if (!opts->mainline)
93b3df6f 939 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 940 oid_to_hex(&commit->object.oid));
043a4492
RR
941
942 for (cnt = 1, p = commit->parents;
943 cnt != opts->mainline && p;
944 cnt++)
945 p = p->next;
946 if (cnt != opts->mainline || !p)
93b3df6f 947 return error(_("commit %s does not have parent %d"),
f2fd0760 948 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
949 parent = p->item;
950 } else if (0 < opts->mainline)
93b3df6f 951 return error(_("mainline was specified but commit %s is not a merge."),
f2fd0760 952 oid_to_hex(&commit->object.oid));
043a4492
RR
953 else
954 parent = commit->parents->item;
955
bcbb68be
JS
956 if (get_message(commit, &msg) != 0)
957 return error(_("cannot get commit message for %s"),
958 oid_to_hex(&commit->object.oid));
959
6e98de72 960 if (opts->allow_ff && !is_fixup(command) &&
ed1c9977 961 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
bcbb68be
JS
962 (!parent && unborn))) {
963 if (is_rebase_i(opts))
964 write_author_script(msg.message);
965 res = fast_forward_to(commit->object.oid.hash, head, unborn,
966 opts);
967 if (res || command != TODO_REWORD)
968 goto leave;
969 edit = amend = 1;
970 msg_file = NULL;
971 goto fast_forward_edit;
972 }
043a4492 973 if (parent && parse_commit(parent) < 0)
004fefa7
JS
974 /* TRANSLATORS: The first %s will be a "todo" command like
975 "revert" or "pick", the second %s a SHA1. */
043a4492 976 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
977 command_to_string(command),
978 oid_to_hex(&parent->object.oid));
043a4492 979
043a4492
RR
980 /*
981 * "commit" is an existing commit. We would want to apply
982 * the difference it introduces since its first parent "prev"
983 * on top of the current HEAD if we are cherry-pick. Or the
984 * reverse of it if we are revert.
985 */
986
004fefa7 987 if (command == TODO_REVERT) {
043a4492
RR
988 base = commit;
989 base_label = msg.label;
990 next = parent;
991 next_label = msg.parent_label;
992 strbuf_addstr(&msgbuf, "Revert \"");
993 strbuf_addstr(&msgbuf, msg.subject);
994 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 995 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
996
997 if (commit->parents && commit->parents->next) {
998 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 999 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1000 }
1001 strbuf_addstr(&msgbuf, ".\n");
1002 } else {
1003 const char *p;
1004
1005 base = parent;
1006 base_label = msg.parent_label;
1007 next = commit;
1008 next_label = msg.label;
1009
23aa5142
JS
1010 /* Append the commit log message to msgbuf. */
1011 if (find_commit_subject(msg.message, &p))
1012 strbuf_addstr(&msgbuf, p);
043a4492
RR
1013
1014 if (opts->record_origin) {
bab4d109 1015 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1016 strbuf_addch(&msgbuf, '\n');
cd650a4e 1017 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1018 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1019 strbuf_addstr(&msgbuf, ")\n");
1020 }
1021 }
1022
04efc8b5
JS
1023 if (command == TODO_REWORD)
1024 edit = 1;
1025 else if (is_fixup(command)) {
6e98de72
JS
1026 if (update_squash_messages(command, commit, opts))
1027 return -1;
1028 amend = 1;
1029 if (!final_fixup)
1030 msg_file = rebase_path_squash_msg();
1031 else if (file_exists(rebase_path_fixup_msg())) {
1032 cleanup_commit_message = 1;
1033 msg_file = rebase_path_fixup_msg();
1034 } else {
1035 const char *dest = git_path("SQUASH_MSG");
1036 unlink(dest);
1037 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1038 return error(_("could not rename '%s' to '%s'"),
1039 rebase_path_squash_msg(), dest);
1040 unlink(git_path("MERGE_MSG"));
1041 msg_file = dest;
1042 edit = 1;
1043 }
1044 }
1045
0473f28a
JS
1046 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1047 res = -1;
1048 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
043a4492
RR
1049 res = do_recursive_merge(base, next, base_label, next_label,
1050 head, &msgbuf, opts);
f241ff0d
JS
1051 if (res < 0)
1052 return res;
75871495 1053 res |= write_message(msgbuf.buf, msgbuf.len,
f56fffef 1054 git_path_merge_msg(), 0);
043a4492
RR
1055 } else {
1056 struct commit_list *common = NULL;
1057 struct commit_list *remotes = NULL;
1058
75871495 1059 res = write_message(msgbuf.buf, msgbuf.len,
f56fffef 1060 git_path_merge_msg(), 0);
043a4492
RR
1061
1062 commit_list_insert(base, &common);
1063 commit_list_insert(next, &remotes);
03a4e260
JS
1064 res |= try_merge_command(opts->strategy,
1065 opts->xopts_nr, (const char **)opts->xopts,
043a4492
RR
1066 common, sha1_to_hex(head), remotes);
1067 free_commit_list(common);
1068 free_commit_list(remotes);
1069 }
452202c7 1070 strbuf_release(&msgbuf);
043a4492
RR
1071
1072 /*
1073 * If the merge was clean or if it failed due to conflict, we write
1074 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1075 * However, if the merge did not even start, then we don't want to
1076 * write it at all.
1077 */
004fefa7 1078 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
dbfad033
JS
1079 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
1080 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1081 res = -1;
004fefa7 1082 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
dbfad033
JS
1083 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
1084 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1085 res = -1;
043a4492
RR
1086
1087 if (res) {
004fefa7 1088 error(command == TODO_REVERT
043a4492
RR
1089 ? _("could not revert %s... %s")
1090 : _("could not apply %s... %s"),
39755964 1091 short_commit_name(commit), msg.subject);
ed727b19 1092 print_advice(res == 1, opts);
043a4492 1093 rerere(opts->allow_rerere_auto);
c8d1351d 1094 goto leave;
043a4492
RR
1095 }
1096
c8d1351d 1097 allow = allow_empty(opts, commit);
706728a3
FC
1098 if (allow < 0) {
1099 res = allow;
1100 goto leave;
1101 }
c8d1351d 1102 if (!opts->no_commit)
bcbb68be 1103fast_forward_edit:
6e98de72
JS
1104 res = run_git_commit(msg_file, opts, allow, edit, amend,
1105 cleanup_commit_message);
1106
1107 if (!res && final_fixup) {
1108 unlink(rebase_path_fixup_msg());
1109 unlink(rebase_path_squash_msg());
1110 }
c8d1351d
FC
1111
1112leave:
d74a4e57 1113 free_message(commit, &msg);
1e41229d 1114 update_abort_safety_file();
043a4492
RR
1115
1116 return res;
1117}
1118
c3e8618c 1119static int prepare_revs(struct replay_opts *opts)
043a4492 1120{
a73e22e9
MZ
1121 /*
1122 * picking (but not reverting) ranges (but not individual revisions)
1123 * should be done in reverse
1124 */
1125 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
1126 opts->revs->reverse ^= 1;
1127
1128 if (prepare_revision_walk(opts->revs))
c3e8618c 1129 return error(_("revision walk setup failed"));
043a4492
RR
1130
1131 if (!opts->revs->commits)
c3e8618c
JS
1132 return error(_("empty commit set passed"));
1133 return 0;
043a4492
RR
1134}
1135
0d9c6dc9 1136static int read_and_refresh_cache(struct replay_opts *opts)
043a4492
RR
1137{
1138 static struct lock_file index_lock;
1139 int index_fd = hold_locked_index(&index_lock, 0);
49fb937e
JS
1140 if (read_index_preload(&the_index, NULL) < 0) {
1141 rollback_lock_file(&index_lock);
0d9c6dc9 1142 return error(_("git %s: failed to read the index"),
c28cbc5e 1143 _(action_name(opts)));
49fb937e 1144 }
043a4492 1145 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
33c297aa 1146 if (the_index.cache_changed && index_fd >= 0) {
49fb937e
JS
1147 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1148 rollback_lock_file(&index_lock);
0d9c6dc9 1149 return error(_("git %s: failed to refresh the index"),
c28cbc5e 1150 _(action_name(opts)));
49fb937e 1151 }
043a4492
RR
1152 }
1153 rollback_lock_file(&index_lock);
0d9c6dc9 1154 return 0;
043a4492
RR
1155}
1156
004fefa7
JS
1157struct todo_item {
1158 enum todo_command command;
1159 struct commit *commit;
c22f7dfb
JS
1160 const char *arg;
1161 int arg_len;
004fefa7
JS
1162 size_t offset_in_buf;
1163};
1164
1165struct todo_list {
1166 struct strbuf buf;
1167 struct todo_item *items;
1168 int nr, alloc, current;
1169};
1170
1171#define TODO_LIST_INIT { STRBUF_INIT }
1172
1173static void todo_list_release(struct todo_list *todo_list)
043a4492 1174{
004fefa7
JS
1175 strbuf_release(&todo_list->buf);
1176 free(todo_list->items);
1177 todo_list->items = NULL;
1178 todo_list->nr = todo_list->alloc = 0;
1179}
043a4492 1180
004fefa7
JS
1181static struct todo_item *append_new_todo(struct todo_list *todo_list)
1182{
1183 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1184 return todo_list->items + todo_list->nr++;
043a4492
RR
1185}
1186
004fefa7 1187static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
043a4492
RR
1188{
1189 unsigned char commit_sha1[20];
043a4492 1190 char *end_of_object_name;
004fefa7
JS
1191 int i, saved, status, padding;
1192
8f8550b3
JS
1193 /* left-trim */
1194 bol += strspn(bol, " \t");
1195
25c43667
JS
1196 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1197 item->command = TODO_NOOP;
1198 item->commit = NULL;
1199 item->arg = bol;
1200 item->arg_len = eol - bol;
1201 return 0;
1202 }
1203
414697a9
JS
1204 for (i = 0; i < ARRAY_SIZE(todo_command_info); i++)
1205 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1206 item->command = i;
1207 break;
1208 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1209 bol++;
004fefa7
JS
1210 item->command = i;
1211 break;
1212 }
414697a9 1213 if (i >= ARRAY_SIZE(todo_command_info))
004fefa7 1214 return -1;
043a4492 1215
25c43667
JS
1216 if (item->command == TODO_NOOP) {
1217 item->commit = NULL;
1218 item->arg = bol;
1219 item->arg_len = eol - bol;
1220 return 0;
1221 }
1222
043a4492
RR
1223 /* Eat up extra spaces/ tabs before object name */
1224 padding = strspn(bol, " \t");
1225 if (!padding)
004fefa7 1226 return -1;
043a4492
RR
1227 bol += padding;
1228
311af526
JS
1229 if (item->command == TODO_EXEC) {
1230 item->arg = bol;
1231 item->arg_len = (int)(eol - bol);
1232 return 0;
1233 }
1234
004fefa7 1235 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
1236 saved = *end_of_object_name;
1237 *end_of_object_name = '\0';
1238 status = get_sha1(bol, commit_sha1);
1239 *end_of_object_name = saved;
1240
c22f7dfb
JS
1241 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1242 item->arg_len = (int)(eol - item->arg);
1243
043a4492 1244 if (status < 0)
004fefa7 1245 return -1;
043a4492 1246
004fefa7
JS
1247 item->commit = lookup_commit_reference(commit_sha1);
1248 return !item->commit;
043a4492
RR
1249}
1250
004fefa7 1251static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
043a4492 1252{
004fefa7
JS
1253 struct todo_item *item;
1254 char *p = buf, *next_p;
6e98de72 1255 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 1256
004fefa7 1257 for (i = 1; *p; i++, p = next_p) {
043a4492 1258 char *eol = strchrnul(p, '\n');
004fefa7
JS
1259
1260 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1261
6307041d
JS
1262 if (p != eol && eol[-1] == '\r')
1263 eol--; /* strip Carriage Return */
1264
004fefa7
JS
1265 item = append_new_todo(todo_list);
1266 item->offset_in_buf = p - todo_list->buf.buf;
1267 if (parse_insn_line(item, p, eol)) {
93b3df6f 1268 res = error(_("invalid line %d: %.*s"),
004fefa7 1269 i, (int)(eol - p), p);
6e98de72 1270 item->command = TODO_NOOP;
004fefa7 1271 }
6e98de72
JS
1272
1273 if (fixup_okay)
1274 ; /* do nothing */
1275 else if (is_fixup(item->command))
1276 return error(_("cannot '%s' without a previous commit"),
1277 command_to_string(item->command));
1278 else if (!is_noop(item->command))
1279 fixup_okay = 1;
043a4492 1280 }
52865279 1281
004fefa7 1282 return res;
043a4492
RR
1283}
1284
004fefa7 1285static int read_populate_todo(struct todo_list *todo_list,
043a4492
RR
1286 struct replay_opts *opts)
1287{
c0246501 1288 const char *todo_file = get_todo_path(opts);
043a4492
RR
1289 int fd, res;
1290
004fefa7 1291 strbuf_reset(&todo_list->buf);
c0246501 1292 fd = open(todo_file, O_RDONLY);
043a4492 1293 if (fd < 0)
93b3df6f 1294 return error_errno(_("could not open '%s'"), todo_file);
004fefa7 1295 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
043a4492 1296 close(fd);
93b3df6f 1297 return error(_("could not read '%s'."), todo_file);
043a4492
RR
1298 }
1299 close(fd);
1300
004fefa7 1301 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2eeaf1b3 1302 if (res)
93b3df6f 1303 return error(_("unusable instruction sheet: '%s'"), todo_file);
2eeaf1b3 1304
52865279
JS
1305 if (!todo_list->nr &&
1306 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1307 return error(_("no commits parsed."));
1308
2eeaf1b3 1309 if (!is_rebase_i(opts)) {
004fefa7
JS
1310 enum todo_command valid =
1311 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1312 int i;
1313
1314 for (i = 0; i < todo_list->nr; i++)
1315 if (valid == todo_list->items[i].command)
1316 continue;
1317 else if (valid == TODO_PICK)
93b3df6f 1318 return error(_("cannot cherry-pick during a revert."));
004fefa7 1319 else
93b3df6f 1320 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
1321 }
1322
0ae42a03 1323 return 0;
043a4492
RR
1324}
1325
03a4e260
JS
1326static int git_config_string_dup(char **dest,
1327 const char *var, const char *value)
1328{
1329 if (!value)
1330 return config_error_nonbool(var);
1331 free(*dest);
1332 *dest = xstrdup(value);
1333 return 0;
1334}
1335
043a4492
RR
1336static int populate_opts_cb(const char *key, const char *value, void *data)
1337{
1338 struct replay_opts *opts = data;
1339 int error_flag = 1;
1340
1341 if (!value)
1342 error_flag = 0;
1343 else if (!strcmp(key, "options.no-commit"))
1344 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1345 else if (!strcmp(key, "options.edit"))
1346 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1347 else if (!strcmp(key, "options.signoff"))
1348 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1349 else if (!strcmp(key, "options.record-origin"))
1350 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1351 else if (!strcmp(key, "options.allow-ff"))
1352 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1353 else if (!strcmp(key, "options.mainline"))
1354 opts->mainline = git_config_int(key, value);
1355 else if (!strcmp(key, "options.strategy"))
03a4e260 1356 git_config_string_dup(&opts->strategy, key, value);
3253553e 1357 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 1358 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
1359 else if (!strcmp(key, "options.strategy-option")) {
1360 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1361 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1362 } else
93b3df6f 1363 return error(_("invalid key: %s"), key);
043a4492
RR
1364
1365 if (!error_flag)
93b3df6f 1366 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
1367
1368 return 0;
1369}
1370
5adf9bdc 1371static int read_populate_opts(struct replay_opts *opts)
043a4492 1372{
a1c75762
JS
1373 if (is_rebase_i(opts)) {
1374 struct strbuf buf = STRBUF_INIT;
1375
1376 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1377 if (!starts_with(buf.buf, "-S"))
1378 strbuf_reset(&buf);
1379 else {
1380 free(opts->gpg_sign);
1381 opts->gpg_sign = xstrdup(buf.buf + 2);
1382 }
1383 }
1384 strbuf_release(&buf);
1385
556907f1
JS
1386 if (file_exists(rebase_path_verbose()))
1387 opts->verbose = 1;
1388
b5a67045 1389 return 0;
a1c75762 1390 }
b5a67045 1391
f932729c 1392 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
1393 return 0;
1394 /*
1395 * The function git_parse_source(), called from git_config_from_file(),
1396 * may die() in case of a syntactically incorrect file. We do not care
1397 * about this case, though, because we wrote that file ourselves, so we
1398 * are pretty certain that it is syntactically correct.
1399 */
5adf9bdc 1400 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 1401 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
1402 git_path_opts_file());
1403 return 0;
043a4492
RR
1404}
1405
004fefa7 1406static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
1407 struct replay_opts *opts)
1408{
004fefa7
JS
1409 enum todo_command command = opts->action == REPLAY_PICK ?
1410 TODO_PICK : TODO_REVERT;
414697a9 1411 const char *command_string = todo_command_info[command].str;
043a4492 1412 struct commit *commit;
043a4492 1413
34b0528b
JS
1414 if (prepare_revs(opts))
1415 return -1;
043a4492 1416
004fefa7
JS
1417 while ((commit = get_revision(opts->revs))) {
1418 struct todo_item *item = append_new_todo(todo_list);
1419 const char *commit_buffer = get_commit_buffer(commit, NULL);
1420 const char *subject;
1421 int subject_len;
1422
1423 item->command = command;
1424 item->commit = commit;
c22f7dfb
JS
1425 item->arg = NULL;
1426 item->arg_len = 0;
004fefa7
JS
1427 item->offset_in_buf = todo_list->buf.len;
1428 subject_len = find_commit_subject(commit_buffer, &subject);
1429 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1430 short_commit_name(commit), subject_len, subject);
1431 unuse_commit_buffer(commit, commit_buffer);
1432 }
34b0528b 1433 return 0;
043a4492
RR
1434}
1435
1436static int create_seq_dir(void)
1437{
f932729c 1438 if (file_exists(git_path_seq_dir())) {
043a4492
RR
1439 error(_("a cherry-pick or revert is already in progress"));
1440 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1441 return -1;
a70d8f80 1442 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 1443 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 1444 git_path_seq_dir());
043a4492
RR
1445 return 0;
1446}
1447
311fd397 1448static int save_head(const char *head)
043a4492 1449{
043a4492
RR
1450 static struct lock_file head_lock;
1451 struct strbuf buf = STRBUF_INIT;
1452 int fd;
1453
311fd397
JS
1454 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1455 if (fd < 0) {
1456 rollback_lock_file(&head_lock);
93b3df6f 1457 return error_errno(_("could not lock HEAD"));
311fd397 1458 }
043a4492 1459 strbuf_addf(&buf, "%s\n", head);
311fd397
JS
1460 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1461 rollback_lock_file(&head_lock);
93b3df6f 1462 return error_errno(_("could not write to '%s'"),
311fd397
JS
1463 git_path_head_file());
1464 }
1465 if (commit_lock_file(&head_lock) < 0) {
1466 rollback_lock_file(&head_lock);
93b3df6f 1467 return error(_("failed to finalize '%s'."), git_path_head_file());
311fd397
JS
1468 }
1469 return 0;
043a4492
RR
1470}
1471
1e41229d
SB
1472static int rollback_is_safe(void)
1473{
1474 struct strbuf sb = STRBUF_INIT;
1475 struct object_id expected_head, actual_head;
1476
1477 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1478 strbuf_trim(&sb);
1479 if (get_oid_hex(sb.buf, &expected_head)) {
1480 strbuf_release(&sb);
1481 die(_("could not parse %s"), git_path_abort_safety_file());
1482 }
1483 strbuf_release(&sb);
1484 }
1485 else if (errno == ENOENT)
1486 oidclr(&expected_head);
1487 else
1488 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1489
1490 if (get_oid("HEAD", &actual_head))
1491 oidclr(&actual_head);
1492
1493 return !oidcmp(&actual_head, &expected_head);
1494}
1495
043a4492
RR
1496static int reset_for_rollback(const unsigned char *sha1)
1497{
1498 const char *argv[4]; /* reset --merge <arg> + NULL */
1e41229d 1499
043a4492
RR
1500 argv[0] = "reset";
1501 argv[1] = "--merge";
1502 argv[2] = sha1_to_hex(sha1);
1503 argv[3] = NULL;
1504 return run_command_v_opt(argv, RUN_GIT_CMD);
1505}
1506
1507static int rollback_single_pick(void)
1508{
1509 unsigned char head_sha1[20];
1510
f932729c
JK
1511 if (!file_exists(git_path_cherry_pick_head()) &&
1512 !file_exists(git_path_revert_head()))
043a4492 1513 return error(_("no cherry-pick or revert in progress"));
7695d118 1514 if (read_ref_full("HEAD", 0, head_sha1, NULL))
043a4492
RR
1515 return error(_("cannot resolve HEAD"));
1516 if (is_null_sha1(head_sha1))
1517 return error(_("cannot abort from a branch yet to be born"));
1518 return reset_for_rollback(head_sha1);
1519}
1520
2863584f 1521int sequencer_rollback(struct replay_opts *opts)
043a4492 1522{
043a4492
RR
1523 FILE *f;
1524 unsigned char sha1[20];
1525 struct strbuf buf = STRBUF_INIT;
1526
f932729c 1527 f = fopen(git_path_head_file(), "r");
043a4492
RR
1528 if (!f && errno == ENOENT) {
1529 /*
1530 * There is no multiple-cherry-pick in progress.
1531 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1532 * a single-cherry-pick in progress, abort that.
1533 */
1534 return rollback_single_pick();
1535 }
1536 if (!f)
f7ed1953 1537 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 1538 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 1539 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 1540 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
1541 fclose(f);
1542 goto fail;
1543 }
1544 fclose(f);
1545 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1546 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 1547 git_path_head_file());
043a4492
RR
1548 goto fail;
1549 }
0f974e21
MG
1550 if (is_null_sha1(sha1)) {
1551 error(_("cannot abort from a branch yet to be born"));
1552 goto fail;
1553 }
1e41229d
SB
1554
1555 if (!rollback_is_safe()) {
1556 /* Do not error, just do not rollback */
1557 warning(_("You seem to have moved HEAD. "
1558 "Not rewinding, check your HEAD!"));
1559 } else
043a4492
RR
1560 if (reset_for_rollback(sha1))
1561 goto fail;
043a4492 1562 strbuf_release(&buf);
2863584f 1563 return sequencer_remove_state(opts);
043a4492
RR
1564fail:
1565 strbuf_release(&buf);
1566 return -1;
1567}
1568
004fefa7 1569static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 1570{
043a4492 1571 static struct lock_file todo_lock;
004fefa7
JS
1572 const char *todo_path = get_todo_path(opts);
1573 int next = todo_list->current, offset, fd;
043a4492 1574
84583957
JS
1575 /*
1576 * rebase -i writes "git-rebase-todo" without the currently executing
1577 * command, appending it to "done" instead.
1578 */
1579 if (is_rebase_i(opts))
1580 next++;
1581
004fefa7 1582 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 1583 if (fd < 0)
93b3df6f 1584 return error_errno(_("could not lock '%s'"), todo_path);
004fefa7
JS
1585 offset = next < todo_list->nr ?
1586 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1587 if (write_in_full(fd, todo_list->buf.buf + offset,
1588 todo_list->buf.len - offset) < 0)
93b3df6f 1589 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 1590 if (commit_lock_file(&todo_lock) < 0)
93b3df6f 1591 return error(_("failed to finalize '%s'."), todo_path);
1df6df0c
JS
1592
1593 if (is_rebase_i(opts)) {
1594 const char *done_path = rebase_path_done();
1595 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1596 int prev_offset = !next ? 0 :
1597 todo_list->items[next - 1].offset_in_buf;
1598
1599 if (fd >= 0 && offset > prev_offset &&
1600 write_in_full(fd, todo_list->buf.buf + prev_offset,
1601 offset - prev_offset) < 0) {
1602 close(fd);
1603 return error_errno(_("could not write to '%s'"),
1604 done_path);
1605 }
1606 if (fd >= 0)
1607 close(fd);
1608 }
221675de 1609 return 0;
043a4492
RR
1610}
1611
88d5a271 1612static int save_opts(struct replay_opts *opts)
043a4492 1613{
f932729c 1614 const char *opts_file = git_path_opts_file();
88d5a271 1615 int res = 0;
043a4492
RR
1616
1617 if (opts->no_commit)
88d5a271 1618 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 1619 if (opts->edit)
88d5a271 1620 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 1621 if (opts->signoff)
88d5a271 1622 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 1623 if (opts->record_origin)
88d5a271 1624 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 1625 if (opts->allow_ff)
88d5a271 1626 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
1627 if (opts->mainline) {
1628 struct strbuf buf = STRBUF_INIT;
1629 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 1630 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
1631 strbuf_release(&buf);
1632 }
1633 if (opts->strategy)
88d5a271 1634 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 1635 if (opts->gpg_sign)
88d5a271 1636 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
1637 if (opts->xopts) {
1638 int i;
1639 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 1640 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
1641 "options.strategy-option",
1642 opts->xopts[i], "^$", 0);
1643 }
88d5a271 1644 return res;
043a4492
RR
1645}
1646
56dc3ab0
JS
1647static int make_patch(struct commit *commit, struct replay_opts *opts)
1648{
1649 struct strbuf buf = STRBUF_INIT;
1650 struct rev_info log_tree_opt;
1651 const char *subject, *p;
1652 int res = 0;
1653
1654 p = short_commit_name(commit);
1655 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1656 return -1;
1657
1658 strbuf_addf(&buf, "%s/patch", get_dir(opts));
1659 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1660 init_revisions(&log_tree_opt, NULL);
1661 log_tree_opt.abbrev = 0;
1662 log_tree_opt.diff = 1;
1663 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1664 log_tree_opt.disable_stdin = 1;
1665 log_tree_opt.no_commit_id = 1;
1666 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1667 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1668 if (!log_tree_opt.diffopt.file)
1669 res |= error_errno(_("could not open '%s'"), buf.buf);
1670 else {
1671 res |= log_tree_commit(&log_tree_opt, commit);
1672 fclose(log_tree_opt.diffopt.file);
1673 }
1674 strbuf_reset(&buf);
1675
1676 strbuf_addf(&buf, "%s/message", get_dir(opts));
1677 if (!file_exists(buf.buf)) {
1678 const char *commit_buffer = get_commit_buffer(commit, NULL);
1679 find_commit_subject(commit_buffer, &subject);
1680 res |= write_message(subject, strlen(subject), buf.buf, 1);
1681 unuse_commit_buffer(commit, commit_buffer);
1682 }
1683 strbuf_release(&buf);
1684
1685 return res;
1686}
1687
1688static int intend_to_amend(void)
1689{
1690 unsigned char head[20];
1691 char *p;
1692
1693 if (get_sha1("HEAD", head))
1694 return error(_("cannot read HEAD"));
1695
1696 p = sha1_to_hex(head);
1697 return write_message(p, strlen(p), rebase_path_amend(), 1);
1698}
1699
1700static int error_with_patch(struct commit *commit,
1701 const char *subject, int subject_len,
1702 struct replay_opts *opts, int exit_code, int to_amend)
1703{
1704 if (make_patch(commit, opts))
1705 return -1;
1706
1707 if (to_amend) {
1708 if (intend_to_amend())
1709 return -1;
1710
1711 fprintf(stderr, "You can amend the commit now, with\n"
1712 "\n"
1713 " git commit --amend %s\n"
1714 "\n"
1715 "Once you are satisfied with your changes, run\n"
1716 "\n"
1717 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
1718 } else if (exit_code)
1719 fprintf(stderr, "Could not apply %s... %.*s\n",
1720 short_commit_name(commit), subject_len, subject);
1721
1722 return exit_code;
1723}
1724
6e98de72
JS
1725static int error_failed_squash(struct commit *commit,
1726 struct replay_opts *opts, int subject_len, const char *subject)
1727{
1728 if (rename(rebase_path_squash_msg(), rebase_path_message()))
1729 return error(_("could not rename '%s' to '%s'"),
1730 rebase_path_squash_msg(), rebase_path_message());
1731 unlink(rebase_path_fixup_msg());
1732 unlink(git_path("MERGE_MSG"));
1733 if (copy_file(git_path("MERGE_MSG"), rebase_path_message(), 0666))
1734 return error(_("could not copy '%s' to '%s'"),
1735 rebase_path_message(), git_path("MERGE_MSG"));
1736 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1737}
1738
311af526
JS
1739static int do_exec(const char *command_line)
1740{
1741 const char *child_argv[] = { NULL, NULL };
1742 int dirty, status;
1743
1744 fprintf(stderr, "Executing: %s\n", command_line);
1745 child_argv[0] = command_line;
1746 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1747
1748 /* force re-reading of the cache */
1749 if (discard_cache() < 0 || read_cache() < 0)
1750 return error(_("could not read index"));
1751
1752 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1753
1754 if (status) {
1755 warning(_("execution failed: %s\n%s"
1756 "You can fix the problem, and then run\n"
1757 "\n"
1758 " git rebase --continue\n"
1759 "\n"),
1760 command_line,
1761 dirty ? N_("and made changes to the index and/or the "
1762 "working tree\n") : "");
1763 if (status == 127)
1764 /* command not found */
1765 status = 1;
1766 } else if (dirty) {
1767 warning(_("execution succeeded: %s\nbut "
1768 "left changes to the index and/or the working tree\n"
1769 "Commit or stash your changes, and then run\n"
1770 "\n"
1771 " git rebase --continue\n"
1772 "\n"), command_line);
1773 status = 1;
1774 }
1775
1776 return status;
1777}
1778
6e98de72
JS
1779static int is_final_fixup(struct todo_list *todo_list)
1780{
1781 int i = todo_list->current;
1782
1783 if (!is_fixup(todo_list->items[i].command))
1784 return 0;
1785
1786 while (++i < todo_list->nr)
1787 if (is_fixup(todo_list->items[i].command))
1788 return 0;
1789 else if (!is_noop(todo_list->items[i].command))
1790 break;
1791 return 1;
1792}
1793
25cb8df9
JS
1794static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1795{
1796 int i;
1797
1798 for (i = todo_list->current + offset; i < todo_list->nr; i++)
1799 if (!is_noop(todo_list->items[i].command))
1800 return todo_list->items[i].command;
1801
1802 return -1;
1803}
1804
796c7972
JS
1805static int apply_autostash(struct replay_opts *opts)
1806{
1807 struct strbuf stash_sha1 = STRBUF_INIT;
1808 struct child_process child = CHILD_PROCESS_INIT;
1809 int ret = 0;
1810
1811 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1812 strbuf_release(&stash_sha1);
1813 return 0;
1814 }
1815 strbuf_trim(&stash_sha1);
1816
1817 child.git_cmd = 1;
1818 argv_array_push(&child.args, "stash");
1819 argv_array_push(&child.args, "apply");
1820 argv_array_push(&child.args, stash_sha1.buf);
1821 if (!run_command(&child))
1822 printf(_("Applied autostash."));
1823 else {
1824 struct child_process store = CHILD_PROCESS_INIT;
1825
1826 store.git_cmd = 1;
1827 argv_array_push(&store.args, "stash");
1828 argv_array_push(&store.args, "store");
1829 argv_array_push(&store.args, "-m");
1830 argv_array_push(&store.args, "autostash");
1831 argv_array_push(&store.args, "-q");
1832 argv_array_push(&store.args, stash_sha1.buf);
1833 if (run_command(&store))
1834 ret = error(_("cannot store %s"), stash_sha1.buf);
1835 else
1836 printf(_("Applying autostash resulted in conflicts.\n"
1837 "Your changes are safe in the stash.\n"
1838 "You can run \"git stash pop\" or"
1839 " \"git stash drop\" at any time.\n"));
1840 }
1841
1842 strbuf_release(&stash_sha1);
1843 return ret;
1844}
1845
96e832a5
JS
1846static const char *reflog_message(struct replay_opts *opts,
1847 const char *sub_action, const char *fmt, ...)
1848{
1849 va_list ap;
1850 static struct strbuf buf = STRBUF_INIT;
1851
1852 va_start(ap, fmt);
1853 strbuf_reset(&buf);
1854 strbuf_addstr(&buf, action_name(opts));
1855 if (sub_action)
1856 strbuf_addf(&buf, " (%s)", sub_action);
1857 if (fmt) {
1858 strbuf_addstr(&buf, ": ");
1859 strbuf_vaddf(&buf, fmt, ap);
1860 }
1861 va_end(ap);
1862
1863 return buf.buf;
1864}
1865
004fefa7 1866static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 1867{
56dc3ab0 1868 int res = 0;
043a4492
RR
1869
1870 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1871 if (opts->allow_ff)
1872 assert(!(opts->signoff || opts->no_commit ||
1873 opts->record_origin || opts->edit));
0d9c6dc9
JS
1874 if (read_and_refresh_cache(opts))
1875 return -1;
043a4492 1876
004fefa7
JS
1877 while (todo_list->current < todo_list->nr) {
1878 struct todo_item *item = todo_list->items + todo_list->current;
1879 if (save_todo(todo_list, opts))
221675de 1880 return -1;
6e98de72
JS
1881 if (is_rebase_i(opts)) {
1882 unlink(rebase_path_message());
1883 unlink(rebase_path_author_script());
1884 unlink(rebase_path_stopped_sha());
1885 unlink(rebase_path_amend());
1886 }
1887 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
1888 if (is_rebase_i(opts))
1889 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
1890 command_to_string(item->command), NULL),
1891 1);
25c43667 1892 res = do_pick_commit(item->command, item->commit,
6e98de72 1893 opts, is_final_fixup(todo_list));
56dc3ab0
JS
1894 if (item->command == TODO_EDIT) {
1895 struct commit *commit = item->commit;
1896 if (!res)
1897 warning(_("stopped at %s... %.*s"),
1898 short_commit_name(commit),
1899 item->arg_len, item->arg);
1900 return error_with_patch(commit,
1901 item->arg, item->arg_len, opts, res,
1902 !res);
1903 }
25cb8df9
JS
1904 if (is_rebase_i(opts) && !res)
1905 record_in_rewritten(&item->commit->object.oid,
1906 peek_command(todo_list, 1));
6e98de72
JS
1907 if (res && is_fixup(item->command)) {
1908 if (res == 1)
1909 intend_to_amend();
1910 return error_failed_squash(item->commit, opts,
1911 item->arg_len, item->arg);
4a5146f9
JS
1912 } else if (res && is_rebase_i(opts))
1913 return res | error_with_patch(item->commit,
04efc8b5
JS
1914 item->arg, item->arg_len, opts, res,
1915 item->command == TODO_REWORD);
311af526
JS
1916 } else if (item->command == TODO_EXEC) {
1917 char *end_of_arg = (char *)(item->arg + item->arg_len);
1918 int saved = *end_of_arg;
1919
1920 *end_of_arg = '\0';
1921 res = do_exec(item->arg);
1922 *end_of_arg = saved;
56dc3ab0 1923 } else if (!is_noop(item->command))
25c43667
JS
1924 return error(_("unknown command %d"), item->command);
1925
004fefa7 1926 todo_list->current++;
043a4492
RR
1927 if (res)
1928 return res;
1929 }
1930
56dc3ab0 1931 if (is_rebase_i(opts)) {
4b83ce9f 1932 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 1933 struct stat st;
556907f1 1934
56dc3ab0
JS
1935 /* Stopped in the middle, as planned? */
1936 if (todo_list->current < todo_list->nr)
1937 return 0;
556907f1 1938
4b83ce9f
JS
1939 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
1940 starts_with(head_ref.buf, "refs/")) {
96e832a5 1941 const char *msg;
4b83ce9f
JS
1942 unsigned char head[20], orig[20];
1943 int res;
1944
1945 if (get_sha1("HEAD", head)) {
1946 res = error(_("cannot read HEAD"));
1947cleanup_head_ref:
1948 strbuf_release(&head_ref);
1949 strbuf_release(&buf);
1950 return res;
1951 }
1952 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
1953 get_sha1_hex(buf.buf, orig)) {
1954 res = error(_("could not read orig-head"));
1955 goto cleanup_head_ref;
1956 }
4b83ce9f
JS
1957 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
1958 res = error(_("could not read 'onto'"));
1959 goto cleanup_head_ref;
1960 }
96e832a5
JS
1961 msg = reflog_message(opts, "finish", "%s onto %s",
1962 head_ref.buf, buf.buf);
1963 if (update_ref(msg, head_ref.buf, head, orig,
4b83ce9f
JS
1964 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
1965 res = error(_("could not update %s"),
1966 head_ref.buf);
1967 goto cleanup_head_ref;
1968 }
96e832a5 1969 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 1970 head_ref.buf);
96e832a5 1971 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
1972 res = error(_("could not update HEAD to %s"),
1973 head_ref.buf);
1974 goto cleanup_head_ref;
1975 }
1976 strbuf_reset(&buf);
1977 }
1978
556907f1
JS
1979 if (opts->verbose) {
1980 struct rev_info log_tree_opt;
1981 struct object_id orig, head;
1982
1983 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1984 init_revisions(&log_tree_opt, NULL);
1985 log_tree_opt.diff = 1;
1986 log_tree_opt.diffopt.output_format =
1987 DIFF_FORMAT_DIFFSTAT;
1988 log_tree_opt.disable_stdin = 1;
1989
1990 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
1991 !get_sha1(buf.buf, orig.hash) &&
1992 !get_sha1("HEAD", head.hash)) {
1993 diff_tree_sha1(orig.hash, head.hash,
1994 "", &log_tree_opt.diffopt);
1995 log_tree_diff_flush(&log_tree_opt);
1996 }
1997 }
25cb8df9
JS
1998 flush_rewritten_pending();
1999 if (!stat(rebase_path_rewritten_list(), &st) &&
2000 st.st_size > 0) {
2001 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
2002 const char *post_rewrite_hook =
2003 find_hook("post-rewrite");
25cb8df9
JS
2004
2005 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2006 child.git_cmd = 1;
2007 argv_array_push(&child.args, "notes");
2008 argv_array_push(&child.args, "copy");
2009 argv_array_push(&child.args, "--for-rewrite=rebase");
2010 /* we don't care if this copying failed */
2011 run_command(&child);
79516045
JS
2012
2013 if (post_rewrite_hook) {
2014 struct child_process hook = CHILD_PROCESS_INIT;
2015
2016 hook.in = open(rebase_path_rewritten_list(),
2017 O_RDONLY);
2018 hook.stdout_to_stderr = 1;
2019 argv_array_push(&hook.args, post_rewrite_hook);
2020 argv_array_push(&hook.args, "rebase");
2021 /* we don't care if this hook failed */
2022 run_command(&hook);
2023 }
25cb8df9 2024 }
796c7972 2025 apply_autostash(opts);
25cb8df9 2026
556907f1 2027 strbuf_release(&buf);
4b83ce9f 2028 strbuf_release(&head_ref);
56dc3ab0
JS
2029 }
2030
043a4492
RR
2031 /*
2032 * Sequence of picks finished successfully; cleanup by
2033 * removing the .git/sequencer directory
2034 */
2863584f 2035 return sequencer_remove_state(opts);
043a4492
RR
2036}
2037
2038static int continue_single_pick(void)
2039{
2040 const char *argv[] = { "commit", NULL };
2041
f932729c
JK
2042 if (!file_exists(git_path_cherry_pick_head()) &&
2043 !file_exists(git_path_revert_head()))
043a4492
RR
2044 return error(_("no cherry-pick or revert in progress"));
2045 return run_command_v_opt(argv, RUN_GIT_CMD);
2046}
2047
9d93ccd1
JS
2048static int commit_staged_changes(struct replay_opts *opts)
2049{
2050 int amend = 0;
2051
2052 if (has_unstaged_changes(1))
2053 return error(_("cannot rebase: You have unstaged changes."));
52632209
JS
2054 if (!has_uncommitted_changes(0)) {
2055 const char *cherry_pick_head = git_path("CHERRY_PICK_HEAD");
2056
2057 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2058 return error(_("could not remove CHERRY_PICK_HEAD"));
9d93ccd1 2059 return 0;
52632209 2060 }
9d93ccd1
JS
2061
2062 if (file_exists(rebase_path_amend())) {
2063 struct strbuf rev = STRBUF_INIT;
2064 unsigned char head[20], to_amend[20];
2065
2066 if (get_sha1("HEAD", head))
2067 return error(_("cannot amend non-existing commit"));
2068 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2069 return error(_("invalid file: '%s'"), rebase_path_amend());
2070 if (get_sha1_hex(rev.buf, to_amend))
2071 return error(_("invalid contents: '%s'"),
2072 rebase_path_amend());
2073 if (hashcmp(head, to_amend))
2074 return error(_("\nYou have uncommitted changes in your "
2075 "working tree. Please, commit them\n"
2076 "first and then run 'git rebase "
2077 "--continue' again."));
2078
2079 strbuf_release(&rev);
2080 amend = 1;
2081 }
2082
2083 if (run_git_commit(rebase_path_message(), opts, 1, 1, amend, 0))
2084 return error(_("could not commit staged changes."));
2085 unlink(rebase_path_amend());
2086 return 0;
2087}
2088
2863584f 2089int sequencer_continue(struct replay_opts *opts)
043a4492 2090{
004fefa7
JS
2091 struct todo_list todo_list = TODO_LIST_INIT;
2092 int res;
043a4492 2093
2863584f
JS
2094 if (read_and_refresh_cache(opts))
2095 return -1;
2096
9d93ccd1
JS
2097 if (is_rebase_i(opts)) {
2098 if (commit_staged_changes(opts))
2099 return -1;
4258a6da 2100 } else if (!file_exists(get_todo_path(opts)))
043a4492 2101 return continue_single_pick();
004fefa7 2102 if (read_populate_opts(opts))
0ae42a03 2103 return -1;
004fefa7
JS
2104 if ((res = read_populate_todo(&todo_list, opts)))
2105 goto release_todo_list;
043a4492 2106
4258a6da
JS
2107 if (!is_rebase_i(opts)) {
2108 /* Verify that the conflict has been resolved */
2109 if (file_exists(git_path_cherry_pick_head()) ||
2110 file_exists(git_path_revert_head())) {
2111 res = continue_single_pick();
2112 if (res)
2113 goto release_todo_list;
2114 }
2115 if (index_differs_from("HEAD", 0, 0)) {
2116 res = error_dirty_index(opts);
004fefa7 2117 goto release_todo_list;
4258a6da
JS
2118 }
2119 todo_list.current++;
ca98c6d4
JS
2120 } else if (file_exists(rebase_path_stopped_sha())) {
2121 struct strbuf buf = STRBUF_INIT;
2122 struct object_id oid;
2123
2124 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2125 !get_sha1_committish(buf.buf, oid.hash))
2126 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2127 strbuf_release(&buf);
043a4492 2128 }
4258a6da 2129
004fefa7
JS
2130 res = pick_commits(&todo_list, opts);
2131release_todo_list:
2132 todo_list_release(&todo_list);
2133 return res;
043a4492
RR
2134}
2135
2136static int single_pick(struct commit *cmit, struct replay_opts *opts)
2137{
2138 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
004fefa7 2139 return do_pick_commit(opts->action == REPLAY_PICK ?
6e98de72 2140 TODO_PICK : TODO_REVERT, cmit, opts, 0);
043a4492
RR
2141}
2142
2143int sequencer_pick_revisions(struct replay_opts *opts)
2144{
004fefa7 2145 struct todo_list todo_list = TODO_LIST_INIT;
043a4492 2146 unsigned char sha1[20];
004fefa7 2147 int i, res;
043a4492 2148
2863584f 2149 assert(opts->revs);
0d9c6dc9
JS
2150 if (read_and_refresh_cache(opts))
2151 return -1;
043a4492 2152
21246dbb
MV
2153 for (i = 0; i < opts->revs->pending.nr; i++) {
2154 unsigned char sha1[20];
2155 const char *name = opts->revs->pending.objects[i].name;
2156
2157 /* This happens when using --stdin. */
2158 if (!strlen(name))
2159 continue;
2160
2161 if (!get_sha1(name, sha1)) {
7c0b0d8d
JH
2162 if (!lookup_commit_reference_gently(sha1, 1)) {
2163 enum object_type type = sha1_object_info(sha1, NULL);
b9b946d4
JS
2164 return error(_("%s: can't cherry-pick a %s"),
2165 name, typename(type));
7c0b0d8d 2166 }
21246dbb 2167 } else
b9b946d4 2168 return error(_("%s: bad revision"), name);
21246dbb
MV
2169 }
2170
043a4492
RR
2171 /*
2172 * If we were called as "git cherry-pick <commit>", just
2173 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2174 * REVERT_HEAD, and don't touch the sequencer state.
2175 * This means it is possible to cherry-pick in the middle
2176 * of a cherry-pick sequence.
2177 */
2178 if (opts->revs->cmdline.nr == 1 &&
2179 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2180 opts->revs->no_walk &&
2181 !opts->revs->cmdline.rev->flags) {
2182 struct commit *cmit;
2183 if (prepare_revision_walk(opts->revs))
b9b946d4 2184 return error(_("revision walk setup failed"));
043a4492
RR
2185 cmit = get_revision(opts->revs);
2186 if (!cmit || get_revision(opts->revs))
b9b946d4 2187 return error("BUG: expected exactly one commit from walk");
043a4492
RR
2188 return single_pick(cmit, opts);
2189 }
2190
2191 /*
2192 * Start a new cherry-pick/ revert sequence; but
2193 * first, make sure that an existing one isn't in
2194 * progress
2195 */
2196
34b0528b
JS
2197 if (walk_revs_populate_todo(&todo_list, opts) ||
2198 create_seq_dir() < 0)
043a4492 2199 return -1;
0f974e21 2200 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
93b3df6f 2201 return error(_("can't revert as initial commit"));
311fd397
JS
2202 if (save_head(sha1_to_hex(sha1)))
2203 return -1;
88d5a271
JS
2204 if (save_opts(opts))
2205 return -1;
1e41229d 2206 update_abort_safety_file();
004fefa7
JS
2207 res = pick_commits(&todo_list, opts);
2208 todo_list_release(&todo_list);
2209 return res;
043a4492 2210}
5ed75e2a 2211
bab4d109 2212void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
5ed75e2a 2213{
bab4d109 2214 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 2215 struct strbuf sob = STRBUF_INIT;
bab4d109 2216 int has_footer;
5ed75e2a
MV
2217
2218 strbuf_addstr(&sob, sign_off_header);
2219 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2220 getenv("GIT_COMMITTER_EMAIL")));
2221 strbuf_addch(&sob, '\n');
bab4d109
BC
2222
2223 /*
2224 * If the whole message buffer is equal to the sob, pretend that we
2225 * found a conforming footer with a matching sob
2226 */
2227 if (msgbuf->len - ignore_footer == sob.len &&
2228 !strncmp(msgbuf->buf, sob.buf, sob.len))
2229 has_footer = 3;
2230 else
2231 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2232
33f2f9ab
BC
2233 if (!has_footer) {
2234 const char *append_newlines = NULL;
2235 size_t len = msgbuf->len - ignore_footer;
2236
8c613fd5
BC
2237 if (!len) {
2238 /*
2239 * The buffer is completely empty. Leave foom for
2240 * the title and body to be filled in by the user.
2241 */
33f2f9ab 2242 append_newlines = "\n\n";
8c613fd5
BC
2243 } else if (msgbuf->buf[len - 1] != '\n') {
2244 /*
2245 * Incomplete line. Complete the line and add a
2246 * blank one so that there is an empty line between
2247 * the message body and the sob.
2248 */
2249 append_newlines = "\n\n";
2250 } else if (len == 1) {
2251 /*
2252 * Buffer contains a single newline. Add another
2253 * so that we leave room for the title and body.
2254 */
2255 append_newlines = "\n";
2256 } else if (msgbuf->buf[len - 2] != '\n') {
2257 /*
2258 * Buffer ends with a single newline. Add another
2259 * so that there is an empty line between the message
2260 * body and the sob.
2261 */
33f2f9ab 2262 append_newlines = "\n";
8c613fd5 2263 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
2264
2265 if (append_newlines)
2266 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2267 append_newlines, strlen(append_newlines));
5ed75e2a 2268 }
bab4d109
BC
2269
2270 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2271 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2272 sob.buf, sob.len);
2273
5ed75e2a
MV
2274 strbuf_release(&sob);
2275}