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