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