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