Sync with 1.7.12.1
[git.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         if (opts->allow_empty_message)
315                 argv_array_push(&array, "--allow-empty-message");
316
317         rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
318         argv_array_clear(&array);
319         return rc;
320 }
321
322 static int is_original_commit_empty(struct commit *commit)
323 {
324         const unsigned char *ptree_sha1;
325
326         if (parse_commit(commit))
327                 return error(_("Could not parse commit %s\n"),
328                              sha1_to_hex(commit->object.sha1));
329         if (commit->parents) {
330                 struct commit *parent = commit->parents->item;
331                 if (parse_commit(parent))
332                         return error(_("Could not parse parent commit %s\n"),
333                                 sha1_to_hex(parent->object.sha1));
334                 ptree_sha1 = parent->tree->object.sha1;
335         } else {
336                 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
337         }
338
339         return !hashcmp(ptree_sha1, commit->tree->object.sha1);
340 }
341
342 /*
343  * Do we run "git commit" with "--allow-empty"?
344  */
345 static int allow_empty(struct replay_opts *opts, struct commit *commit)
346 {
347         int index_unchanged, empty_commit;
348
349         /*
350          * Three cases:
351          *
352          * (1) we do not allow empty at all and error out.
353          *
354          * (2) we allow ones that were initially empty, but
355          * forbid the ones that become empty;
356          *
357          * (3) we allow both.
358          */
359         if (!opts->allow_empty)
360                 return 0; /* let "git commit" barf as necessary */
361
362         index_unchanged = is_index_unchanged();
363         if (index_unchanged < 0)
364                 return index_unchanged;
365         if (!index_unchanged)
366                 return 0; /* we do not have to say --allow-empty */
367
368         if (opts->keep_redundant_commits)
369                 return 1;
370
371         empty_commit = is_original_commit_empty(commit);
372         if (empty_commit < 0)
373                 return empty_commit;
374         if (!empty_commit)
375                 return 0;
376         else
377                 return 1;
378 }
379
380 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
381 {
382         unsigned char head[20];
383         struct commit *base, *next, *parent;
384         const char *base_label, *next_label;
385         struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
386         char *defmsg = NULL;
387         struct strbuf msgbuf = STRBUF_INIT;
388         int res;
389
390         if (opts->no_commit) {
391                 /*
392                  * We do not intend to commit immediately.  We just want to
393                  * merge the differences in, so let's compute the tree
394                  * that represents the "current" state for merge-recursive
395                  * to work on.
396                  */
397                 if (write_cache_as_tree(head, 0, NULL))
398                         die (_("Your index file is unmerged."));
399         } else {
400                 if (get_sha1("HEAD", head))
401                         return error(_("You do not have a valid HEAD"));
402                 if (index_differs_from("HEAD", 0))
403                         return error_dirty_index(opts);
404         }
405         discard_cache();
406
407         if (!commit->parents) {
408                 parent = NULL;
409         }
410         else if (commit->parents->next) {
411                 /* Reverting or cherry-picking a merge commit */
412                 int cnt;
413                 struct commit_list *p;
414
415                 if (!opts->mainline)
416                         return error(_("Commit %s is a merge but no -m option was given."),
417                                 sha1_to_hex(commit->object.sha1));
418
419                 for (cnt = 1, p = commit->parents;
420                      cnt != opts->mainline && p;
421                      cnt++)
422                         p = p->next;
423                 if (cnt != opts->mainline || !p)
424                         return error(_("Commit %s does not have parent %d"),
425                                 sha1_to_hex(commit->object.sha1), opts->mainline);
426                 parent = p->item;
427         } else if (0 < opts->mainline)
428                 return error(_("Mainline was specified but commit %s is not a merge."),
429                         sha1_to_hex(commit->object.sha1));
430         else
431                 parent = commit->parents->item;
432
433         if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
434                 return fast_forward_to(commit->object.sha1, head);
435
436         if (parent && parse_commit(parent) < 0)
437                 /* TRANSLATORS: The first %s will be "revert" or
438                    "cherry-pick", the second %s a SHA1 */
439                 return error(_("%s: cannot parse parent commit %s"),
440                         action_name(opts), sha1_to_hex(parent->object.sha1));
441
442         if (get_message(commit, &msg) != 0)
443                 return error(_("Cannot get commit message for %s"),
444                         sha1_to_hex(commit->object.sha1));
445
446         /*
447          * "commit" is an existing commit.  We would want to apply
448          * the difference it introduces since its first parent "prev"
449          * on top of the current HEAD if we are cherry-pick.  Or the
450          * reverse of it if we are revert.
451          */
452
453         defmsg = git_pathdup("MERGE_MSG");
454
455         if (opts->action == REPLAY_REVERT) {
456                 base = commit;
457                 base_label = msg.label;
458                 next = parent;
459                 next_label = msg.parent_label;
460                 strbuf_addstr(&msgbuf, "Revert \"");
461                 strbuf_addstr(&msgbuf, msg.subject);
462                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
463                 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
464
465                 if (commit->parents && commit->parents->next) {
466                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
467                         strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
468                 }
469                 strbuf_addstr(&msgbuf, ".\n");
470         } else {
471                 const char *p;
472
473                 base = parent;
474                 base_label = msg.parent_label;
475                 next = commit;
476                 next_label = msg.label;
477
478                 /*
479                  * Append the commit log message to msgbuf; it starts
480                  * after the tree, parent, author, committer
481                  * information followed by "\n\n".
482                  */
483                 p = strstr(msg.message, "\n\n");
484                 if (p) {
485                         p += 2;
486                         strbuf_addstr(&msgbuf, p);
487                 }
488
489                 if (opts->record_origin) {
490                         strbuf_addstr(&msgbuf, "(cherry picked from commit ");
491                         strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
492                         strbuf_addstr(&msgbuf, ")\n");
493                 }
494         }
495
496         if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
497                 res = do_recursive_merge(base, next, base_label, next_label,
498                                          head, &msgbuf, opts);
499                 write_message(&msgbuf, defmsg);
500         } else {
501                 struct commit_list *common = NULL;
502                 struct commit_list *remotes = NULL;
503
504                 write_message(&msgbuf, defmsg);
505
506                 commit_list_insert(base, &common);
507                 commit_list_insert(next, &remotes);
508                 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
509                                         common, sha1_to_hex(head), remotes);
510                 free_commit_list(common);
511                 free_commit_list(remotes);
512         }
513
514         /*
515          * If the merge was clean or if it failed due to conflict, we write
516          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
517          * However, if the merge did not even start, then we don't want to
518          * write it at all.
519          */
520         if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
521                 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
522         if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
523                 write_cherry_pick_head(commit, "REVERT_HEAD");
524
525         if (res) {
526                 error(opts->action == REPLAY_REVERT
527                       ? _("could not revert %s... %s")
528                       : _("could not apply %s... %s"),
529                       find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
530                       msg.subject);
531                 print_advice(res == 1, opts);
532                 rerere(opts->allow_rerere_auto);
533         } else {
534                 int allow = allow_empty(opts, commit);
535                 if (allow < 0)
536                         return allow;
537                 if (!opts->no_commit)
538                         res = run_git_commit(defmsg, opts, allow);
539         }
540
541         free_message(&msg);
542         free(defmsg);
543
544         return res;
545 }
546
547 static void prepare_revs(struct replay_opts *opts)
548 {
549         /*
550          * picking (but not reverting) ranges (but not individual revisions)
551          * should be done in reverse
552          */
553         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
554                 opts->revs->reverse ^= 1;
555
556         if (prepare_revision_walk(opts->revs))
557                 die(_("revision walk setup failed"));
558
559         if (!opts->revs->commits)
560                 die(_("empty commit set passed"));
561 }
562
563 static void read_and_refresh_cache(struct replay_opts *opts)
564 {
565         static struct lock_file index_lock;
566         int index_fd = hold_locked_index(&index_lock, 0);
567         if (read_index_preload(&the_index, NULL) < 0)
568                 die(_("git %s: failed to read the index"), action_name(opts));
569         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
570         if (the_index.cache_changed) {
571                 if (write_index(&the_index, index_fd) ||
572                     commit_locked_index(&index_lock))
573                         die(_("git %s: failed to refresh the index"), action_name(opts));
574         }
575         rollback_lock_file(&index_lock);
576 }
577
578 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
579                 struct replay_opts *opts)
580 {
581         struct commit_list *cur = NULL;
582         const char *sha1_abbrev = NULL;
583         const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
584         const char *subject;
585         int subject_len;
586
587         for (cur = todo_list; cur; cur = cur->next) {
588                 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
589                 subject_len = find_commit_subject(cur->item->buffer, &subject);
590                 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
591                         subject_len, subject);
592         }
593         return 0;
594 }
595
596 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
597 {
598         unsigned char commit_sha1[20];
599         enum replay_action action;
600         char *end_of_object_name;
601         int saved, status, padding;
602
603         if (!prefixcmp(bol, "pick")) {
604                 action = REPLAY_PICK;
605                 bol += strlen("pick");
606         } else if (!prefixcmp(bol, "revert")) {
607                 action = REPLAY_REVERT;
608                 bol += strlen("revert");
609         } else
610                 return NULL;
611
612         /* Eat up extra spaces/ tabs before object name */
613         padding = strspn(bol, " \t");
614         if (!padding)
615                 return NULL;
616         bol += padding;
617
618         end_of_object_name = bol + strcspn(bol, " \t\n");
619         saved = *end_of_object_name;
620         *end_of_object_name = '\0';
621         status = get_sha1(bol, commit_sha1);
622         *end_of_object_name = saved;
623
624         /*
625          * Verify that the action matches up with the one in
626          * opts; we don't support arbitrary instructions
627          */
628         if (action != opts->action) {
629                 const char *action_str;
630                 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
631                 error(_("Cannot %s during a %s"), action_str, action_name(opts));
632                 return NULL;
633         }
634
635         if (status < 0)
636                 return NULL;
637
638         return lookup_commit_reference(commit_sha1);
639 }
640
641 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
642                         struct replay_opts *opts)
643 {
644         struct commit_list **next = todo_list;
645         struct commit *commit;
646         char *p = buf;
647         int i;
648
649         for (i = 1; *p; i++) {
650                 char *eol = strchrnul(p, '\n');
651                 commit = parse_insn_line(p, eol, opts);
652                 if (!commit)
653                         return error(_("Could not parse line %d."), i);
654                 next = commit_list_append(commit, next);
655                 p = *eol ? eol + 1 : eol;
656         }
657         if (!*todo_list)
658                 return error(_("No commits parsed."));
659         return 0;
660 }
661
662 static void read_populate_todo(struct commit_list **todo_list,
663                         struct replay_opts *opts)
664 {
665         const char *todo_file = git_path(SEQ_TODO_FILE);
666         struct strbuf buf = STRBUF_INIT;
667         int fd, res;
668
669         fd = open(todo_file, O_RDONLY);
670         if (fd < 0)
671                 die_errno(_("Could not open %s"), todo_file);
672         if (strbuf_read(&buf, fd, 0) < 0) {
673                 close(fd);
674                 strbuf_release(&buf);
675                 die(_("Could not read %s."), todo_file);
676         }
677         close(fd);
678
679         res = parse_insn_buffer(buf.buf, todo_list, opts);
680         strbuf_release(&buf);
681         if (res)
682                 die(_("Unusable instruction sheet: %s"), todo_file);
683 }
684
685 static int populate_opts_cb(const char *key, const char *value, void *data)
686 {
687         struct replay_opts *opts = data;
688         int error_flag = 1;
689
690         if (!value)
691                 error_flag = 0;
692         else if (!strcmp(key, "options.no-commit"))
693                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
694         else if (!strcmp(key, "options.edit"))
695                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
696         else if (!strcmp(key, "options.signoff"))
697                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
698         else if (!strcmp(key, "options.record-origin"))
699                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
700         else if (!strcmp(key, "options.allow-ff"))
701                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
702         else if (!strcmp(key, "options.mainline"))
703                 opts->mainline = git_config_int(key, value);
704         else if (!strcmp(key, "options.strategy"))
705                 git_config_string(&opts->strategy, key, value);
706         else if (!strcmp(key, "options.strategy-option")) {
707                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
708                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
709         } else
710                 return error(_("Invalid key: %s"), key);
711
712         if (!error_flag)
713                 return error(_("Invalid value for %s: %s"), key, value);
714
715         return 0;
716 }
717
718 static void read_populate_opts(struct replay_opts **opts_ptr)
719 {
720         const char *opts_file = git_path(SEQ_OPTS_FILE);
721
722         if (!file_exists(opts_file))
723                 return;
724         if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
725                 die(_("Malformed options sheet: %s"), opts_file);
726 }
727
728 static void walk_revs_populate_todo(struct commit_list **todo_list,
729                                 struct replay_opts *opts)
730 {
731         struct commit *commit;
732         struct commit_list **next;
733
734         prepare_revs(opts);
735
736         next = todo_list;
737         while ((commit = get_revision(opts->revs)))
738                 next = commit_list_append(commit, next);
739 }
740
741 static int create_seq_dir(void)
742 {
743         const char *seq_dir = git_path(SEQ_DIR);
744
745         if (file_exists(seq_dir)) {
746                 error(_("a cherry-pick or revert is already in progress"));
747                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
748                 return -1;
749         }
750         else if (mkdir(seq_dir, 0777) < 0)
751                 die_errno(_("Could not create sequencer directory %s"), seq_dir);
752         return 0;
753 }
754
755 static void save_head(const char *head)
756 {
757         const char *head_file = git_path(SEQ_HEAD_FILE);
758         static struct lock_file head_lock;
759         struct strbuf buf = STRBUF_INIT;
760         int fd;
761
762         fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
763         strbuf_addf(&buf, "%s\n", head);
764         if (write_in_full(fd, buf.buf, buf.len) < 0)
765                 die_errno(_("Could not write to %s"), head_file);
766         if (commit_lock_file(&head_lock) < 0)
767                 die(_("Error wrapping up %s."), head_file);
768 }
769
770 static int reset_for_rollback(const unsigned char *sha1)
771 {
772         const char *argv[4];    /* reset --merge <arg> + NULL */
773         argv[0] = "reset";
774         argv[1] = "--merge";
775         argv[2] = sha1_to_hex(sha1);
776         argv[3] = NULL;
777         return run_command_v_opt(argv, RUN_GIT_CMD);
778 }
779
780 static int rollback_single_pick(void)
781 {
782         unsigned char head_sha1[20];
783
784         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
785             !file_exists(git_path("REVERT_HEAD")))
786                 return error(_("no cherry-pick or revert in progress"));
787         if (read_ref_full("HEAD", head_sha1, 0, NULL))
788                 return error(_("cannot resolve HEAD"));
789         if (is_null_sha1(head_sha1))
790                 return error(_("cannot abort from a branch yet to be born"));
791         return reset_for_rollback(head_sha1);
792 }
793
794 static int sequencer_rollback(struct replay_opts *opts)
795 {
796         const char *filename;
797         FILE *f;
798         unsigned char sha1[20];
799         struct strbuf buf = STRBUF_INIT;
800
801         filename = git_path(SEQ_HEAD_FILE);
802         f = fopen(filename, "r");
803         if (!f && errno == ENOENT) {
804                 /*
805                  * There is no multiple-cherry-pick in progress.
806                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
807                  * a single-cherry-pick in progress, abort that.
808                  */
809                 return rollback_single_pick();
810         }
811         if (!f)
812                 return error(_("cannot open %s: %s"), filename,
813                                                 strerror(errno));
814         if (strbuf_getline(&buf, f, '\n')) {
815                 error(_("cannot read %s: %s"), filename, ferror(f) ?
816                         strerror(errno) : _("unexpected end of file"));
817                 fclose(f);
818                 goto fail;
819         }
820         fclose(f);
821         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
822                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
823                         filename);
824                 goto fail;
825         }
826         if (reset_for_rollback(sha1))
827                 goto fail;
828         remove_sequencer_state();
829         strbuf_release(&buf);
830         return 0;
831 fail:
832         strbuf_release(&buf);
833         return -1;
834 }
835
836 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
837 {
838         const char *todo_file = git_path(SEQ_TODO_FILE);
839         static struct lock_file todo_lock;
840         struct strbuf buf = STRBUF_INIT;
841         int fd;
842
843         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
844         if (format_todo(&buf, todo_list, opts) < 0)
845                 die(_("Could not format %s."), todo_file);
846         if (write_in_full(fd, buf.buf, buf.len) < 0) {
847                 strbuf_release(&buf);
848                 die_errno(_("Could not write to %s"), todo_file);
849         }
850         if (commit_lock_file(&todo_lock) < 0) {
851                 strbuf_release(&buf);
852                 die(_("Error wrapping up %s."), todo_file);
853         }
854         strbuf_release(&buf);
855 }
856
857 static void save_opts(struct replay_opts *opts)
858 {
859         const char *opts_file = git_path(SEQ_OPTS_FILE);
860
861         if (opts->no_commit)
862                 git_config_set_in_file(opts_file, "options.no-commit", "true");
863         if (opts->edit)
864                 git_config_set_in_file(opts_file, "options.edit", "true");
865         if (opts->signoff)
866                 git_config_set_in_file(opts_file, "options.signoff", "true");
867         if (opts->record_origin)
868                 git_config_set_in_file(opts_file, "options.record-origin", "true");
869         if (opts->allow_ff)
870                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
871         if (opts->mainline) {
872                 struct strbuf buf = STRBUF_INIT;
873                 strbuf_addf(&buf, "%d", opts->mainline);
874                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
875                 strbuf_release(&buf);
876         }
877         if (opts->strategy)
878                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
879         if (opts->xopts) {
880                 int i;
881                 for (i = 0; i < opts->xopts_nr; i++)
882                         git_config_set_multivar_in_file(opts_file,
883                                                         "options.strategy-option",
884                                                         opts->xopts[i], "^$", 0);
885         }
886 }
887
888 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
889 {
890         struct commit_list *cur;
891         int res;
892
893         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
894         if (opts->allow_ff)
895                 assert(!(opts->signoff || opts->no_commit ||
896                                 opts->record_origin || opts->edit));
897         read_and_refresh_cache(opts);
898
899         for (cur = todo_list; cur; cur = cur->next) {
900                 save_todo(cur, opts);
901                 res = do_pick_commit(cur->item, opts);
902                 if (res)
903                         return res;
904         }
905
906         /*
907          * Sequence of picks finished successfully; cleanup by
908          * removing the .git/sequencer directory
909          */
910         remove_sequencer_state();
911         return 0;
912 }
913
914 static int continue_single_pick(void)
915 {
916         const char *argv[] = { "commit", NULL };
917
918         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
919             !file_exists(git_path("REVERT_HEAD")))
920                 return error(_("no cherry-pick or revert in progress"));
921         return run_command_v_opt(argv, RUN_GIT_CMD);
922 }
923
924 static int sequencer_continue(struct replay_opts *opts)
925 {
926         struct commit_list *todo_list = NULL;
927
928         if (!file_exists(git_path(SEQ_TODO_FILE)))
929                 return continue_single_pick();
930         read_populate_opts(&opts);
931         read_populate_todo(&todo_list, opts);
932
933         /* Verify that the conflict has been resolved */
934         if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
935             file_exists(git_path("REVERT_HEAD"))) {
936                 int ret = continue_single_pick();
937                 if (ret)
938                         return ret;
939         }
940         if (index_differs_from("HEAD", 0))
941                 return error_dirty_index(opts);
942         todo_list = todo_list->next;
943         return pick_commits(todo_list, opts);
944 }
945
946 static int single_pick(struct commit *cmit, struct replay_opts *opts)
947 {
948         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
949         return do_pick_commit(cmit, opts);
950 }
951
952 int sequencer_pick_revisions(struct replay_opts *opts)
953 {
954         struct commit_list *todo_list = NULL;
955         unsigned char sha1[20];
956
957         if (opts->subcommand == REPLAY_NONE)
958                 assert(opts->revs);
959
960         read_and_refresh_cache(opts);
961
962         /*
963          * Decide what to do depending on the arguments; a fresh
964          * cherry-pick should be handled differently from an existing
965          * one that is being continued
966          */
967         if (opts->subcommand == REPLAY_REMOVE_STATE) {
968                 remove_sequencer_state();
969                 return 0;
970         }
971         if (opts->subcommand == REPLAY_ROLLBACK)
972                 return sequencer_rollback(opts);
973         if (opts->subcommand == REPLAY_CONTINUE)
974                 return sequencer_continue(opts);
975
976         /*
977          * If we were called as "git cherry-pick <commit>", just
978          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
979          * REVERT_HEAD, and don't touch the sequencer state.
980          * This means it is possible to cherry-pick in the middle
981          * of a cherry-pick sequence.
982          */
983         if (opts->revs->cmdline.nr == 1 &&
984             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
985             opts->revs->no_walk &&
986             !opts->revs->cmdline.rev->flags) {
987                 struct commit *cmit;
988                 if (prepare_revision_walk(opts->revs))
989                         die(_("revision walk setup failed"));
990                 cmit = get_revision(opts->revs);
991                 if (!cmit || get_revision(opts->revs))
992                         die("BUG: expected exactly one commit from walk");
993                 return single_pick(cmit, opts);
994         }
995
996         /*
997          * Start a new cherry-pick/ revert sequence; but
998          * first, make sure that an existing one isn't in
999          * progress
1000          */
1001
1002         walk_revs_populate_todo(&todo_list, opts);
1003         if (create_seq_dir() < 0)
1004                 return -1;
1005         if (get_sha1("HEAD", sha1)) {
1006                 if (opts->action == REPLAY_REVERT)
1007                         return error(_("Can't revert as initial commit"));
1008                 return error(_("Can't cherry-pick into empty head"));
1009         }
1010         save_head(sha1_to_hex(sha1));
1011         save_opts(opts);
1012         return pick_commits(todo_list, opts);
1013 }