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