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