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