git-svn: make Git::SVN::RA a separate file
[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         if (opts->action != REPLAY_REVERT)
547                 opts->revs->reverse ^= 1;
548
549         if (prepare_revision_walk(opts->revs))
550                 die(_("revision walk setup failed"));
551
552         if (!opts->revs->commits)
553                 die(_("empty commit set passed"));
554 }
555
556 static void read_and_refresh_cache(struct replay_opts *opts)
557 {
558         static struct lock_file index_lock;
559         int index_fd = hold_locked_index(&index_lock, 0);
560         if (read_index_preload(&the_index, NULL) < 0)
561                 die(_("git %s: failed to read the index"), action_name(opts));
562         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
563         if (the_index.cache_changed) {
564                 if (write_index(&the_index, index_fd) ||
565                     commit_locked_index(&index_lock))
566                         die(_("git %s: failed to refresh the index"), action_name(opts));
567         }
568         rollback_lock_file(&index_lock);
569 }
570
571 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
572                 struct replay_opts *opts)
573 {
574         struct commit_list *cur = NULL;
575         const char *sha1_abbrev = NULL;
576         const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
577         const char *subject;
578         int subject_len;
579
580         for (cur = todo_list; cur; cur = cur->next) {
581                 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
582                 subject_len = find_commit_subject(cur->item->buffer, &subject);
583                 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
584                         subject_len, subject);
585         }
586         return 0;
587 }
588
589 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
590 {
591         unsigned char commit_sha1[20];
592         enum replay_action action;
593         char *end_of_object_name;
594         int saved, status, padding;
595
596         if (!prefixcmp(bol, "pick")) {
597                 action = REPLAY_PICK;
598                 bol += strlen("pick");
599         } else if (!prefixcmp(bol, "revert")) {
600                 action = REPLAY_REVERT;
601                 bol += strlen("revert");
602         } else
603                 return NULL;
604
605         /* Eat up extra spaces/ tabs before object name */
606         padding = strspn(bol, " \t");
607         if (!padding)
608                 return NULL;
609         bol += padding;
610
611         end_of_object_name = bol + strcspn(bol, " \t\n");
612         saved = *end_of_object_name;
613         *end_of_object_name = '\0';
614         status = get_sha1(bol, commit_sha1);
615         *end_of_object_name = saved;
616
617         /*
618          * Verify that the action matches up with the one in
619          * opts; we don't support arbitrary instructions
620          */
621         if (action != opts->action) {
622                 const char *action_str;
623                 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
624                 error(_("Cannot %s during a %s"), action_str, action_name(opts));
625                 return NULL;
626         }
627
628         if (status < 0)
629                 return NULL;
630
631         return lookup_commit_reference(commit_sha1);
632 }
633
634 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
635                         struct replay_opts *opts)
636 {
637         struct commit_list **next = todo_list;
638         struct commit *commit;
639         char *p = buf;
640         int i;
641
642         for (i = 1; *p; i++) {
643                 char *eol = strchrnul(p, '\n');
644                 commit = parse_insn_line(p, eol, opts);
645                 if (!commit)
646                         return error(_("Could not parse line %d."), i);
647                 next = commit_list_append(commit, next);
648                 p = *eol ? eol + 1 : eol;
649         }
650         if (!*todo_list)
651                 return error(_("No commits parsed."));
652         return 0;
653 }
654
655 static void read_populate_todo(struct commit_list **todo_list,
656                         struct replay_opts *opts)
657 {
658         const char *todo_file = git_path(SEQ_TODO_FILE);
659         struct strbuf buf = STRBUF_INIT;
660         int fd, res;
661
662         fd = open(todo_file, O_RDONLY);
663         if (fd < 0)
664                 die_errno(_("Could not open %s"), todo_file);
665         if (strbuf_read(&buf, fd, 0) < 0) {
666                 close(fd);
667                 strbuf_release(&buf);
668                 die(_("Could not read %s."), todo_file);
669         }
670         close(fd);
671
672         res = parse_insn_buffer(buf.buf, todo_list, opts);
673         strbuf_release(&buf);
674         if (res)
675                 die(_("Unusable instruction sheet: %s"), todo_file);
676 }
677
678 static int populate_opts_cb(const char *key, const char *value, void *data)
679 {
680         struct replay_opts *opts = data;
681         int error_flag = 1;
682
683         if (!value)
684                 error_flag = 0;
685         else if (!strcmp(key, "options.no-commit"))
686                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
687         else if (!strcmp(key, "options.edit"))
688                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
689         else if (!strcmp(key, "options.signoff"))
690                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
691         else if (!strcmp(key, "options.record-origin"))
692                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
693         else if (!strcmp(key, "options.allow-ff"))
694                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
695         else if (!strcmp(key, "options.mainline"))
696                 opts->mainline = git_config_int(key, value);
697         else if (!strcmp(key, "options.strategy"))
698                 git_config_string(&opts->strategy, key, value);
699         else if (!strcmp(key, "options.strategy-option")) {
700                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
701                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
702         } else
703                 return error(_("Invalid key: %s"), key);
704
705         if (!error_flag)
706                 return error(_("Invalid value for %s: %s"), key, value);
707
708         return 0;
709 }
710
711 static void read_populate_opts(struct replay_opts **opts_ptr)
712 {
713         const char *opts_file = git_path(SEQ_OPTS_FILE);
714
715         if (!file_exists(opts_file))
716                 return;
717         if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
718                 die(_("Malformed options sheet: %s"), opts_file);
719 }
720
721 static void walk_revs_populate_todo(struct commit_list **todo_list,
722                                 struct replay_opts *opts)
723 {
724         struct commit *commit;
725         struct commit_list **next;
726
727         prepare_revs(opts);
728
729         next = todo_list;
730         while ((commit = get_revision(opts->revs)))
731                 next = commit_list_append(commit, next);
732 }
733
734 static int create_seq_dir(void)
735 {
736         const char *seq_dir = git_path(SEQ_DIR);
737
738         if (file_exists(seq_dir)) {
739                 error(_("a cherry-pick or revert is already in progress"));
740                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
741                 return -1;
742         }
743         else if (mkdir(seq_dir, 0777) < 0)
744                 die_errno(_("Could not create sequencer directory %s"), seq_dir);
745         return 0;
746 }
747
748 static void save_head(const char *head)
749 {
750         const char *head_file = git_path(SEQ_HEAD_FILE);
751         static struct lock_file head_lock;
752         struct strbuf buf = STRBUF_INIT;
753         int fd;
754
755         fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
756         strbuf_addf(&buf, "%s\n", head);
757         if (write_in_full(fd, buf.buf, buf.len) < 0)
758                 die_errno(_("Could not write to %s"), head_file);
759         if (commit_lock_file(&head_lock) < 0)
760                 die(_("Error wrapping up %s."), head_file);
761 }
762
763 static int reset_for_rollback(const unsigned char *sha1)
764 {
765         const char *argv[4];    /* reset --merge <arg> + NULL */
766         argv[0] = "reset";
767         argv[1] = "--merge";
768         argv[2] = sha1_to_hex(sha1);
769         argv[3] = NULL;
770         return run_command_v_opt(argv, RUN_GIT_CMD);
771 }
772
773 static int rollback_single_pick(void)
774 {
775         unsigned char head_sha1[20];
776
777         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
778             !file_exists(git_path("REVERT_HEAD")))
779                 return error(_("no cherry-pick or revert in progress"));
780         if (read_ref_full("HEAD", head_sha1, 0, NULL))
781                 return error(_("cannot resolve HEAD"));
782         if (is_null_sha1(head_sha1))
783                 return error(_("cannot abort from a branch yet to be born"));
784         return reset_for_rollback(head_sha1);
785 }
786
787 static int sequencer_rollback(struct replay_opts *opts)
788 {
789         const char *filename;
790         FILE *f;
791         unsigned char sha1[20];
792         struct strbuf buf = STRBUF_INIT;
793
794         filename = git_path(SEQ_HEAD_FILE);
795         f = fopen(filename, "r");
796         if (!f && errno == ENOENT) {
797                 /*
798                  * There is no multiple-cherry-pick in progress.
799                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
800                  * a single-cherry-pick in progress, abort that.
801                  */
802                 return rollback_single_pick();
803         }
804         if (!f)
805                 return error(_("cannot open %s: %s"), filename,
806                                                 strerror(errno));
807         if (strbuf_getline(&buf, f, '\n')) {
808                 error(_("cannot read %s: %s"), filename, ferror(f) ?
809                         strerror(errno) : _("unexpected end of file"));
810                 fclose(f);
811                 goto fail;
812         }
813         fclose(f);
814         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
815                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
816                         filename);
817                 goto fail;
818         }
819         if (reset_for_rollback(sha1))
820                 goto fail;
821         remove_sequencer_state();
822         strbuf_release(&buf);
823         return 0;
824 fail:
825         strbuf_release(&buf);
826         return -1;
827 }
828
829 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
830 {
831         const char *todo_file = git_path(SEQ_TODO_FILE);
832         static struct lock_file todo_lock;
833         struct strbuf buf = STRBUF_INIT;
834         int fd;
835
836         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
837         if (format_todo(&buf, todo_list, opts) < 0)
838                 die(_("Could not format %s."), todo_file);
839         if (write_in_full(fd, buf.buf, buf.len) < 0) {
840                 strbuf_release(&buf);
841                 die_errno(_("Could not write to %s"), todo_file);
842         }
843         if (commit_lock_file(&todo_lock) < 0) {
844                 strbuf_release(&buf);
845                 die(_("Error wrapping up %s."), todo_file);
846         }
847         strbuf_release(&buf);
848 }
849
850 static void save_opts(struct replay_opts *opts)
851 {
852         const char *opts_file = git_path(SEQ_OPTS_FILE);
853
854         if (opts->no_commit)
855                 git_config_set_in_file(opts_file, "options.no-commit", "true");
856         if (opts->edit)
857                 git_config_set_in_file(opts_file, "options.edit", "true");
858         if (opts->signoff)
859                 git_config_set_in_file(opts_file, "options.signoff", "true");
860         if (opts->record_origin)
861                 git_config_set_in_file(opts_file, "options.record-origin", "true");
862         if (opts->allow_ff)
863                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
864         if (opts->mainline) {
865                 struct strbuf buf = STRBUF_INIT;
866                 strbuf_addf(&buf, "%d", opts->mainline);
867                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
868                 strbuf_release(&buf);
869         }
870         if (opts->strategy)
871                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
872         if (opts->xopts) {
873                 int i;
874                 for (i = 0; i < opts->xopts_nr; i++)
875                         git_config_set_multivar_in_file(opts_file,
876                                                         "options.strategy-option",
877                                                         opts->xopts[i], "^$", 0);
878         }
879 }
880
881 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
882 {
883         struct commit_list *cur;
884         int res;
885
886         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
887         if (opts->allow_ff)
888                 assert(!(opts->signoff || opts->no_commit ||
889                                 opts->record_origin || opts->edit));
890         read_and_refresh_cache(opts);
891
892         for (cur = todo_list; cur; cur = cur->next) {
893                 save_todo(cur, opts);
894                 res = do_pick_commit(cur->item, opts);
895                 if (res)
896                         return res;
897         }
898
899         /*
900          * Sequence of picks finished successfully; cleanup by
901          * removing the .git/sequencer directory
902          */
903         remove_sequencer_state();
904         return 0;
905 }
906
907 static int continue_single_pick(void)
908 {
909         const char *argv[] = { "commit", NULL };
910
911         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
912             !file_exists(git_path("REVERT_HEAD")))
913                 return error(_("no cherry-pick or revert in progress"));
914         return run_command_v_opt(argv, RUN_GIT_CMD);
915 }
916
917 static int sequencer_continue(struct replay_opts *opts)
918 {
919         struct commit_list *todo_list = NULL;
920
921         if (!file_exists(git_path(SEQ_TODO_FILE)))
922                 return continue_single_pick();
923         read_populate_opts(&opts);
924         read_populate_todo(&todo_list, opts);
925
926         /* Verify that the conflict has been resolved */
927         if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
928             file_exists(git_path("REVERT_HEAD"))) {
929                 int ret = continue_single_pick();
930                 if (ret)
931                         return ret;
932         }
933         if (index_differs_from("HEAD", 0))
934                 return error_dirty_index(opts);
935         todo_list = todo_list->next;
936         return pick_commits(todo_list, opts);
937 }
938
939 static int single_pick(struct commit *cmit, struct replay_opts *opts)
940 {
941         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
942         return do_pick_commit(cmit, opts);
943 }
944
945 int sequencer_pick_revisions(struct replay_opts *opts)
946 {
947         struct commit_list *todo_list = NULL;
948         unsigned char sha1[20];
949
950         if (opts->subcommand == REPLAY_NONE)
951                 assert(opts->revs);
952
953         read_and_refresh_cache(opts);
954
955         /*
956          * Decide what to do depending on the arguments; a fresh
957          * cherry-pick should be handled differently from an existing
958          * one that is being continued
959          */
960         if (opts->subcommand == REPLAY_REMOVE_STATE) {
961                 remove_sequencer_state();
962                 return 0;
963         }
964         if (opts->subcommand == REPLAY_ROLLBACK)
965                 return sequencer_rollback(opts);
966         if (opts->subcommand == REPLAY_CONTINUE)
967                 return sequencer_continue(opts);
968
969         /*
970          * If we were called as "git cherry-pick <commit>", just
971          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
972          * REVERT_HEAD, and don't touch the sequencer state.
973          * This means it is possible to cherry-pick in the middle
974          * of a cherry-pick sequence.
975          */
976         if (opts->revs->cmdline.nr == 1 &&
977             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
978             opts->revs->no_walk &&
979             !opts->revs->cmdline.rev->flags) {
980                 struct commit *cmit;
981                 if (prepare_revision_walk(opts->revs))
982                         die(_("revision walk setup failed"));
983                 cmit = get_revision(opts->revs);
984                 if (!cmit || get_revision(opts->revs))
985                         die("BUG: expected exactly one commit from walk");
986                 return single_pick(cmit, opts);
987         }
988
989         /*
990          * Start a new cherry-pick/ revert sequence; but
991          * first, make sure that an existing one isn't in
992          * progress
993          */
994
995         walk_revs_populate_todo(&todo_list, opts);
996         if (create_seq_dir() < 0)
997                 return -1;
998         if (get_sha1("HEAD", sha1)) {
999                 if (opts->action == REPLAY_REVERT)
1000                         return error(_("Can't revert as initial commit"));
1001                 return error(_("Can't cherry-pick into empty head"));
1002         }
1003         save_head(sha1_to_hex(sha1));
1004         save_opts(opts);
1005         return pick_commits(todo_list, opts);
1006 }