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