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