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