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