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