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