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