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