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