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