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