Merge branch 'js/rerere-forget-protect-against-NUL' into maint
[git] / sequencer.c
1 #include "cache.h"
2 #include "sequencer.h"
3 #include "dir.h"
4 #include "object.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "run-command.h"
8 #include "exec_cmd.h"
9 #include "utf8.h"
10 #include "cache-tree.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "rerere.h"
14 #include "merge-recursive.h"
15 #include "refs.h"
16 #include "argv-array.h"
17
18 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
19
20 const char sign_off_header[] = "Signed-off-by: ";
21
22 static void remove_sequencer_state(void)
23 {
24         struct strbuf seq_dir = STRBUF_INIT;
25
26         strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
27         remove_dir_recursively(&seq_dir, 0);
28         strbuf_release(&seq_dir);
29 }
30
31 static const char *action_name(const struct replay_opts *opts)
32 {
33         return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
34 }
35
36 static char *get_encoding(const char *message);
37
38 struct commit_message {
39         char *parent_label;
40         const char *label;
41         const char *subject;
42         char *reencoded_message;
43         const char *message;
44 };
45
46 static int get_message(struct commit *commit, struct commit_message *out)
47 {
48         const char *encoding;
49         const char *abbrev, *subject;
50         int abbrev_len, subject_len;
51         char *q;
52
53         if (!commit->buffer)
54                 return -1;
55         encoding = get_encoding(commit->buffer);
56         if (!encoding)
57                 encoding = "UTF-8";
58         if (!git_commit_encoding)
59                 git_commit_encoding = "UTF-8";
60
61         out->reencoded_message = NULL;
62         out->message = commit->buffer;
63         if (same_encoding(encoding, git_commit_encoding))
64                 out->reencoded_message = reencode_string(commit->buffer,
65                                         git_commit_encoding, encoding);
66         if (out->reencoded_message)
67                 out->message = out->reencoded_message;
68
69         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
70         abbrev_len = strlen(abbrev);
71
72         subject_len = find_commit_subject(out->message, &subject);
73
74         out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
75                               strlen("... ") + subject_len + 1);
76         q = out->parent_label;
77         q = mempcpy(q, "parent of ", strlen("parent of "));
78         out->label = q;
79         q = mempcpy(q, abbrev, abbrev_len);
80         q = mempcpy(q, "... ", strlen("... "));
81         out->subject = q;
82         q = mempcpy(q, subject, subject_len);
83         *q = '\0';
84         return 0;
85 }
86
87 static void free_message(struct commit_message *msg)
88 {
89         free(msg->parent_label);
90         free(msg->reencoded_message);
91 }
92
93 static char *get_encoding(const char *message)
94 {
95         const char *p = message, *eol;
96
97         while (*p && *p != '\n') {
98                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
99                         ; /* do nothing */
100                 if (!prefixcmp(p, "encoding ")) {
101                         char *result = xmalloc(eol - 8 - p);
102                         strlcpy(result, p + 9, eol - 8 - p);
103                         return result;
104                 }
105                 p = eol;
106                 if (*p == '\n')
107                         p++;
108         }
109         return NULL;
110 }
111
112 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
113 {
114         const char *filename;
115         int fd;
116         struct strbuf buf = STRBUF_INIT;
117
118         strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
119
120         filename = git_path("%s", pseudoref);
121         fd = open(filename, O_WRONLY | O_CREAT, 0666);
122         if (fd < 0)
123                 die_errno(_("Could not open '%s' for writing"), filename);
124         if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
125                 die_errno(_("Could not write to '%s'"), filename);
126         strbuf_release(&buf);
127 }
128
129 static void print_advice(int show_hint, struct replay_opts *opts)
130 {
131         char *msg = getenv("GIT_CHERRY_PICK_HELP");
132
133         if (msg) {
134                 fprintf(stderr, "%s\n", msg);
135                 /*
136                  * A conflict has occurred but the porcelain
137                  * (typically rebase --interactive) wants to take care
138                  * of the commit itself so remove CHERRY_PICK_HEAD
139                  */
140                 unlink(git_path("CHERRY_PICK_HEAD"));
141                 return;
142         }
143
144         if (show_hint) {
145                 if (opts->no_commit)
146                         advise(_("after resolving the conflicts, mark the corrected paths\n"
147                                  "with 'git add <paths>' or 'git rm <paths>'"));
148                 else
149                         advise(_("after resolving the conflicts, mark the corrected paths\n"
150                                  "with 'git add <paths>' or 'git rm <paths>'\n"
151                                  "and commit the result with 'git commit'"));
152         }
153 }
154
155 static void write_message(struct strbuf *msgbuf, const char *filename)
156 {
157         static struct lock_file msg_file;
158
159         int msg_fd = hold_lock_file_for_update(&msg_file, filename,
160                                                LOCK_DIE_ON_ERROR);
161         if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
162                 die_errno(_("Could not write to %s"), filename);
163         strbuf_release(msgbuf);
164         if (commit_lock_file(&msg_file) < 0)
165                 die(_("Error wrapping up %s"), filename);
166 }
167
168 static struct tree *empty_tree(void)
169 {
170         return lookup_tree(EMPTY_TREE_SHA1_BIN);
171 }
172
173 static int error_dirty_index(struct replay_opts *opts)
174 {
175         if (read_cache_unmerged())
176                 return error_resolve_conflict(action_name(opts));
177
178         /* Different translation strings for cherry-pick and revert */
179         if (opts->action == REPLAY_PICK)
180                 error(_("Your local changes would be overwritten by cherry-pick."));
181         else
182                 error(_("Your local changes would be overwritten by revert."));
183
184         if (advice_commit_before_merge)
185                 advise(_("Commit your changes or stash them to proceed."));
186         return -1;
187 }
188
189 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
190                            int unborn)
191 {
192         struct ref_lock *ref_lock;
193
194         read_cache();
195         if (checkout_fast_forward(from, to, 1))
196                 exit(1); /* the callee should have complained already */
197         ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from, 0);
198         return write_ref_sha1(ref_lock, to, "cherry-pick");
199 }
200
201 static int do_recursive_merge(struct commit *base, struct commit *next,
202                               const char *base_label, const char *next_label,
203                               unsigned char *head, struct strbuf *msgbuf,
204                               struct replay_opts *opts)
205 {
206         struct merge_options o;
207         struct tree *result, *next_tree, *base_tree, *head_tree;
208         int clean, index_fd;
209         const char **xopt;
210         static struct lock_file index_lock;
211
212         index_fd = hold_locked_index(&index_lock, 1);
213
214         read_cache();
215
216         init_merge_options(&o);
217         o.ancestor = base ? base_label : "(empty tree)";
218         o.branch1 = "HEAD";
219         o.branch2 = next ? next_label : "(empty tree)";
220
221         head_tree = parse_tree_indirect(head);
222         next_tree = next ? next->tree : empty_tree();
223         base_tree = base ? base->tree : empty_tree();
224
225         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
226                 parse_merge_opt(&o, *xopt);
227
228         clean = merge_trees(&o,
229                             head_tree,
230                             next_tree, base_tree, &result);
231
232         if (active_cache_changed &&
233             (write_cache(index_fd, active_cache, active_nr) ||
234              commit_locked_index(&index_lock)))
235                 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
236                 die(_("%s: Unable to write new index file"), action_name(opts));
237         rollback_lock_file(&index_lock);
238
239         if (opts->signoff)
240                 append_signoff(msgbuf, 0);
241
242         if (!clean) {
243                 int i;
244                 strbuf_addstr(msgbuf, "\nConflicts:\n");
245                 for (i = 0; i < active_nr;) {
246                         struct cache_entry *ce = active_cache[i++];
247                         if (ce_stage(ce)) {
248                                 strbuf_addch(msgbuf, '\t');
249                                 strbuf_addstr(msgbuf, ce->name);
250                                 strbuf_addch(msgbuf, '\n');
251                                 while (i < active_nr && !strcmp(ce->name,
252                                                 active_cache[i]->name))
253                                         i++;
254                         }
255                 }
256         }
257
258         return !clean;
259 }
260
261 static int is_index_unchanged(void)
262 {
263         unsigned char head_sha1[20];
264         struct commit *head_commit;
265
266         if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
267                 return error(_("Could not resolve HEAD commit\n"));
268
269         head_commit = lookup_commit(head_sha1);
270
271         /*
272          * If head_commit is NULL, check_commit, called from
273          * lookup_commit, would have indicated that head_commit is not
274          * a commit object already.  parse_commit() will return failure
275          * without further complaints in such a case.  Otherwise, if
276          * the commit is invalid, parse_commit() will complain.  So
277          * there is nothing for us to say here.  Just return failure.
278          */
279         if (parse_commit(head_commit))
280                 return -1;
281
282         if (!active_cache_tree)
283                 active_cache_tree = cache_tree();
284
285         if (!cache_tree_fully_valid(active_cache_tree))
286                 if (cache_tree_update(active_cache_tree, active_cache,
287                                   active_nr, 0))
288                         return error(_("Unable to update cache tree\n"));
289
290         return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
291 }
292
293 /*
294  * If we are cherry-pick, and if the merge did not result in
295  * hand-editing, we will hit this commit and inherit the original
296  * author date and name.
297  * If we are revert, or if our cherry-pick results in a hand merge,
298  * we had better say that the current user is responsible for that.
299  */
300 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
301                           int allow_empty)
302 {
303         struct argv_array array;
304         int rc;
305
306         argv_array_init(&array);
307         argv_array_push(&array, "commit");
308         argv_array_push(&array, "-n");
309
310         if (opts->signoff)
311                 argv_array_push(&array, "-s");
312         if (!opts->edit) {
313                 argv_array_push(&array, "-F");
314                 argv_array_push(&array, defmsg);
315         }
316
317         if (allow_empty)
318                 argv_array_push(&array, "--allow-empty");
319
320         if (opts->allow_empty_message)
321                 argv_array_push(&array, "--allow-empty-message");
322
323         rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
324         argv_array_clear(&array);
325         return rc;
326 }
327
328 static int is_original_commit_empty(struct commit *commit)
329 {
330         const unsigned char *ptree_sha1;
331
332         if (parse_commit(commit))
333                 return error(_("Could not parse commit %s\n"),
334                              sha1_to_hex(commit->object.sha1));
335         if (commit->parents) {
336                 struct commit *parent = commit->parents->item;
337                 if (parse_commit(parent))
338                         return error(_("Could not parse parent commit %s\n"),
339                                 sha1_to_hex(parent->object.sha1));
340                 ptree_sha1 = parent->tree->object.sha1;
341         } else {
342                 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
343         }
344
345         return !hashcmp(ptree_sha1, commit->tree->object.sha1);
346 }
347
348 /*
349  * Do we run "git commit" with "--allow-empty"?
350  */
351 static int allow_empty(struct replay_opts *opts, struct commit *commit)
352 {
353         int index_unchanged, empty_commit;
354
355         /*
356          * Three cases:
357          *
358          * (1) we do not allow empty at all and error out.
359          *
360          * (2) we allow ones that were initially empty, but
361          * forbid the ones that become empty;
362          *
363          * (3) we allow both.
364          */
365         if (!opts->allow_empty)
366                 return 0; /* let "git commit" barf as necessary */
367
368         index_unchanged = is_index_unchanged();
369         if (index_unchanged < 0)
370                 return index_unchanged;
371         if (!index_unchanged)
372                 return 0; /* we do not have to say --allow-empty */
373
374         if (opts->keep_redundant_commits)
375                 return 1;
376
377         empty_commit = is_original_commit_empty(commit);
378         if (empty_commit < 0)
379                 return empty_commit;
380         if (!empty_commit)
381                 return 0;
382         else
383                 return 1;
384 }
385
386 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
387 {
388         unsigned char head[20];
389         struct commit *base, *next, *parent;
390         const char *base_label, *next_label;
391         struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
392         char *defmsg = NULL;
393         struct strbuf msgbuf = STRBUF_INIT;
394         int res, unborn = 0;
395
396         if (opts->no_commit) {
397                 /*
398                  * We do not intend to commit immediately.  We just want to
399                  * merge the differences in, so let's compute the tree
400                  * that represents the "current" state for merge-recursive
401                  * to work on.
402                  */
403                 if (write_cache_as_tree(head, 0, NULL))
404                         die (_("Your index file is unmerged."));
405         } else {
406                 unborn = get_sha1("HEAD", head);
407                 if (unborn)
408                         hashcpy(head, EMPTY_TREE_SHA1_BIN);
409                 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
410                         return error_dirty_index(opts);
411         }
412         discard_cache();
413
414         if (!commit->parents) {
415                 parent = NULL;
416         }
417         else if (commit->parents->next) {
418                 /* Reverting or cherry-picking a merge commit */
419                 int cnt;
420                 struct commit_list *p;
421
422                 if (!opts->mainline)
423                         return error(_("Commit %s is a merge but no -m option was given."),
424                                 sha1_to_hex(commit->object.sha1));
425
426                 for (cnt = 1, p = commit->parents;
427                      cnt != opts->mainline && p;
428                      cnt++)
429                         p = p->next;
430                 if (cnt != opts->mainline || !p)
431                         return error(_("Commit %s does not have parent %d"),
432                                 sha1_to_hex(commit->object.sha1), opts->mainline);
433                 parent = p->item;
434         } else if (0 < opts->mainline)
435                 return error(_("Mainline was specified but commit %s is not a merge."),
436                         sha1_to_hex(commit->object.sha1));
437         else
438                 parent = commit->parents->item;
439
440         if (opts->allow_ff &&
441             ((parent && !hashcmp(parent->object.sha1, head)) ||
442              (!parent && unborn)))
443              return fast_forward_to(commit->object.sha1, head, unborn);
444
445         if (parent && parse_commit(parent) < 0)
446                 /* TRANSLATORS: The first %s will be "revert" or
447                    "cherry-pick", the second %s a SHA1 */
448                 return error(_("%s: cannot parse parent commit %s"),
449                         action_name(opts), sha1_to_hex(parent->object.sha1));
450
451         if (get_message(commit, &msg) != 0)
452                 return error(_("Cannot get commit message for %s"),
453                         sha1_to_hex(commit->object.sha1));
454
455         /*
456          * "commit" is an existing commit.  We would want to apply
457          * the difference it introduces since its first parent "prev"
458          * on top of the current HEAD if we are cherry-pick.  Or the
459          * reverse of it if we are revert.
460          */
461
462         defmsg = git_pathdup("MERGE_MSG");
463
464         if (opts->action == REPLAY_REVERT) {
465                 base = commit;
466                 base_label = msg.label;
467                 next = parent;
468                 next_label = msg.parent_label;
469                 strbuf_addstr(&msgbuf, "Revert \"");
470                 strbuf_addstr(&msgbuf, msg.subject);
471                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
472                 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
473
474                 if (commit->parents && commit->parents->next) {
475                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
476                         strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
477                 }
478                 strbuf_addstr(&msgbuf, ".\n");
479         } else {
480                 const char *p;
481
482                 base = parent;
483                 base_label = msg.parent_label;
484                 next = commit;
485                 next_label = msg.label;
486
487                 /*
488                  * Append the commit log message to msgbuf; it starts
489                  * after the tree, parent, author, committer
490                  * information followed by "\n\n".
491                  */
492                 p = strstr(msg.message, "\n\n");
493                 if (p) {
494                         p += 2;
495                         strbuf_addstr(&msgbuf, p);
496                 }
497
498                 if (opts->record_origin) {
499                         strbuf_addstr(&msgbuf, "(cherry picked from commit ");
500                         strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
501                         strbuf_addstr(&msgbuf, ")\n");
502                 }
503         }
504
505         if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
506                 res = do_recursive_merge(base, next, base_label, next_label,
507                                          head, &msgbuf, opts);
508                 write_message(&msgbuf, defmsg);
509         } else {
510                 struct commit_list *common = NULL;
511                 struct commit_list *remotes = NULL;
512
513                 write_message(&msgbuf, defmsg);
514
515                 commit_list_insert(base, &common);
516                 commit_list_insert(next, &remotes);
517                 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
518                                         common, sha1_to_hex(head), remotes);
519                 free_commit_list(common);
520                 free_commit_list(remotes);
521         }
522
523         /*
524          * If the merge was clean or if it failed due to conflict, we write
525          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
526          * However, if the merge did not even start, then we don't want to
527          * write it at all.
528          */
529         if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
530                 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
531         if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
532                 write_cherry_pick_head(commit, "REVERT_HEAD");
533
534         if (res) {
535                 error(opts->action == REPLAY_REVERT
536                       ? _("could not revert %s... %s")
537                       : _("could not apply %s... %s"),
538                       find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
539                       msg.subject);
540                 print_advice(res == 1, opts);
541                 rerere(opts->allow_rerere_auto);
542         } else {
543                 int allow = allow_empty(opts, commit);
544                 if (allow < 0)
545                         return allow;
546                 if (!opts->no_commit)
547                         res = run_git_commit(defmsg, opts, allow);
548         }
549
550         free_message(&msg);
551         free(defmsg);
552
553         return res;
554 }
555
556 static void prepare_revs(struct replay_opts *opts)
557 {
558         /*
559          * picking (but not reverting) ranges (but not individual revisions)
560          * should be done in reverse
561          */
562         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
563                 opts->revs->reverse ^= 1;
564
565         if (prepare_revision_walk(opts->revs))
566                 die(_("revision walk setup failed"));
567
568         if (!opts->revs->commits)
569                 die(_("empty commit set passed"));
570 }
571
572 static void read_and_refresh_cache(struct replay_opts *opts)
573 {
574         static struct lock_file index_lock;
575         int index_fd = hold_locked_index(&index_lock, 0);
576         if (read_index_preload(&the_index, NULL) < 0)
577                 die(_("git %s: failed to read the index"), action_name(opts));
578         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
579         if (the_index.cache_changed) {
580                 if (write_index(&the_index, index_fd) ||
581                     commit_locked_index(&index_lock))
582                         die(_("git %s: failed to refresh the index"), action_name(opts));
583         }
584         rollback_lock_file(&index_lock);
585 }
586
587 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
588                 struct replay_opts *opts)
589 {
590         struct commit_list *cur = NULL;
591         const char *sha1_abbrev = NULL;
592         const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
593         const char *subject;
594         int subject_len;
595
596         for (cur = todo_list; cur; cur = cur->next) {
597                 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
598                 subject_len = find_commit_subject(cur->item->buffer, &subject);
599                 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
600                         subject_len, subject);
601         }
602         return 0;
603 }
604
605 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
606 {
607         unsigned char commit_sha1[20];
608         enum replay_action action;
609         char *end_of_object_name;
610         int saved, status, padding;
611
612         if (!prefixcmp(bol, "pick")) {
613                 action = REPLAY_PICK;
614                 bol += strlen("pick");
615         } else if (!prefixcmp(bol, "revert")) {
616                 action = REPLAY_REVERT;
617                 bol += strlen("revert");
618         } else
619                 return NULL;
620
621         /* Eat up extra spaces/ tabs before object name */
622         padding = strspn(bol, " \t");
623         if (!padding)
624                 return NULL;
625         bol += padding;
626
627         end_of_object_name = bol + strcspn(bol, " \t\n");
628         saved = *end_of_object_name;
629         *end_of_object_name = '\0';
630         status = get_sha1(bol, commit_sha1);
631         *end_of_object_name = saved;
632
633         /*
634          * Verify that the action matches up with the one in
635          * opts; we don't support arbitrary instructions
636          */
637         if (action != opts->action) {
638                 const char *action_str;
639                 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
640                 error(_("Cannot %s during a %s"), action_str, action_name(opts));
641                 return NULL;
642         }
643
644         if (status < 0)
645                 return NULL;
646
647         return lookup_commit_reference(commit_sha1);
648 }
649
650 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
651                         struct replay_opts *opts)
652 {
653         struct commit_list **next = todo_list;
654         struct commit *commit;
655         char *p = buf;
656         int i;
657
658         for (i = 1; *p; i++) {
659                 char *eol = strchrnul(p, '\n');
660                 commit = parse_insn_line(p, eol, opts);
661                 if (!commit)
662                         return error(_("Could not parse line %d."), i);
663                 next = commit_list_append(commit, next);
664                 p = *eol ? eol + 1 : eol;
665         }
666         if (!*todo_list)
667                 return error(_("No commits parsed."));
668         return 0;
669 }
670
671 static void read_populate_todo(struct commit_list **todo_list,
672                         struct replay_opts *opts)
673 {
674         const char *todo_file = git_path(SEQ_TODO_FILE);
675         struct strbuf buf = STRBUF_INIT;
676         int fd, res;
677
678         fd = open(todo_file, O_RDONLY);
679         if (fd < 0)
680                 die_errno(_("Could not open %s"), todo_file);
681         if (strbuf_read(&buf, fd, 0) < 0) {
682                 close(fd);
683                 strbuf_release(&buf);
684                 die(_("Could not read %s."), todo_file);
685         }
686         close(fd);
687
688         res = parse_insn_buffer(buf.buf, todo_list, opts);
689         strbuf_release(&buf);
690         if (res)
691                 die(_("Unusable instruction sheet: %s"), todo_file);
692 }
693
694 static int populate_opts_cb(const char *key, const char *value, void *data)
695 {
696         struct replay_opts *opts = data;
697         int error_flag = 1;
698
699         if (!value)
700                 error_flag = 0;
701         else if (!strcmp(key, "options.no-commit"))
702                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
703         else if (!strcmp(key, "options.edit"))
704                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
705         else if (!strcmp(key, "options.signoff"))
706                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
707         else if (!strcmp(key, "options.record-origin"))
708                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
709         else if (!strcmp(key, "options.allow-ff"))
710                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
711         else if (!strcmp(key, "options.mainline"))
712                 opts->mainline = git_config_int(key, value);
713         else if (!strcmp(key, "options.strategy"))
714                 git_config_string(&opts->strategy, key, value);
715         else if (!strcmp(key, "options.strategy-option")) {
716                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
717                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
718         } else
719                 return error(_("Invalid key: %s"), key);
720
721         if (!error_flag)
722                 return error(_("Invalid value for %s: %s"), key, value);
723
724         return 0;
725 }
726
727 static void read_populate_opts(struct replay_opts **opts_ptr)
728 {
729         const char *opts_file = git_path(SEQ_OPTS_FILE);
730
731         if (!file_exists(opts_file))
732                 return;
733         if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
734                 die(_("Malformed options sheet: %s"), opts_file);
735 }
736
737 static void walk_revs_populate_todo(struct commit_list **todo_list,
738                                 struct replay_opts *opts)
739 {
740         struct commit *commit;
741         struct commit_list **next;
742
743         prepare_revs(opts);
744
745         next = todo_list;
746         while ((commit = get_revision(opts->revs)))
747                 next = commit_list_append(commit, next);
748 }
749
750 static int create_seq_dir(void)
751 {
752         const char *seq_dir = git_path(SEQ_DIR);
753
754         if (file_exists(seq_dir)) {
755                 error(_("a cherry-pick or revert is already in progress"));
756                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
757                 return -1;
758         }
759         else if (mkdir(seq_dir, 0777) < 0)
760                 die_errno(_("Could not create sequencer directory %s"), seq_dir);
761         return 0;
762 }
763
764 static void save_head(const char *head)
765 {
766         const char *head_file = git_path(SEQ_HEAD_FILE);
767         static struct lock_file head_lock;
768         struct strbuf buf = STRBUF_INIT;
769         int fd;
770
771         fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
772         strbuf_addf(&buf, "%s\n", head);
773         if (write_in_full(fd, buf.buf, buf.len) < 0)
774                 die_errno(_("Could not write to %s"), head_file);
775         if (commit_lock_file(&head_lock) < 0)
776                 die(_("Error wrapping up %s."), head_file);
777 }
778
779 static int reset_for_rollback(const unsigned char *sha1)
780 {
781         const char *argv[4];    /* reset --merge <arg> + NULL */
782         argv[0] = "reset";
783         argv[1] = "--merge";
784         argv[2] = sha1_to_hex(sha1);
785         argv[3] = NULL;
786         return run_command_v_opt(argv, RUN_GIT_CMD);
787 }
788
789 static int rollback_single_pick(void)
790 {
791         unsigned char head_sha1[20];
792
793         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
794             !file_exists(git_path("REVERT_HEAD")))
795                 return error(_("no cherry-pick or revert in progress"));
796         if (read_ref_full("HEAD", head_sha1, 0, NULL))
797                 return error(_("cannot resolve HEAD"));
798         if (is_null_sha1(head_sha1))
799                 return error(_("cannot abort from a branch yet to be born"));
800         return reset_for_rollback(head_sha1);
801 }
802
803 static int sequencer_rollback(struct replay_opts *opts)
804 {
805         const char *filename;
806         FILE *f;
807         unsigned char sha1[20];
808         struct strbuf buf = STRBUF_INIT;
809
810         filename = git_path(SEQ_HEAD_FILE);
811         f = fopen(filename, "r");
812         if (!f && errno == ENOENT) {
813                 /*
814                  * There is no multiple-cherry-pick in progress.
815                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
816                  * a single-cherry-pick in progress, abort that.
817                  */
818                 return rollback_single_pick();
819         }
820         if (!f)
821                 return error(_("cannot open %s: %s"), filename,
822                                                 strerror(errno));
823         if (strbuf_getline(&buf, f, '\n')) {
824                 error(_("cannot read %s: %s"), filename, ferror(f) ?
825                         strerror(errno) : _("unexpected end of file"));
826                 fclose(f);
827                 goto fail;
828         }
829         fclose(f);
830         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
831                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
832                         filename);
833                 goto fail;
834         }
835         if (reset_for_rollback(sha1))
836                 goto fail;
837         remove_sequencer_state();
838         strbuf_release(&buf);
839         return 0;
840 fail:
841         strbuf_release(&buf);
842         return -1;
843 }
844
845 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
846 {
847         const char *todo_file = git_path(SEQ_TODO_FILE);
848         static struct lock_file todo_lock;
849         struct strbuf buf = STRBUF_INIT;
850         int fd;
851
852         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
853         if (format_todo(&buf, todo_list, opts) < 0)
854                 die(_("Could not format %s."), todo_file);
855         if (write_in_full(fd, buf.buf, buf.len) < 0) {
856                 strbuf_release(&buf);
857                 die_errno(_("Could not write to %s"), todo_file);
858         }
859         if (commit_lock_file(&todo_lock) < 0) {
860                 strbuf_release(&buf);
861                 die(_("Error wrapping up %s."), todo_file);
862         }
863         strbuf_release(&buf);
864 }
865
866 static void save_opts(struct replay_opts *opts)
867 {
868         const char *opts_file = git_path(SEQ_OPTS_FILE);
869
870         if (opts->no_commit)
871                 git_config_set_in_file(opts_file, "options.no-commit", "true");
872         if (opts->edit)
873                 git_config_set_in_file(opts_file, "options.edit", "true");
874         if (opts->signoff)
875                 git_config_set_in_file(opts_file, "options.signoff", "true");
876         if (opts->record_origin)
877                 git_config_set_in_file(opts_file, "options.record-origin", "true");
878         if (opts->allow_ff)
879                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
880         if (opts->mainline) {
881                 struct strbuf buf = STRBUF_INIT;
882                 strbuf_addf(&buf, "%d", opts->mainline);
883                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
884                 strbuf_release(&buf);
885         }
886         if (opts->strategy)
887                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
888         if (opts->xopts) {
889                 int i;
890                 for (i = 0; i < opts->xopts_nr; i++)
891                         git_config_set_multivar_in_file(opts_file,
892                                                         "options.strategy-option",
893                                                         opts->xopts[i], "^$", 0);
894         }
895 }
896
897 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
898 {
899         struct commit_list *cur;
900         int res;
901
902         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
903         if (opts->allow_ff)
904                 assert(!(opts->signoff || opts->no_commit ||
905                                 opts->record_origin || opts->edit));
906         read_and_refresh_cache(opts);
907
908         for (cur = todo_list; cur; cur = cur->next) {
909                 save_todo(cur, opts);
910                 res = do_pick_commit(cur->item, opts);
911                 if (res)
912                         return res;
913         }
914
915         /*
916          * Sequence of picks finished successfully; cleanup by
917          * removing the .git/sequencer directory
918          */
919         remove_sequencer_state();
920         return 0;
921 }
922
923 static int continue_single_pick(void)
924 {
925         const char *argv[] = { "commit", NULL };
926
927         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
928             !file_exists(git_path("REVERT_HEAD")))
929                 return error(_("no cherry-pick or revert in progress"));
930         return run_command_v_opt(argv, RUN_GIT_CMD);
931 }
932
933 static int sequencer_continue(struct replay_opts *opts)
934 {
935         struct commit_list *todo_list = NULL;
936
937         if (!file_exists(git_path(SEQ_TODO_FILE)))
938                 return continue_single_pick();
939         read_populate_opts(&opts);
940         read_populate_todo(&todo_list, opts);
941
942         /* Verify that the conflict has been resolved */
943         if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
944             file_exists(git_path("REVERT_HEAD"))) {
945                 int ret = continue_single_pick();
946                 if (ret)
947                         return ret;
948         }
949         if (index_differs_from("HEAD", 0))
950                 return error_dirty_index(opts);
951         todo_list = todo_list->next;
952         return pick_commits(todo_list, opts);
953 }
954
955 static int single_pick(struct commit *cmit, struct replay_opts *opts)
956 {
957         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
958         return do_pick_commit(cmit, opts);
959 }
960
961 int sequencer_pick_revisions(struct replay_opts *opts)
962 {
963         struct commit_list *todo_list = NULL;
964         unsigned char sha1[20];
965
966         if (opts->subcommand == REPLAY_NONE)
967                 assert(opts->revs);
968
969         read_and_refresh_cache(opts);
970
971         /*
972          * Decide what to do depending on the arguments; a fresh
973          * cherry-pick should be handled differently from an existing
974          * one that is being continued
975          */
976         if (opts->subcommand == REPLAY_REMOVE_STATE) {
977                 remove_sequencer_state();
978                 return 0;
979         }
980         if (opts->subcommand == REPLAY_ROLLBACK)
981                 return sequencer_rollback(opts);
982         if (opts->subcommand == REPLAY_CONTINUE)
983                 return sequencer_continue(opts);
984
985         /*
986          * If we were called as "git cherry-pick <commit>", just
987          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
988          * REVERT_HEAD, and don't touch the sequencer state.
989          * This means it is possible to cherry-pick in the middle
990          * of a cherry-pick sequence.
991          */
992         if (opts->revs->cmdline.nr == 1 &&
993             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
994             opts->revs->no_walk &&
995             !opts->revs->cmdline.rev->flags) {
996                 struct commit *cmit;
997                 if (prepare_revision_walk(opts->revs))
998                         die(_("revision walk setup failed"));
999                 cmit = get_revision(opts->revs);
1000                 if (!cmit || get_revision(opts->revs))
1001                         die("BUG: expected exactly one commit from walk");
1002                 return single_pick(cmit, opts);
1003         }
1004
1005         /*
1006          * Start a new cherry-pick/ revert sequence; but
1007          * first, make sure that an existing one isn't in
1008          * progress
1009          */
1010
1011         walk_revs_populate_todo(&todo_list, opts);
1012         if (create_seq_dir() < 0)
1013                 return -1;
1014         if (get_sha1("HEAD", sha1)) {
1015                 if (opts->action == REPLAY_REVERT)
1016                         return error(_("Can't revert as initial commit"));
1017                 return error(_("Can't cherry-pick into empty head"));
1018         }
1019         save_head(sha1_to_hex(sha1));
1020         save_opts(opts);
1021         return pick_commits(todo_list, opts);
1022 }
1023
1024 static int ends_rfc2822_footer(struct strbuf *sb, int ignore_footer)
1025 {
1026         int ch;
1027         int hit = 0;
1028         int i, j, k;
1029         int len = sb->len - ignore_footer;
1030         int first = 1;
1031         const char *buf = sb->buf;
1032
1033         for (i = len - 1; i > 0; i--) {
1034                 if (hit && buf[i] == '\n')
1035                         break;
1036                 hit = (buf[i] == '\n');
1037         }
1038
1039         while (i < len - 1 && buf[i] == '\n')
1040                 i++;
1041
1042         for (; i < len; i = k) {
1043                 for (k = i; k < len && buf[k] != '\n'; k++)
1044                         ; /* do nothing */
1045                 k++;
1046
1047                 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
1048                         continue;
1049
1050                 first = 0;
1051
1052                 for (j = 0; i + j < len; j++) {
1053                         ch = buf[i + j];
1054                         if (ch == ':')
1055                                 break;
1056                         if (isalnum(ch) ||
1057                             (ch == '-'))
1058                                 continue;
1059                         return 0;
1060                 }
1061         }
1062         return 1;
1063 }
1064
1065 void append_signoff(struct strbuf *msgbuf, int ignore_footer)
1066 {
1067         struct strbuf sob = STRBUF_INIT;
1068         int i;
1069
1070         strbuf_addstr(&sob, sign_off_header);
1071         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1072                                 getenv("GIT_COMMITTER_EMAIL")));
1073         strbuf_addch(&sob, '\n');
1074         for (i = msgbuf->len - 1 - ignore_footer; i > 0 && msgbuf->buf[i - 1] != '\n'; i--)
1075                 ; /* do nothing */
1076         if (prefixcmp(msgbuf->buf + i, sob.buf)) {
1077                 if (!i || !ends_rfc2822_footer(msgbuf, ignore_footer))
1078                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, "\n", 1);
1079                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, sob.buf, sob.len);
1080         }
1081         strbuf_release(&sob);
1082 }