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