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