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