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