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