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