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