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