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