write_locked_index(): add flag to avoid writing unchanged index
[alt-git.git] / sequencer.c
blob6ee251849d7a45a989b28a9f87bd9c6ca95c22ba
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "sequencer.h"
8 #include "tag.h"
9 #include "run-command.h"
10 #include "exec_cmd.h"
11 #include "utf8.h"
12 #include "cache-tree.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "rerere.h"
16 #include "merge-recursive.h"
17 #include "refs.h"
18 #include "argv-array.h"
19 #include "quote.h"
20 #include "trailer.h"
21 #include "log-tree.h"
22 #include "wt-status.h"
23 #include "hashmap.h"
24 #include "notes-utils.h"
25 #include "sigchain.h"
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
32 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
34 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
36 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
37 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
38 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
39 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
41 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
43 * The file containing rebase commands, comments, and empty lines.
44 * This file is created by "git rebase -i" then edited by the user. As
45 * the lines are processed, they are removed from the front of this
46 * file and written to the tail of 'done'.
48 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
50 * The rebase command lines that have already been processed. A line
51 * is moved here when it is first handled, before any associated user
52 * actions.
54 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
56 * The file to keep track of how many commands were already processed (e.g.
57 * for the prompt).
59 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
61 * The file to keep track of how many commands are to be processed in total
62 * (e.g. for the prompt).
64 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
66 * The commit message that is planned to be used for any changes that
67 * need to be committed following a user interaction.
69 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
71 * The file into which is accumulated the suggested commit message for
72 * squash/fixup commands. When the first of a series of squash/fixups
73 * is seen, the file is created and the commit message from the
74 * previous commit and from the first squash/fixup commit are written
75 * to it. The commit message for each subsequent squash/fixup commit
76 * is appended to the file as it is processed.
78 * The first line of the file is of the form
79 * # This is a combination of $count commits.
80 * where $count is the number of commits whose messages have been
81 * written to the file so far (including the initial "pick" commit).
82 * Each time that a commit message is processed, this line is read and
83 * updated. It is deleted just before the combined commit is made.
85 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
87 * If the current series of squash/fixups has not yet included a squash
88 * command, then this file exists and holds the commit message of the
89 * original "pick" commit. (If the series ends without a "squash"
90 * command, then this can be used as the commit message of the combined
91 * commit without opening the editor.)
93 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
95 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
96 * GIT_AUTHOR_DATE that will be used for the commit that is currently
97 * being rebased.
99 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
101 * When an "edit" rebase command is being processed, the SHA1 of the
102 * commit to be edited is recorded in this file. When "git rebase
103 * --continue" is executed, if there are any staged changes then they
104 * will be amended to the HEAD commit, but only provided the HEAD
105 * commit is still the commit to be edited. When any other rebase
106 * command is processed, this file is deleted.
108 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
110 * When we stop at a given patch via the "edit" command, this file contains
111 * the abbreviated commit name of the corresponding patch.
113 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
115 * For the post-rewrite hook, we make a list of rewritten commits and
116 * their new sha1s. The rewritten-pending list keeps the sha1s of
117 * commits that have been processed, but not committed yet,
118 * e.g. because they are waiting for a 'squash' command.
120 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
121 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
122 "rebase-merge/rewritten-pending")
124 * The following files are written by git-rebase just after parsing the
125 * command-line (and are only consumed, not modified, by the sequencer).
127 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
128 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
129 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
130 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
131 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
132 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
133 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
134 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
135 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
137 static int git_sequencer_config(const char *k, const char *v, void *cb)
139 struct replay_opts *opts = cb;
140 int status;
142 if (!strcmp(k, "commit.cleanup")) {
143 const char *s;
145 status = git_config_string(&s, k, v);
146 if (status)
147 return status;
149 if (!strcmp(s, "verbatim"))
150 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
151 else if (!strcmp(s, "whitespace"))
152 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
153 else if (!strcmp(s, "strip"))
154 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
155 else if (!strcmp(s, "scissors"))
156 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
157 else
158 warning(_("invalid commit message cleanup mode '%s'"),
161 return status;
164 if (!strcmp(k, "commit.gpgsign")) {
165 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
166 return 0;
169 status = git_gpg_config(k, v, NULL);
170 if (status)
171 return status;
173 return git_diff_basic_config(k, v, NULL);
176 void sequencer_init_config(struct replay_opts *opts)
178 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
179 git_config(git_sequencer_config, opts);
182 static inline int is_rebase_i(const struct replay_opts *opts)
184 return opts->action == REPLAY_INTERACTIVE_REBASE;
187 static const char *get_dir(const struct replay_opts *opts)
189 if (is_rebase_i(opts))
190 return rebase_path();
191 return git_path_seq_dir();
194 static const char *get_todo_path(const struct replay_opts *opts)
196 if (is_rebase_i(opts))
197 return rebase_path_todo();
198 return git_path_todo_file();
202 * Returns 0 for non-conforming footer
203 * Returns 1 for conforming footer
204 * Returns 2 when sob exists within conforming footer
205 * Returns 3 when sob exists within conforming footer as last entry
207 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
208 int ignore_footer)
210 struct trailer_info info;
211 int i;
212 int found_sob = 0, found_sob_last = 0;
214 trailer_info_get(&info, sb->buf);
216 if (info.trailer_start == info.trailer_end)
217 return 0;
219 for (i = 0; i < info.trailer_nr; i++)
220 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
221 found_sob = 1;
222 if (i == info.trailer_nr - 1)
223 found_sob_last = 1;
226 trailer_info_release(&info);
228 if (found_sob_last)
229 return 3;
230 if (found_sob)
231 return 2;
232 return 1;
235 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
237 static struct strbuf buf = STRBUF_INIT;
239 strbuf_reset(&buf);
240 if (opts->gpg_sign)
241 sq_quotef(&buf, "-S%s", opts->gpg_sign);
242 return buf.buf;
245 int sequencer_remove_state(struct replay_opts *opts)
247 struct strbuf dir = STRBUF_INIT;
248 int i;
250 free(opts->gpg_sign);
251 free(opts->strategy);
252 for (i = 0; i < opts->xopts_nr; i++)
253 free(opts->xopts[i]);
254 free(opts->xopts);
256 strbuf_addstr(&dir, get_dir(opts));
257 remove_dir_recursively(&dir, 0);
258 strbuf_release(&dir);
260 return 0;
263 static const char *action_name(const struct replay_opts *opts)
265 switch (opts->action) {
266 case REPLAY_REVERT:
267 return N_("revert");
268 case REPLAY_PICK:
269 return N_("cherry-pick");
270 case REPLAY_INTERACTIVE_REBASE:
271 return N_("rebase -i");
273 die(_("Unknown action: %d"), opts->action);
276 struct commit_message {
277 char *parent_label;
278 char *label;
279 char *subject;
280 const char *message;
283 static const char *short_commit_name(struct commit *commit)
285 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
288 static int get_message(struct commit *commit, struct commit_message *out)
290 const char *abbrev, *subject;
291 int subject_len;
293 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
294 abbrev = short_commit_name(commit);
296 subject_len = find_commit_subject(out->message, &subject);
298 out->subject = xmemdupz(subject, subject_len);
299 out->label = xstrfmt("%s... %s", abbrev, out->subject);
300 out->parent_label = xstrfmt("parent of %s", out->label);
302 return 0;
305 static void free_message(struct commit *commit, struct commit_message *msg)
307 free(msg->parent_label);
308 free(msg->label);
309 free(msg->subject);
310 unuse_commit_buffer(commit, msg->message);
313 static void print_advice(int show_hint, struct replay_opts *opts)
315 char *msg = getenv("GIT_CHERRY_PICK_HELP");
317 if (msg) {
318 fprintf(stderr, "%s\n", msg);
320 * A conflict has occurred but the porcelain
321 * (typically rebase --interactive) wants to take care
322 * of the commit itself so remove CHERRY_PICK_HEAD
324 unlink(git_path_cherry_pick_head());
325 return;
328 if (show_hint) {
329 if (opts->no_commit)
330 advise(_("after resolving the conflicts, mark the corrected paths\n"
331 "with 'git add <paths>' or 'git rm <paths>'"));
332 else
333 advise(_("after resolving the conflicts, mark the corrected paths\n"
334 "with 'git add <paths>' or 'git rm <paths>'\n"
335 "and commit the result with 'git commit'"));
339 static int write_message(const void *buf, size_t len, const char *filename,
340 int append_eol)
342 struct lock_file msg_file = LOCK_INIT;
344 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
345 if (msg_fd < 0)
346 return error_errno(_("could not lock '%s'"), filename);
347 if (write_in_full(msg_fd, buf, len) < 0) {
348 rollback_lock_file(&msg_file);
349 return error_errno(_("could not write to '%s'"), filename);
351 if (append_eol && write(msg_fd, "\n", 1) < 0) {
352 rollback_lock_file(&msg_file);
353 return error_errno(_("could not write eol to '%s'"), filename);
355 if (commit_lock_file(&msg_file) < 0)
356 return error(_("failed to finalize '%s'"), filename);
358 return 0;
362 * Reads a file that was presumably written by a shell script, i.e. with an
363 * end-of-line marker that needs to be stripped.
365 * Note that only the last end-of-line marker is stripped, consistent with the
366 * behavior of "$(cat path)" in a shell script.
368 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
370 static int read_oneliner(struct strbuf *buf,
371 const char *path, int skip_if_empty)
373 int orig_len = buf->len;
375 if (!file_exists(path))
376 return 0;
378 if (strbuf_read_file(buf, path, 0) < 0) {
379 warning_errno(_("could not read '%s'"), path);
380 return 0;
383 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
384 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
385 --buf->len;
386 buf->buf[buf->len] = '\0';
389 if (skip_if_empty && buf->len == orig_len)
390 return 0;
392 return 1;
395 static struct tree *empty_tree(void)
397 return lookup_tree(the_hash_algo->empty_tree);
400 static int error_dirty_index(struct replay_opts *opts)
402 if (read_cache_unmerged())
403 return error_resolve_conflict(_(action_name(opts)));
405 error(_("your local changes would be overwritten by %s."),
406 _(action_name(opts)));
408 if (advice_commit_before_merge)
409 advise(_("commit your changes or stash them to proceed."));
410 return -1;
413 static void update_abort_safety_file(void)
415 struct object_id head;
417 /* Do nothing on a single-pick */
418 if (!file_exists(git_path_seq_dir()))
419 return;
421 if (!get_oid("HEAD", &head))
422 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
423 else
424 write_file(git_path_abort_safety_file(), "%s", "");
427 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
428 int unborn, struct replay_opts *opts)
430 struct ref_transaction *transaction;
431 struct strbuf sb = STRBUF_INIT;
432 struct strbuf err = STRBUF_INIT;
434 read_cache();
435 if (checkout_fast_forward(from, to, 1))
436 return -1; /* the callee should have complained already */
438 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
440 transaction = ref_transaction_begin(&err);
441 if (!transaction ||
442 ref_transaction_update(transaction, "HEAD",
443 to, unborn ? &null_oid : from,
444 0, sb.buf, &err) ||
445 ref_transaction_commit(transaction, &err)) {
446 ref_transaction_free(transaction);
447 error("%s", err.buf);
448 strbuf_release(&sb);
449 strbuf_release(&err);
450 return -1;
453 strbuf_release(&sb);
454 strbuf_release(&err);
455 ref_transaction_free(transaction);
456 update_abort_safety_file();
457 return 0;
460 void append_conflicts_hint(struct strbuf *msgbuf)
462 int i;
464 strbuf_addch(msgbuf, '\n');
465 strbuf_commented_addf(msgbuf, "Conflicts:\n");
466 for (i = 0; i < active_nr;) {
467 const struct cache_entry *ce = active_cache[i++];
468 if (ce_stage(ce)) {
469 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
470 while (i < active_nr && !strcmp(ce->name,
471 active_cache[i]->name))
472 i++;
477 static int do_recursive_merge(struct commit *base, struct commit *next,
478 const char *base_label, const char *next_label,
479 struct object_id *head, struct strbuf *msgbuf,
480 struct replay_opts *opts)
482 struct merge_options o;
483 struct tree *result, *next_tree, *base_tree, *head_tree;
484 int clean;
485 char **xopt;
486 struct lock_file index_lock = LOCK_INIT;
488 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
489 return -1;
491 read_cache();
493 init_merge_options(&o);
494 o.ancestor = base ? base_label : "(empty tree)";
495 o.branch1 = "HEAD";
496 o.branch2 = next ? next_label : "(empty tree)";
497 if (is_rebase_i(opts))
498 o.buffer_output = 2;
499 o.show_rename_progress = 1;
501 head_tree = parse_tree_indirect(head);
502 next_tree = next ? next->tree : empty_tree();
503 base_tree = base ? base->tree : empty_tree();
505 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
506 parse_merge_opt(&o, *xopt);
508 clean = merge_trees(&o,
509 head_tree,
510 next_tree, base_tree, &result);
511 if (is_rebase_i(opts) && clean <= 0)
512 fputs(o.obuf.buf, stdout);
513 strbuf_release(&o.obuf);
514 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
515 if (clean < 0) {
516 rollback_lock_file(&index_lock);
517 return clean;
520 if (write_locked_index(&the_index, &index_lock,
521 COMMIT_LOCK | SKIP_IF_UNCHANGED))
523 * TRANSLATORS: %s will be "revert", "cherry-pick" or
524 * "rebase -i".
526 return error(_("%s: Unable to write new index file"),
527 _(action_name(opts)));
529 if (!clean)
530 append_conflicts_hint(msgbuf);
532 return !clean;
535 static int is_index_unchanged(void)
537 struct object_id head_oid;
538 struct commit *head_commit;
540 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
541 return error(_("could not resolve HEAD commit"));
543 head_commit = lookup_commit(&head_oid);
546 * If head_commit is NULL, check_commit, called from
547 * lookup_commit, would have indicated that head_commit is not
548 * a commit object already. parse_commit() will return failure
549 * without further complaints in such a case. Otherwise, if
550 * the commit is invalid, parse_commit() will complain. So
551 * there is nothing for us to say here. Just return failure.
553 if (parse_commit(head_commit))
554 return -1;
556 if (!active_cache_tree)
557 active_cache_tree = cache_tree();
559 if (!cache_tree_fully_valid(active_cache_tree))
560 if (cache_tree_update(&the_index, 0))
561 return error(_("unable to update cache tree"));
563 return !oidcmp(&active_cache_tree->oid,
564 &head_commit->tree->object.oid);
567 static int write_author_script(const char *message)
569 struct strbuf buf = STRBUF_INIT;
570 const char *eol;
571 int res;
573 for (;;)
574 if (!*message || starts_with(message, "\n")) {
575 missing_author:
576 /* Missing 'author' line? */
577 unlink(rebase_path_author_script());
578 return 0;
579 } else if (skip_prefix(message, "author ", &message))
580 break;
581 else if ((eol = strchr(message, '\n')))
582 message = eol + 1;
583 else
584 goto missing_author;
586 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
587 while (*message && *message != '\n' && *message != '\r')
588 if (skip_prefix(message, " <", &message))
589 break;
590 else if (*message != '\'')
591 strbuf_addch(&buf, *(message++));
592 else
593 strbuf_addf(&buf, "'\\\\%c'", *(message++));
594 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
595 while (*message && *message != '\n' && *message != '\r')
596 if (skip_prefix(message, "> ", &message))
597 break;
598 else if (*message != '\'')
599 strbuf_addch(&buf, *(message++));
600 else
601 strbuf_addf(&buf, "'\\\\%c'", *(message++));
602 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
603 while (*message && *message != '\n' && *message != '\r')
604 if (*message != '\'')
605 strbuf_addch(&buf, *(message++));
606 else
607 strbuf_addf(&buf, "'\\\\%c'", *(message++));
608 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
609 strbuf_release(&buf);
610 return res;
614 * Read a list of environment variable assignments (such as the author-script
615 * file) into an environment block. Returns -1 on error, 0 otherwise.
617 static int read_env_script(struct argv_array *env)
619 struct strbuf script = STRBUF_INIT;
620 int i, count = 0;
621 char *p, *p2;
623 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
624 return -1;
626 for (p = script.buf; *p; p++)
627 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
628 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
629 else if (*p == '\'')
630 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
631 else if (*p == '\n') {
632 *p = '\0';
633 count++;
636 for (i = 0, p = script.buf; i < count; i++) {
637 argv_array_push(env, p);
638 p += strlen(p) + 1;
641 return 0;
644 static char *get_author(const char *message)
646 size_t len;
647 const char *a;
649 a = find_commit_header(message, "author", &len);
650 if (a)
651 return xmemdupz(a, len);
653 return NULL;
656 static const char staged_changes_advice[] =
657 N_("you have staged changes in your working tree\n"
658 "If these changes are meant to be squashed into the previous commit, run:\n"
659 "\n"
660 " git commit --amend %s\n"
661 "\n"
662 "If they are meant to go into a new commit, run:\n"
663 "\n"
664 " git commit %s\n"
665 "\n"
666 "In both cases, once you're done, continue with:\n"
667 "\n"
668 " git rebase --continue\n");
670 #define ALLOW_EMPTY (1<<0)
671 #define EDIT_MSG (1<<1)
672 #define AMEND_MSG (1<<2)
673 #define CLEANUP_MSG (1<<3)
674 #define VERIFY_MSG (1<<4)
677 * If we are cherry-pick, and if the merge did not result in
678 * hand-editing, we will hit this commit and inherit the original
679 * author date and name.
681 * If we are revert, or if our cherry-pick results in a hand merge,
682 * we had better say that the current user is responsible for that.
684 * An exception is when run_git_commit() is called during an
685 * interactive rebase: in that case, we will want to retain the
686 * author metadata.
688 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
689 unsigned int flags)
691 struct child_process cmd = CHILD_PROCESS_INIT;
692 const char *value;
694 cmd.git_cmd = 1;
696 if (is_rebase_i(opts)) {
697 if (!(flags & EDIT_MSG)) {
698 cmd.stdout_to_stderr = 1;
699 cmd.err = -1;
702 if (read_env_script(&cmd.env_array)) {
703 const char *gpg_opt = gpg_sign_opt_quoted(opts);
705 return error(_(staged_changes_advice),
706 gpg_opt, gpg_opt);
710 argv_array_push(&cmd.args, "commit");
712 if (!(flags & VERIFY_MSG))
713 argv_array_push(&cmd.args, "-n");
714 if ((flags & AMEND_MSG))
715 argv_array_push(&cmd.args, "--amend");
716 if (opts->gpg_sign)
717 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
718 if (defmsg)
719 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
720 if ((flags & CLEANUP_MSG))
721 argv_array_push(&cmd.args, "--cleanup=strip");
722 if ((flags & EDIT_MSG))
723 argv_array_push(&cmd.args, "-e");
724 else if (!(flags & CLEANUP_MSG) &&
725 !opts->signoff && !opts->record_origin &&
726 git_config_get_value("commit.cleanup", &value))
727 argv_array_push(&cmd.args, "--cleanup=verbatim");
729 if ((flags & ALLOW_EMPTY))
730 argv_array_push(&cmd.args, "--allow-empty");
732 if (opts->allow_empty_message)
733 argv_array_push(&cmd.args, "--allow-empty-message");
735 if (cmd.err == -1) {
736 /* hide stderr on success */
737 struct strbuf buf = STRBUF_INIT;
738 int rc = pipe_command(&cmd,
739 NULL, 0,
740 /* stdout is already redirected */
741 NULL, 0,
742 &buf, 0);
743 if (rc)
744 fputs(buf.buf, stderr);
745 strbuf_release(&buf);
746 return rc;
749 return run_command(&cmd);
752 static int rest_is_empty(const struct strbuf *sb, int start)
754 int i, eol;
755 const char *nl;
757 /* Check if the rest is just whitespace and Signed-off-by's. */
758 for (i = start; i < sb->len; i++) {
759 nl = memchr(sb->buf + i, '\n', sb->len - i);
760 if (nl)
761 eol = nl - sb->buf;
762 else
763 eol = sb->len;
765 if (strlen(sign_off_header) <= eol - i &&
766 starts_with(sb->buf + i, sign_off_header)) {
767 i = eol;
768 continue;
770 while (i < eol)
771 if (!isspace(sb->buf[i++]))
772 return 0;
775 return 1;
779 * Find out if the message in the strbuf contains only whitespace and
780 * Signed-off-by lines.
782 int message_is_empty(const struct strbuf *sb,
783 enum commit_msg_cleanup_mode cleanup_mode)
785 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
786 return 0;
787 return rest_is_empty(sb, 0);
791 * See if the user edited the message in the editor or left what
792 * was in the template intact
794 int template_untouched(const struct strbuf *sb, const char *template_file,
795 enum commit_msg_cleanup_mode cleanup_mode)
797 struct strbuf tmpl = STRBUF_INIT;
798 const char *start;
800 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
801 return 0;
803 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
804 return 0;
806 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
807 if (!skip_prefix(sb->buf, tmpl.buf, &start))
808 start = sb->buf;
809 strbuf_release(&tmpl);
810 return rest_is_empty(sb, start - sb->buf);
813 int update_head_with_reflog(const struct commit *old_head,
814 const struct object_id *new_head,
815 const char *action, const struct strbuf *msg,
816 struct strbuf *err)
818 struct ref_transaction *transaction;
819 struct strbuf sb = STRBUF_INIT;
820 const char *nl;
821 int ret = 0;
823 if (action) {
824 strbuf_addstr(&sb, action);
825 strbuf_addstr(&sb, ": ");
828 nl = strchr(msg->buf, '\n');
829 if (nl) {
830 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
831 } else {
832 strbuf_addbuf(&sb, msg);
833 strbuf_addch(&sb, '\n');
836 transaction = ref_transaction_begin(err);
837 if (!transaction ||
838 ref_transaction_update(transaction, "HEAD", new_head,
839 old_head ? &old_head->object.oid : &null_oid,
840 0, sb.buf, err) ||
841 ref_transaction_commit(transaction, err)) {
842 ret = -1;
844 ref_transaction_free(transaction);
845 strbuf_release(&sb);
847 return ret;
850 static int run_rewrite_hook(const struct object_id *oldoid,
851 const struct object_id *newoid)
853 struct child_process proc = CHILD_PROCESS_INIT;
854 const char *argv[3];
855 int code;
856 struct strbuf sb = STRBUF_INIT;
858 argv[0] = find_hook("post-rewrite");
859 if (!argv[0])
860 return 0;
862 argv[1] = "amend";
863 argv[2] = NULL;
865 proc.argv = argv;
866 proc.in = -1;
867 proc.stdout_to_stderr = 1;
869 code = start_command(&proc);
870 if (code)
871 return code;
872 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
873 sigchain_push(SIGPIPE, SIG_IGN);
874 write_in_full(proc.in, sb.buf, sb.len);
875 close(proc.in);
876 strbuf_release(&sb);
877 sigchain_pop(SIGPIPE);
878 return finish_command(&proc);
881 void commit_post_rewrite(const struct commit *old_head,
882 const struct object_id *new_head)
884 struct notes_rewrite_cfg *cfg;
886 cfg = init_copy_notes_for_rewrite("amend");
887 if (cfg) {
888 /* we are amending, so old_head is not NULL */
889 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
890 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
892 run_rewrite_hook(&old_head->object.oid, new_head);
895 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
897 struct argv_array hook_env = ARGV_ARRAY_INIT;
898 int ret;
899 const char *name;
901 name = git_path_commit_editmsg();
902 if (write_message(msg->buf, msg->len, name, 0))
903 return -1;
905 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
906 argv_array_push(&hook_env, "GIT_EDITOR=:");
907 if (commit)
908 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
909 "commit", commit, NULL);
910 else
911 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
912 "message", NULL);
913 if (ret)
914 ret = error(_("'prepare-commit-msg' hook failed"));
915 argv_array_clear(&hook_env);
917 return ret;
920 static const char implicit_ident_advice_noconfig[] =
921 N_("Your name and email address were configured automatically based\n"
922 "on your username and hostname. Please check that they are accurate.\n"
923 "You can suppress this message by setting them explicitly. Run the\n"
924 "following command and follow the instructions in your editor to edit\n"
925 "your configuration file:\n"
926 "\n"
927 " git config --global --edit\n"
928 "\n"
929 "After doing this, you may fix the identity used for this commit with:\n"
930 "\n"
931 " git commit --amend --reset-author\n");
933 static const char implicit_ident_advice_config[] =
934 N_("Your name and email address were configured automatically based\n"
935 "on your username and hostname. Please check that they are accurate.\n"
936 "You can suppress this message by setting them explicitly:\n"
937 "\n"
938 " git config --global user.name \"Your Name\"\n"
939 " git config --global user.email you@example.com\n"
940 "\n"
941 "After doing this, you may fix the identity used for this commit with:\n"
942 "\n"
943 " git commit --amend --reset-author\n");
945 static const char *implicit_ident_advice(void)
947 char *user_config = expand_user_path("~/.gitconfig", 0);
948 char *xdg_config = xdg_config_home("config");
949 int config_exists = file_exists(user_config) || file_exists(xdg_config);
951 free(user_config);
952 free(xdg_config);
954 if (config_exists)
955 return _(implicit_ident_advice_config);
956 else
957 return _(implicit_ident_advice_noconfig);
961 void print_commit_summary(const char *prefix, const struct object_id *oid,
962 unsigned int flags)
964 struct rev_info rev;
965 struct commit *commit;
966 struct strbuf format = STRBUF_INIT;
967 const char *head;
968 struct pretty_print_context pctx = {0};
969 struct strbuf author_ident = STRBUF_INIT;
970 struct strbuf committer_ident = STRBUF_INIT;
972 commit = lookup_commit(oid);
973 if (!commit)
974 die(_("couldn't look up newly created commit"));
975 if (parse_commit(commit))
976 die(_("could not parse newly created commit"));
978 strbuf_addstr(&format, "format:%h] %s");
980 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
981 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
982 if (strbuf_cmp(&author_ident, &committer_ident)) {
983 strbuf_addstr(&format, "\n Author: ");
984 strbuf_addbuf_percentquote(&format, &author_ident);
986 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
987 struct strbuf date = STRBUF_INIT;
989 format_commit_message(commit, "%ad", &date, &pctx);
990 strbuf_addstr(&format, "\n Date: ");
991 strbuf_addbuf_percentquote(&format, &date);
992 strbuf_release(&date);
994 if (!committer_ident_sufficiently_given()) {
995 strbuf_addstr(&format, "\n Committer: ");
996 strbuf_addbuf_percentquote(&format, &committer_ident);
997 if (advice_implicit_identity) {
998 strbuf_addch(&format, '\n');
999 strbuf_addstr(&format, implicit_ident_advice());
1002 strbuf_release(&author_ident);
1003 strbuf_release(&committer_ident);
1005 init_revisions(&rev, prefix);
1006 setup_revisions(0, NULL, &rev, NULL);
1008 rev.diff = 1;
1009 rev.diffopt.output_format =
1010 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1012 rev.verbose_header = 1;
1013 rev.show_root_diff = 1;
1014 get_commit_format(format.buf, &rev);
1015 rev.always_show_header = 0;
1016 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1017 rev.diffopt.break_opt = 0;
1018 diff_setup_done(&rev.diffopt);
1020 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1021 if (!head)
1022 die_errno(_("unable to resolve HEAD after creating commit"));
1023 if (!strcmp(head, "HEAD"))
1024 head = _("detached HEAD");
1025 else
1026 skip_prefix(head, "refs/heads/", &head);
1027 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1028 _(" (root-commit)") : "");
1030 if (!log_tree_commit(&rev, commit)) {
1031 rev.always_show_header = 1;
1032 rev.use_terminator = 1;
1033 log_tree_commit(&rev, commit);
1036 strbuf_release(&format);
1039 static int parse_head(struct commit **head)
1041 struct commit *current_head;
1042 struct object_id oid;
1044 if (get_oid("HEAD", &oid)) {
1045 current_head = NULL;
1046 } else {
1047 current_head = lookup_commit_reference(&oid);
1048 if (!current_head)
1049 return error(_("could not parse HEAD"));
1050 if (oidcmp(&oid, &current_head->object.oid)) {
1051 warning(_("HEAD %s is not a commit!"),
1052 oid_to_hex(&oid));
1054 if (parse_commit(current_head))
1055 return error(_("could not parse HEAD commit"));
1057 *head = current_head;
1059 return 0;
1063 * Try to commit without forking 'git commit'. In some cases we need
1064 * to run 'git commit' to display an error message
1066 * Returns:
1067 * -1 - error unable to commit
1068 * 0 - success
1069 * 1 - run 'git commit'
1071 static int try_to_commit(struct strbuf *msg, const char *author,
1072 struct replay_opts *opts, unsigned int flags,
1073 struct object_id *oid)
1075 struct object_id tree;
1076 struct commit *current_head;
1077 struct commit_list *parents = NULL;
1078 struct commit_extra_header *extra = NULL;
1079 struct strbuf err = STRBUF_INIT;
1080 struct strbuf commit_msg = STRBUF_INIT;
1081 char *amend_author = NULL;
1082 const char *hook_commit = NULL;
1083 enum commit_msg_cleanup_mode cleanup;
1084 int res = 0;
1086 if (parse_head(&current_head))
1087 return -1;
1089 if (flags & AMEND_MSG) {
1090 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1091 const char *out_enc = get_commit_output_encoding();
1092 const char *message = logmsg_reencode(current_head, NULL,
1093 out_enc);
1095 if (!msg) {
1096 const char *orig_message = NULL;
1098 find_commit_subject(message, &orig_message);
1099 msg = &commit_msg;
1100 strbuf_addstr(msg, orig_message);
1101 hook_commit = "HEAD";
1103 author = amend_author = get_author(message);
1104 unuse_commit_buffer(current_head, message);
1105 if (!author) {
1106 res = error(_("unable to parse commit author"));
1107 goto out;
1109 parents = copy_commit_list(current_head->parents);
1110 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1111 } else if (current_head) {
1112 commit_list_insert(current_head, &parents);
1115 if (write_cache_as_tree(tree.hash, 0, NULL)) {
1116 res = error(_("git write-tree failed to write a tree"));
1117 goto out;
1120 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1121 &current_head->tree->object.oid :
1122 &empty_tree_oid, &tree)) {
1123 res = 1; /* run 'git commit' to display error message */
1124 goto out;
1127 if (find_hook("prepare-commit-msg")) {
1128 res = run_prepare_commit_msg_hook(msg, hook_commit);
1129 if (res)
1130 goto out;
1131 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1132 2048) < 0) {
1133 res = error_errno(_("unable to read commit message "
1134 "from '%s'"),
1135 git_path_commit_editmsg());
1136 goto out;
1138 msg = &commit_msg;
1141 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1142 opts->default_msg_cleanup;
1144 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1145 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1146 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1147 res = 1; /* run 'git commit' to display error message */
1148 goto out;
1151 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1152 oid, author, opts->gpg_sign, extra)) {
1153 res = error(_("failed to write commit object"));
1154 goto out;
1157 if (update_head_with_reflog(current_head, oid,
1158 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1159 res = error("%s", err.buf);
1160 goto out;
1163 if (flags & AMEND_MSG)
1164 commit_post_rewrite(current_head, oid);
1166 out:
1167 free_commit_extra_headers(extra);
1168 strbuf_release(&err);
1169 strbuf_release(&commit_msg);
1170 free(amend_author);
1172 return res;
1175 static int do_commit(const char *msg_file, const char *author,
1176 struct replay_opts *opts, unsigned int flags)
1178 int res = 1;
1180 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1181 struct object_id oid;
1182 struct strbuf sb = STRBUF_INIT;
1184 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1185 return error_errno(_("unable to read commit message "
1186 "from '%s'"),
1187 msg_file);
1189 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1190 &oid);
1191 strbuf_release(&sb);
1192 if (!res) {
1193 unlink(git_path_cherry_pick_head());
1194 unlink(git_path_merge_msg());
1195 if (!is_rebase_i(opts))
1196 print_commit_summary(NULL, &oid,
1197 SUMMARY_SHOW_AUTHOR_DATE);
1198 return res;
1201 if (res == 1)
1202 return run_git_commit(msg_file, opts, flags);
1204 return res;
1207 static int is_original_commit_empty(struct commit *commit)
1209 const struct object_id *ptree_oid;
1211 if (parse_commit(commit))
1212 return error(_("could not parse commit %s"),
1213 oid_to_hex(&commit->object.oid));
1214 if (commit->parents) {
1215 struct commit *parent = commit->parents->item;
1216 if (parse_commit(parent))
1217 return error(_("could not parse parent commit %s"),
1218 oid_to_hex(&parent->object.oid));
1219 ptree_oid = &parent->tree->object.oid;
1220 } else {
1221 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1224 return !oidcmp(ptree_oid, &commit->tree->object.oid);
1228 * Do we run "git commit" with "--allow-empty"?
1230 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1232 int index_unchanged, empty_commit;
1235 * Three cases:
1237 * (1) we do not allow empty at all and error out.
1239 * (2) we allow ones that were initially empty, but
1240 * forbid the ones that become empty;
1242 * (3) we allow both.
1244 if (!opts->allow_empty)
1245 return 0; /* let "git commit" barf as necessary */
1247 index_unchanged = is_index_unchanged();
1248 if (index_unchanged < 0)
1249 return index_unchanged;
1250 if (!index_unchanged)
1251 return 0; /* we do not have to say --allow-empty */
1253 if (opts->keep_redundant_commits)
1254 return 1;
1256 empty_commit = is_original_commit_empty(commit);
1257 if (empty_commit < 0)
1258 return empty_commit;
1259 if (!empty_commit)
1260 return 0;
1261 else
1262 return 1;
1266 * Note that ordering matters in this enum. Not only must it match the mapping
1267 * below, it is also divided into several sections that matter. When adding
1268 * new commands, make sure you add it in the right section.
1270 enum todo_command {
1271 /* commands that handle commits */
1272 TODO_PICK = 0,
1273 TODO_REVERT,
1274 TODO_EDIT,
1275 TODO_REWORD,
1276 TODO_FIXUP,
1277 TODO_SQUASH,
1278 /* commands that do something else than handling a single commit */
1279 TODO_EXEC,
1280 /* commands that do nothing but are counted for reporting progress */
1281 TODO_NOOP,
1282 TODO_DROP,
1283 /* comments (not counted for reporting progress) */
1284 TODO_COMMENT
1287 static struct {
1288 char c;
1289 const char *str;
1290 } todo_command_info[] = {
1291 { 'p', "pick" },
1292 { 0, "revert" },
1293 { 'e', "edit" },
1294 { 'r', "reword" },
1295 { 'f', "fixup" },
1296 { 's', "squash" },
1297 { 'x', "exec" },
1298 { 0, "noop" },
1299 { 'd', "drop" },
1300 { 0, NULL }
1303 static const char *command_to_string(const enum todo_command command)
1305 if (command < TODO_COMMENT)
1306 return todo_command_info[command].str;
1307 die("Unknown command: %d", command);
1310 static char command_to_char(const enum todo_command command)
1312 if (command < TODO_COMMENT && todo_command_info[command].c)
1313 return todo_command_info[command].c;
1314 return comment_line_char;
1317 static int is_noop(const enum todo_command command)
1319 return TODO_NOOP <= command;
1322 static int is_fixup(enum todo_command command)
1324 return command == TODO_FIXUP || command == TODO_SQUASH;
1327 static int update_squash_messages(enum todo_command command,
1328 struct commit *commit, struct replay_opts *opts)
1330 struct strbuf buf = STRBUF_INIT;
1331 int count, res;
1332 const char *message, *body;
1334 if (file_exists(rebase_path_squash_msg())) {
1335 struct strbuf header = STRBUF_INIT;
1336 char *eol, *p;
1338 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1339 return error(_("could not read '%s'"),
1340 rebase_path_squash_msg());
1342 p = buf.buf + 1;
1343 eol = strchrnul(buf.buf, '\n');
1344 if (buf.buf[0] != comment_line_char ||
1345 (p += strcspn(p, "0123456789\n")) == eol)
1346 return error(_("unexpected 1st line of squash message:"
1347 "\n\n\t%.*s"),
1348 (int)(eol - buf.buf), buf.buf);
1349 count = strtol(p, NULL, 10);
1351 if (count < 1)
1352 return error(_("invalid 1st line of squash message:\n"
1353 "\n\t%.*s"),
1354 (int)(eol - buf.buf), buf.buf);
1356 strbuf_addf(&header, "%c ", comment_line_char);
1357 strbuf_addf(&header,
1358 _("This is a combination of %d commits."), ++count);
1359 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1360 strbuf_release(&header);
1361 } else {
1362 struct object_id head;
1363 struct commit *head_commit;
1364 const char *head_message, *body;
1366 if (get_oid("HEAD", &head))
1367 return error(_("need a HEAD to fixup"));
1368 if (!(head_commit = lookup_commit_reference(&head)))
1369 return error(_("could not read HEAD"));
1370 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1371 return error(_("could not read HEAD's commit message"));
1373 find_commit_subject(head_message, &body);
1374 if (write_message(body, strlen(body),
1375 rebase_path_fixup_msg(), 0)) {
1376 unuse_commit_buffer(head_commit, head_message);
1377 return error(_("cannot write '%s'"),
1378 rebase_path_fixup_msg());
1381 count = 2;
1382 strbuf_addf(&buf, "%c ", comment_line_char);
1383 strbuf_addf(&buf, _("This is a combination of %d commits."),
1384 count);
1385 strbuf_addf(&buf, "\n%c ", comment_line_char);
1386 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1387 strbuf_addstr(&buf, "\n\n");
1388 strbuf_addstr(&buf, body);
1390 unuse_commit_buffer(head_commit, head_message);
1393 if (!(message = get_commit_buffer(commit, NULL)))
1394 return error(_("could not read commit message of %s"),
1395 oid_to_hex(&commit->object.oid));
1396 find_commit_subject(message, &body);
1398 if (command == TODO_SQUASH) {
1399 unlink(rebase_path_fixup_msg());
1400 strbuf_addf(&buf, "\n%c ", comment_line_char);
1401 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1402 strbuf_addstr(&buf, "\n\n");
1403 strbuf_addstr(&buf, body);
1404 } else if (command == TODO_FIXUP) {
1405 strbuf_addf(&buf, "\n%c ", comment_line_char);
1406 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1407 count);
1408 strbuf_addstr(&buf, "\n\n");
1409 strbuf_add_commented_lines(&buf, body, strlen(body));
1410 } else
1411 return error(_("unknown command: %d"), command);
1412 unuse_commit_buffer(commit, message);
1414 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1415 strbuf_release(&buf);
1416 return res;
1419 static void flush_rewritten_pending(void) {
1420 struct strbuf buf = STRBUF_INIT;
1421 struct object_id newoid;
1422 FILE *out;
1424 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1425 !get_oid("HEAD", &newoid) &&
1426 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1427 char *bol = buf.buf, *eol;
1429 while (*bol) {
1430 eol = strchrnul(bol, '\n');
1431 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1432 bol, oid_to_hex(&newoid));
1433 if (!*eol)
1434 break;
1435 bol = eol + 1;
1437 fclose(out);
1438 unlink(rebase_path_rewritten_pending());
1440 strbuf_release(&buf);
1443 static void record_in_rewritten(struct object_id *oid,
1444 enum todo_command next_command) {
1445 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1447 if (!out)
1448 return;
1450 fprintf(out, "%s\n", oid_to_hex(oid));
1451 fclose(out);
1453 if (!is_fixup(next_command))
1454 flush_rewritten_pending();
1457 static int do_pick_commit(enum todo_command command, struct commit *commit,
1458 struct replay_opts *opts, int final_fixup)
1460 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1461 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1462 struct object_id head;
1463 struct commit *base, *next, *parent;
1464 const char *base_label, *next_label;
1465 char *author = NULL;
1466 struct commit_message msg = { NULL, NULL, NULL, NULL };
1467 struct strbuf msgbuf = STRBUF_INIT;
1468 int res, unborn = 0, allow;
1470 if (opts->no_commit) {
1472 * We do not intend to commit immediately. We just want to
1473 * merge the differences in, so let's compute the tree
1474 * that represents the "current" state for merge-recursive
1475 * to work on.
1477 if (write_cache_as_tree(head.hash, 0, NULL))
1478 return error(_("your index file is unmerged."));
1479 } else {
1480 unborn = get_oid("HEAD", &head);
1481 if (unborn)
1482 oidcpy(&head, the_hash_algo->empty_tree);
1483 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1484 NULL, 0))
1485 return error_dirty_index(opts);
1487 discard_cache();
1489 if (!commit->parents)
1490 parent = NULL;
1491 else if (commit->parents->next) {
1492 /* Reverting or cherry-picking a merge commit */
1493 int cnt;
1494 struct commit_list *p;
1496 if (!opts->mainline)
1497 return error(_("commit %s is a merge but no -m option was given."),
1498 oid_to_hex(&commit->object.oid));
1500 for (cnt = 1, p = commit->parents;
1501 cnt != opts->mainline && p;
1502 cnt++)
1503 p = p->next;
1504 if (cnt != opts->mainline || !p)
1505 return error(_("commit %s does not have parent %d"),
1506 oid_to_hex(&commit->object.oid), opts->mainline);
1507 parent = p->item;
1508 } else if (0 < opts->mainline)
1509 return error(_("mainline was specified but commit %s is not a merge."),
1510 oid_to_hex(&commit->object.oid));
1511 else
1512 parent = commit->parents->item;
1514 if (get_message(commit, &msg) != 0)
1515 return error(_("cannot get commit message for %s"),
1516 oid_to_hex(&commit->object.oid));
1518 if (opts->allow_ff && !is_fixup(command) &&
1519 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1520 (!parent && unborn))) {
1521 if (is_rebase_i(opts))
1522 write_author_script(msg.message);
1523 res = fast_forward_to(&commit->object.oid, &head, unborn,
1524 opts);
1525 if (res || command != TODO_REWORD)
1526 goto leave;
1527 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1528 msg_file = NULL;
1529 goto fast_forward_edit;
1531 if (parent && parse_commit(parent) < 0)
1532 /* TRANSLATORS: The first %s will be a "todo" command like
1533 "revert" or "pick", the second %s a SHA1. */
1534 return error(_("%s: cannot parse parent commit %s"),
1535 command_to_string(command),
1536 oid_to_hex(&parent->object.oid));
1539 * "commit" is an existing commit. We would want to apply
1540 * the difference it introduces since its first parent "prev"
1541 * on top of the current HEAD if we are cherry-pick. Or the
1542 * reverse of it if we are revert.
1545 if (command == TODO_REVERT) {
1546 base = commit;
1547 base_label = msg.label;
1548 next = parent;
1549 next_label = msg.parent_label;
1550 strbuf_addstr(&msgbuf, "Revert \"");
1551 strbuf_addstr(&msgbuf, msg.subject);
1552 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1553 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1555 if (commit->parents && commit->parents->next) {
1556 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1557 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1559 strbuf_addstr(&msgbuf, ".\n");
1560 } else {
1561 const char *p;
1563 base = parent;
1564 base_label = msg.parent_label;
1565 next = commit;
1566 next_label = msg.label;
1568 /* Append the commit log message to msgbuf. */
1569 if (find_commit_subject(msg.message, &p))
1570 strbuf_addstr(&msgbuf, p);
1572 if (opts->record_origin) {
1573 strbuf_complete_line(&msgbuf);
1574 if (!has_conforming_footer(&msgbuf, NULL, 0))
1575 strbuf_addch(&msgbuf, '\n');
1576 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1577 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1578 strbuf_addstr(&msgbuf, ")\n");
1580 if (!is_fixup(command))
1581 author = get_author(msg.message);
1584 if (command == TODO_REWORD)
1585 flags |= EDIT_MSG | VERIFY_MSG;
1586 else if (is_fixup(command)) {
1587 if (update_squash_messages(command, commit, opts))
1588 return -1;
1589 flags |= AMEND_MSG;
1590 if (!final_fixup)
1591 msg_file = rebase_path_squash_msg();
1592 else if (file_exists(rebase_path_fixup_msg())) {
1593 flags |= CLEANUP_MSG;
1594 msg_file = rebase_path_fixup_msg();
1595 } else {
1596 const char *dest = git_path_squash_msg();
1597 unlink(dest);
1598 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1599 return error(_("could not rename '%s' to '%s'"),
1600 rebase_path_squash_msg(), dest);
1601 unlink(git_path_merge_msg());
1602 msg_file = dest;
1603 flags |= EDIT_MSG;
1607 if (opts->signoff)
1608 append_signoff(&msgbuf, 0, 0);
1610 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1611 res = -1;
1612 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1613 res = do_recursive_merge(base, next, base_label, next_label,
1614 &head, &msgbuf, opts);
1615 if (res < 0)
1616 return res;
1617 res |= write_message(msgbuf.buf, msgbuf.len,
1618 git_path_merge_msg(), 0);
1619 } else {
1620 struct commit_list *common = NULL;
1621 struct commit_list *remotes = NULL;
1623 res = write_message(msgbuf.buf, msgbuf.len,
1624 git_path_merge_msg(), 0);
1626 commit_list_insert(base, &common);
1627 commit_list_insert(next, &remotes);
1628 res |= try_merge_command(opts->strategy,
1629 opts->xopts_nr, (const char **)opts->xopts,
1630 common, oid_to_hex(&head), remotes);
1631 free_commit_list(common);
1632 free_commit_list(remotes);
1634 strbuf_release(&msgbuf);
1637 * If the merge was clean or if it failed due to conflict, we write
1638 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1639 * However, if the merge did not even start, then we don't want to
1640 * write it at all.
1642 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1643 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1644 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1645 res = -1;
1646 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1647 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1648 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1649 res = -1;
1651 if (res) {
1652 error(command == TODO_REVERT
1653 ? _("could not revert %s... %s")
1654 : _("could not apply %s... %s"),
1655 short_commit_name(commit), msg.subject);
1656 print_advice(res == 1, opts);
1657 rerere(opts->allow_rerere_auto);
1658 goto leave;
1661 allow = allow_empty(opts, commit);
1662 if (allow < 0) {
1663 res = allow;
1664 goto leave;
1665 } else if (allow)
1666 flags |= ALLOW_EMPTY;
1667 if (!opts->no_commit) {
1668 fast_forward_edit:
1669 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1670 res = do_commit(msg_file, author, opts, flags);
1671 else
1672 res = error(_("unable to parse commit author"));
1675 if (!res && final_fixup) {
1676 unlink(rebase_path_fixup_msg());
1677 unlink(rebase_path_squash_msg());
1680 leave:
1681 free_message(commit, &msg);
1682 free(author);
1683 update_abort_safety_file();
1685 return res;
1688 static int prepare_revs(struct replay_opts *opts)
1691 * picking (but not reverting) ranges (but not individual revisions)
1692 * should be done in reverse
1694 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1695 opts->revs->reverse ^= 1;
1697 if (prepare_revision_walk(opts->revs))
1698 return error(_("revision walk setup failed"));
1700 if (!opts->revs->commits)
1701 return error(_("empty commit set passed"));
1702 return 0;
1705 static int read_and_refresh_cache(struct replay_opts *opts)
1707 struct lock_file index_lock = LOCK_INIT;
1708 int index_fd = hold_locked_index(&index_lock, 0);
1709 if (read_index_preload(&the_index, NULL) < 0) {
1710 rollback_lock_file(&index_lock);
1711 return error(_("git %s: failed to read the index"),
1712 _(action_name(opts)));
1714 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1715 if (index_fd >= 0) {
1716 if (write_locked_index(&the_index, &index_lock,
1717 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1718 return error(_("git %s: failed to refresh the index"),
1719 _(action_name(opts)));
1722 return 0;
1725 struct todo_item {
1726 enum todo_command command;
1727 struct commit *commit;
1728 const char *arg;
1729 int arg_len;
1730 size_t offset_in_buf;
1733 struct todo_list {
1734 struct strbuf buf;
1735 struct todo_item *items;
1736 int nr, alloc, current;
1737 int done_nr, total_nr;
1738 struct stat_data stat;
1741 #define TODO_LIST_INIT { STRBUF_INIT }
1743 static void todo_list_release(struct todo_list *todo_list)
1745 strbuf_release(&todo_list->buf);
1746 FREE_AND_NULL(todo_list->items);
1747 todo_list->nr = todo_list->alloc = 0;
1750 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1752 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1753 return todo_list->items + todo_list->nr++;
1756 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1758 struct object_id commit_oid;
1759 char *end_of_object_name;
1760 int i, saved, status, padding;
1762 /* left-trim */
1763 bol += strspn(bol, " \t");
1765 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1766 item->command = TODO_COMMENT;
1767 item->commit = NULL;
1768 item->arg = bol;
1769 item->arg_len = eol - bol;
1770 return 0;
1773 for (i = 0; i < TODO_COMMENT; i++)
1774 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1775 item->command = i;
1776 break;
1777 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1778 bol++;
1779 item->command = i;
1780 break;
1782 if (i >= TODO_COMMENT)
1783 return -1;
1785 /* Eat up extra spaces/ tabs before object name */
1786 padding = strspn(bol, " \t");
1787 bol += padding;
1789 if (item->command == TODO_NOOP) {
1790 if (bol != eol)
1791 return error(_("%s does not accept arguments: '%s'"),
1792 command_to_string(item->command), bol);
1793 item->commit = NULL;
1794 item->arg = bol;
1795 item->arg_len = eol - bol;
1796 return 0;
1799 if (!padding)
1800 return error(_("missing arguments for %s"),
1801 command_to_string(item->command));
1803 if (item->command == TODO_EXEC) {
1804 item->commit = NULL;
1805 item->arg = bol;
1806 item->arg_len = (int)(eol - bol);
1807 return 0;
1810 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1811 saved = *end_of_object_name;
1812 *end_of_object_name = '\0';
1813 status = get_oid(bol, &commit_oid);
1814 *end_of_object_name = saved;
1816 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1817 item->arg_len = (int)(eol - item->arg);
1819 if (status < 0)
1820 return -1;
1822 item->commit = lookup_commit_reference(&commit_oid);
1823 return !item->commit;
1826 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1828 struct todo_item *item;
1829 char *p = buf, *next_p;
1830 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1832 for (i = 1; *p; i++, p = next_p) {
1833 char *eol = strchrnul(p, '\n');
1835 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1837 if (p != eol && eol[-1] == '\r')
1838 eol--; /* strip Carriage Return */
1840 item = append_new_todo(todo_list);
1841 item->offset_in_buf = p - todo_list->buf.buf;
1842 if (parse_insn_line(item, p, eol)) {
1843 res = error(_("invalid line %d: %.*s"),
1844 i, (int)(eol - p), p);
1845 item->command = TODO_NOOP;
1848 if (fixup_okay)
1849 ; /* do nothing */
1850 else if (is_fixup(item->command))
1851 return error(_("cannot '%s' without a previous commit"),
1852 command_to_string(item->command));
1853 else if (!is_noop(item->command))
1854 fixup_okay = 1;
1857 return res;
1860 static int count_commands(struct todo_list *todo_list)
1862 int count = 0, i;
1864 for (i = 0; i < todo_list->nr; i++)
1865 if (todo_list->items[i].command != TODO_COMMENT)
1866 count++;
1868 return count;
1871 static int read_populate_todo(struct todo_list *todo_list,
1872 struct replay_opts *opts)
1874 struct stat st;
1875 const char *todo_file = get_todo_path(opts);
1876 int fd, res;
1878 strbuf_reset(&todo_list->buf);
1879 fd = open(todo_file, O_RDONLY);
1880 if (fd < 0)
1881 return error_errno(_("could not open '%s'"), todo_file);
1882 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1883 close(fd);
1884 return error(_("could not read '%s'."), todo_file);
1886 close(fd);
1888 res = stat(todo_file, &st);
1889 if (res)
1890 return error(_("could not stat '%s'"), todo_file);
1891 fill_stat_data(&todo_list->stat, &st);
1893 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1894 if (res) {
1895 if (is_rebase_i(opts))
1896 return error(_("please fix this using "
1897 "'git rebase --edit-todo'."));
1898 return error(_("unusable instruction sheet: '%s'"), todo_file);
1901 if (!todo_list->nr &&
1902 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1903 return error(_("no commits parsed."));
1905 if (!is_rebase_i(opts)) {
1906 enum todo_command valid =
1907 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1908 int i;
1910 for (i = 0; i < todo_list->nr; i++)
1911 if (valid == todo_list->items[i].command)
1912 continue;
1913 else if (valid == TODO_PICK)
1914 return error(_("cannot cherry-pick during a revert."));
1915 else
1916 return error(_("cannot revert during a cherry-pick."));
1919 if (is_rebase_i(opts)) {
1920 struct todo_list done = TODO_LIST_INIT;
1921 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1923 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1924 !parse_insn_buffer(done.buf.buf, &done))
1925 todo_list->done_nr = count_commands(&done);
1926 else
1927 todo_list->done_nr = 0;
1929 todo_list->total_nr = todo_list->done_nr
1930 + count_commands(todo_list);
1931 todo_list_release(&done);
1933 if (f) {
1934 fprintf(f, "%d\n", todo_list->total_nr);
1935 fclose(f);
1939 return 0;
1942 static int git_config_string_dup(char **dest,
1943 const char *var, const char *value)
1945 if (!value)
1946 return config_error_nonbool(var);
1947 free(*dest);
1948 *dest = xstrdup(value);
1949 return 0;
1952 static int populate_opts_cb(const char *key, const char *value, void *data)
1954 struct replay_opts *opts = data;
1955 int error_flag = 1;
1957 if (!value)
1958 error_flag = 0;
1959 else if (!strcmp(key, "options.no-commit"))
1960 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1961 else if (!strcmp(key, "options.edit"))
1962 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1963 else if (!strcmp(key, "options.signoff"))
1964 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1965 else if (!strcmp(key, "options.record-origin"))
1966 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1967 else if (!strcmp(key, "options.allow-ff"))
1968 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1969 else if (!strcmp(key, "options.mainline"))
1970 opts->mainline = git_config_int(key, value);
1971 else if (!strcmp(key, "options.strategy"))
1972 git_config_string_dup(&opts->strategy, key, value);
1973 else if (!strcmp(key, "options.gpg-sign"))
1974 git_config_string_dup(&opts->gpg_sign, key, value);
1975 else if (!strcmp(key, "options.strategy-option")) {
1976 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1977 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1978 } else if (!strcmp(key, "options.allow-rerere-auto"))
1979 opts->allow_rerere_auto =
1980 git_config_bool_or_int(key, value, &error_flag) ?
1981 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1982 else
1983 return error(_("invalid key: %s"), key);
1985 if (!error_flag)
1986 return error(_("invalid value for %s: %s"), key, value);
1988 return 0;
1991 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1993 int i;
1995 strbuf_reset(buf);
1996 if (!read_oneliner(buf, rebase_path_strategy(), 0))
1997 return;
1998 opts->strategy = strbuf_detach(buf, NULL);
1999 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2000 return;
2002 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2003 for (i = 0; i < opts->xopts_nr; i++) {
2004 const char *arg = opts->xopts[i];
2006 skip_prefix(arg, "--", &arg);
2007 opts->xopts[i] = xstrdup(arg);
2011 static int read_populate_opts(struct replay_opts *opts)
2013 if (is_rebase_i(opts)) {
2014 struct strbuf buf = STRBUF_INIT;
2016 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2017 if (!starts_with(buf.buf, "-S"))
2018 strbuf_reset(&buf);
2019 else {
2020 free(opts->gpg_sign);
2021 opts->gpg_sign = xstrdup(buf.buf + 2);
2023 strbuf_reset(&buf);
2026 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2027 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2028 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2029 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2030 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2031 strbuf_reset(&buf);
2034 if (file_exists(rebase_path_verbose()))
2035 opts->verbose = 1;
2037 read_strategy_opts(opts, &buf);
2038 strbuf_release(&buf);
2040 return 0;
2043 if (!file_exists(git_path_opts_file()))
2044 return 0;
2046 * The function git_parse_source(), called from git_config_from_file(),
2047 * may die() in case of a syntactically incorrect file. We do not care
2048 * about this case, though, because we wrote that file ourselves, so we
2049 * are pretty certain that it is syntactically correct.
2051 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2052 return error(_("malformed options sheet: '%s'"),
2053 git_path_opts_file());
2054 return 0;
2057 static int walk_revs_populate_todo(struct todo_list *todo_list,
2058 struct replay_opts *opts)
2060 enum todo_command command = opts->action == REPLAY_PICK ?
2061 TODO_PICK : TODO_REVERT;
2062 const char *command_string = todo_command_info[command].str;
2063 struct commit *commit;
2065 if (prepare_revs(opts))
2066 return -1;
2068 while ((commit = get_revision(opts->revs))) {
2069 struct todo_item *item = append_new_todo(todo_list);
2070 const char *commit_buffer = get_commit_buffer(commit, NULL);
2071 const char *subject;
2072 int subject_len;
2074 item->command = command;
2075 item->commit = commit;
2076 item->arg = NULL;
2077 item->arg_len = 0;
2078 item->offset_in_buf = todo_list->buf.len;
2079 subject_len = find_commit_subject(commit_buffer, &subject);
2080 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2081 short_commit_name(commit), subject_len, subject);
2082 unuse_commit_buffer(commit, commit_buffer);
2084 return 0;
2087 static int create_seq_dir(void)
2089 if (file_exists(git_path_seq_dir())) {
2090 error(_("a cherry-pick or revert is already in progress"));
2091 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2092 return -1;
2093 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2094 return error_errno(_("could not create sequencer directory '%s'"),
2095 git_path_seq_dir());
2096 return 0;
2099 static int save_head(const char *head)
2101 struct lock_file head_lock = LOCK_INIT;
2102 struct strbuf buf = STRBUF_INIT;
2103 int fd;
2104 ssize_t written;
2106 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2107 if (fd < 0)
2108 return error_errno(_("could not lock HEAD"));
2109 strbuf_addf(&buf, "%s\n", head);
2110 written = write_in_full(fd, buf.buf, buf.len);
2111 strbuf_release(&buf);
2112 if (written < 0) {
2113 rollback_lock_file(&head_lock);
2114 return error_errno(_("could not write to '%s'"),
2115 git_path_head_file());
2117 if (commit_lock_file(&head_lock) < 0)
2118 return error(_("failed to finalize '%s'"), git_path_head_file());
2119 return 0;
2122 static int rollback_is_safe(void)
2124 struct strbuf sb = STRBUF_INIT;
2125 struct object_id expected_head, actual_head;
2127 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2128 strbuf_trim(&sb);
2129 if (get_oid_hex(sb.buf, &expected_head)) {
2130 strbuf_release(&sb);
2131 die(_("could not parse %s"), git_path_abort_safety_file());
2133 strbuf_release(&sb);
2135 else if (errno == ENOENT)
2136 oidclr(&expected_head);
2137 else
2138 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2140 if (get_oid("HEAD", &actual_head))
2141 oidclr(&actual_head);
2143 return !oidcmp(&actual_head, &expected_head);
2146 static int reset_for_rollback(const struct object_id *oid)
2148 const char *argv[4]; /* reset --merge <arg> + NULL */
2150 argv[0] = "reset";
2151 argv[1] = "--merge";
2152 argv[2] = oid_to_hex(oid);
2153 argv[3] = NULL;
2154 return run_command_v_opt(argv, RUN_GIT_CMD);
2157 static int rollback_single_pick(void)
2159 struct object_id head_oid;
2161 if (!file_exists(git_path_cherry_pick_head()) &&
2162 !file_exists(git_path_revert_head()))
2163 return error(_("no cherry-pick or revert in progress"));
2164 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2165 return error(_("cannot resolve HEAD"));
2166 if (is_null_oid(&head_oid))
2167 return error(_("cannot abort from a branch yet to be born"));
2168 return reset_for_rollback(&head_oid);
2171 int sequencer_rollback(struct replay_opts *opts)
2173 FILE *f;
2174 struct object_id oid;
2175 struct strbuf buf = STRBUF_INIT;
2176 const char *p;
2178 f = fopen(git_path_head_file(), "r");
2179 if (!f && errno == ENOENT) {
2181 * There is no multiple-cherry-pick in progress.
2182 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2183 * a single-cherry-pick in progress, abort that.
2185 return rollback_single_pick();
2187 if (!f)
2188 return error_errno(_("cannot open '%s'"), git_path_head_file());
2189 if (strbuf_getline_lf(&buf, f)) {
2190 error(_("cannot read '%s': %s"), git_path_head_file(),
2191 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2192 fclose(f);
2193 goto fail;
2195 fclose(f);
2196 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2197 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2198 git_path_head_file());
2199 goto fail;
2201 if (is_null_oid(&oid)) {
2202 error(_("cannot abort from a branch yet to be born"));
2203 goto fail;
2206 if (!rollback_is_safe()) {
2207 /* Do not error, just do not rollback */
2208 warning(_("You seem to have moved HEAD. "
2209 "Not rewinding, check your HEAD!"));
2210 } else
2211 if (reset_for_rollback(&oid))
2212 goto fail;
2213 strbuf_release(&buf);
2214 return sequencer_remove_state(opts);
2215 fail:
2216 strbuf_release(&buf);
2217 return -1;
2220 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2222 struct lock_file todo_lock = LOCK_INIT;
2223 const char *todo_path = get_todo_path(opts);
2224 int next = todo_list->current, offset, fd;
2227 * rebase -i writes "git-rebase-todo" without the currently executing
2228 * command, appending it to "done" instead.
2230 if (is_rebase_i(opts))
2231 next++;
2233 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2234 if (fd < 0)
2235 return error_errno(_("could not lock '%s'"), todo_path);
2236 offset = next < todo_list->nr ?
2237 todo_list->items[next].offset_in_buf : todo_list->buf.len;
2238 if (write_in_full(fd, todo_list->buf.buf + offset,
2239 todo_list->buf.len - offset) < 0)
2240 return error_errno(_("could not write to '%s'"), todo_path);
2241 if (commit_lock_file(&todo_lock) < 0)
2242 return error(_("failed to finalize '%s'"), todo_path);
2244 if (is_rebase_i(opts)) {
2245 const char *done_path = rebase_path_done();
2246 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2247 int prev_offset = !next ? 0 :
2248 todo_list->items[next - 1].offset_in_buf;
2250 if (fd >= 0 && offset > prev_offset &&
2251 write_in_full(fd, todo_list->buf.buf + prev_offset,
2252 offset - prev_offset) < 0) {
2253 close(fd);
2254 return error_errno(_("could not write to '%s'"),
2255 done_path);
2257 if (fd >= 0)
2258 close(fd);
2260 return 0;
2263 static int save_opts(struct replay_opts *opts)
2265 const char *opts_file = git_path_opts_file();
2266 int res = 0;
2268 if (opts->no_commit)
2269 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2270 if (opts->edit)
2271 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2272 if (opts->signoff)
2273 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2274 if (opts->record_origin)
2275 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2276 if (opts->allow_ff)
2277 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2278 if (opts->mainline) {
2279 struct strbuf buf = STRBUF_INIT;
2280 strbuf_addf(&buf, "%d", opts->mainline);
2281 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2282 strbuf_release(&buf);
2284 if (opts->strategy)
2285 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2286 if (opts->gpg_sign)
2287 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2288 if (opts->xopts) {
2289 int i;
2290 for (i = 0; i < opts->xopts_nr; i++)
2291 res |= git_config_set_multivar_in_file_gently(opts_file,
2292 "options.strategy-option",
2293 opts->xopts[i], "^$", 0);
2295 if (opts->allow_rerere_auto)
2296 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2297 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2298 "true" : "false");
2299 return res;
2302 static int make_patch(struct commit *commit, struct replay_opts *opts)
2304 struct strbuf buf = STRBUF_INIT;
2305 struct rev_info log_tree_opt;
2306 const char *subject, *p;
2307 int res = 0;
2309 p = short_commit_name(commit);
2310 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2311 return -1;
2313 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2314 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2315 init_revisions(&log_tree_opt, NULL);
2316 log_tree_opt.abbrev = 0;
2317 log_tree_opt.diff = 1;
2318 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2319 log_tree_opt.disable_stdin = 1;
2320 log_tree_opt.no_commit_id = 1;
2321 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2322 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2323 if (!log_tree_opt.diffopt.file)
2324 res |= error_errno(_("could not open '%s'"), buf.buf);
2325 else {
2326 res |= log_tree_commit(&log_tree_opt, commit);
2327 fclose(log_tree_opt.diffopt.file);
2329 strbuf_reset(&buf);
2331 strbuf_addf(&buf, "%s/message", get_dir(opts));
2332 if (!file_exists(buf.buf)) {
2333 const char *commit_buffer = get_commit_buffer(commit, NULL);
2334 find_commit_subject(commit_buffer, &subject);
2335 res |= write_message(subject, strlen(subject), buf.buf, 1);
2336 unuse_commit_buffer(commit, commit_buffer);
2338 strbuf_release(&buf);
2340 return res;
2343 static int intend_to_amend(void)
2345 struct object_id head;
2346 char *p;
2348 if (get_oid("HEAD", &head))
2349 return error(_("cannot read HEAD"));
2351 p = oid_to_hex(&head);
2352 return write_message(p, strlen(p), rebase_path_amend(), 1);
2355 static int error_with_patch(struct commit *commit,
2356 const char *subject, int subject_len,
2357 struct replay_opts *opts, int exit_code, int to_amend)
2359 if (make_patch(commit, opts))
2360 return -1;
2362 if (to_amend) {
2363 if (intend_to_amend())
2364 return -1;
2366 fprintf(stderr, "You can amend the commit now, with\n"
2367 "\n"
2368 " git commit --amend %s\n"
2369 "\n"
2370 "Once you are satisfied with your changes, run\n"
2371 "\n"
2372 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2373 } else if (exit_code)
2374 fprintf(stderr, "Could not apply %s... %.*s\n",
2375 short_commit_name(commit), subject_len, subject);
2377 return exit_code;
2380 static int error_failed_squash(struct commit *commit,
2381 struct replay_opts *opts, int subject_len, const char *subject)
2383 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2384 return error(_("could not rename '%s' to '%s'"),
2385 rebase_path_squash_msg(), rebase_path_message());
2386 unlink(rebase_path_fixup_msg());
2387 unlink(git_path_merge_msg());
2388 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2389 return error(_("could not copy '%s' to '%s'"),
2390 rebase_path_message(), git_path_merge_msg());
2391 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2394 static int do_exec(const char *command_line)
2396 struct argv_array child_env = ARGV_ARRAY_INIT;
2397 const char *child_argv[] = { NULL, NULL };
2398 int dirty, status;
2400 fprintf(stderr, "Executing: %s\n", command_line);
2401 child_argv[0] = command_line;
2402 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2403 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2404 child_env.argv);
2406 /* force re-reading of the cache */
2407 if (discard_cache() < 0 || read_cache() < 0)
2408 return error(_("could not read index"));
2410 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2412 if (status) {
2413 warning(_("execution failed: %s\n%s"
2414 "You can fix the problem, and then run\n"
2415 "\n"
2416 " git rebase --continue\n"
2417 "\n"),
2418 command_line,
2419 dirty ? N_("and made changes to the index and/or the "
2420 "working tree\n") : "");
2421 if (status == 127)
2422 /* command not found */
2423 status = 1;
2424 } else if (dirty) {
2425 warning(_("execution succeeded: %s\nbut "
2426 "left changes to the index and/or the working tree\n"
2427 "Commit or stash your changes, and then run\n"
2428 "\n"
2429 " git rebase --continue\n"
2430 "\n"), command_line);
2431 status = 1;
2434 argv_array_clear(&child_env);
2436 return status;
2439 static int is_final_fixup(struct todo_list *todo_list)
2441 int i = todo_list->current;
2443 if (!is_fixup(todo_list->items[i].command))
2444 return 0;
2446 while (++i < todo_list->nr)
2447 if (is_fixup(todo_list->items[i].command))
2448 return 0;
2449 else if (!is_noop(todo_list->items[i].command))
2450 break;
2451 return 1;
2454 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2456 int i;
2458 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2459 if (!is_noop(todo_list->items[i].command))
2460 return todo_list->items[i].command;
2462 return -1;
2465 static int apply_autostash(struct replay_opts *opts)
2467 struct strbuf stash_sha1 = STRBUF_INIT;
2468 struct child_process child = CHILD_PROCESS_INIT;
2469 int ret = 0;
2471 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2472 strbuf_release(&stash_sha1);
2473 return 0;
2475 strbuf_trim(&stash_sha1);
2477 child.git_cmd = 1;
2478 child.no_stdout = 1;
2479 child.no_stderr = 1;
2480 argv_array_push(&child.args, "stash");
2481 argv_array_push(&child.args, "apply");
2482 argv_array_push(&child.args, stash_sha1.buf);
2483 if (!run_command(&child))
2484 fprintf(stderr, _("Applied autostash.\n"));
2485 else {
2486 struct child_process store = CHILD_PROCESS_INIT;
2488 store.git_cmd = 1;
2489 argv_array_push(&store.args, "stash");
2490 argv_array_push(&store.args, "store");
2491 argv_array_push(&store.args, "-m");
2492 argv_array_push(&store.args, "autostash");
2493 argv_array_push(&store.args, "-q");
2494 argv_array_push(&store.args, stash_sha1.buf);
2495 if (run_command(&store))
2496 ret = error(_("cannot store %s"), stash_sha1.buf);
2497 else
2498 fprintf(stderr,
2499 _("Applying autostash resulted in conflicts.\n"
2500 "Your changes are safe in the stash.\n"
2501 "You can run \"git stash pop\" or"
2502 " \"git stash drop\" at any time.\n"));
2505 strbuf_release(&stash_sha1);
2506 return ret;
2509 static const char *reflog_message(struct replay_opts *opts,
2510 const char *sub_action, const char *fmt, ...)
2512 va_list ap;
2513 static struct strbuf buf = STRBUF_INIT;
2515 va_start(ap, fmt);
2516 strbuf_reset(&buf);
2517 strbuf_addstr(&buf, action_name(opts));
2518 if (sub_action)
2519 strbuf_addf(&buf, " (%s)", sub_action);
2520 if (fmt) {
2521 strbuf_addstr(&buf, ": ");
2522 strbuf_vaddf(&buf, fmt, ap);
2524 va_end(ap);
2526 return buf.buf;
2529 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2531 int res = 0;
2533 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2534 if (opts->allow_ff)
2535 assert(!(opts->signoff || opts->no_commit ||
2536 opts->record_origin || opts->edit));
2537 if (read_and_refresh_cache(opts))
2538 return -1;
2540 while (todo_list->current < todo_list->nr) {
2541 struct todo_item *item = todo_list->items + todo_list->current;
2542 if (save_todo(todo_list, opts))
2543 return -1;
2544 if (is_rebase_i(opts)) {
2545 if (item->command != TODO_COMMENT) {
2546 FILE *f = fopen(rebase_path_msgnum(), "w");
2548 todo_list->done_nr++;
2550 if (f) {
2551 fprintf(f, "%d\n", todo_list->done_nr);
2552 fclose(f);
2554 fprintf(stderr, "Rebasing (%d/%d)%s",
2555 todo_list->done_nr,
2556 todo_list->total_nr,
2557 opts->verbose ? "\n" : "\r");
2559 unlink(rebase_path_message());
2560 unlink(rebase_path_author_script());
2561 unlink(rebase_path_stopped_sha());
2562 unlink(rebase_path_amend());
2564 if (item->command <= TODO_SQUASH) {
2565 if (is_rebase_i(opts))
2566 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2567 command_to_string(item->command), NULL),
2569 res = do_pick_commit(item->command, item->commit,
2570 opts, is_final_fixup(todo_list));
2571 if (is_rebase_i(opts) && res < 0) {
2572 /* Reschedule */
2573 todo_list->current--;
2574 if (save_todo(todo_list, opts))
2575 return -1;
2577 if (item->command == TODO_EDIT) {
2578 struct commit *commit = item->commit;
2579 if (!res)
2580 fprintf(stderr,
2581 _("Stopped at %s... %.*s\n"),
2582 short_commit_name(commit),
2583 item->arg_len, item->arg);
2584 return error_with_patch(commit,
2585 item->arg, item->arg_len, opts, res,
2586 !res);
2588 if (is_rebase_i(opts) && !res)
2589 record_in_rewritten(&item->commit->object.oid,
2590 peek_command(todo_list, 1));
2591 if (res && is_fixup(item->command)) {
2592 if (res == 1)
2593 intend_to_amend();
2594 return error_failed_squash(item->commit, opts,
2595 item->arg_len, item->arg);
2596 } else if (res && is_rebase_i(opts))
2597 return res | error_with_patch(item->commit,
2598 item->arg, item->arg_len, opts, res,
2599 item->command == TODO_REWORD);
2600 } else if (item->command == TODO_EXEC) {
2601 char *end_of_arg = (char *)(item->arg + item->arg_len);
2602 int saved = *end_of_arg;
2603 struct stat st;
2605 *end_of_arg = '\0';
2606 res = do_exec(item->arg);
2607 *end_of_arg = saved;
2609 /* Reread the todo file if it has changed. */
2610 if (res)
2611 ; /* fall through */
2612 else if (stat(get_todo_path(opts), &st))
2613 res = error_errno(_("could not stat '%s'"),
2614 get_todo_path(opts));
2615 else if (match_stat_data(&todo_list->stat, &st)) {
2616 todo_list_release(todo_list);
2617 if (read_populate_todo(todo_list, opts))
2618 res = -1; /* message was printed */
2619 /* `current` will be incremented below */
2620 todo_list->current = -1;
2622 } else if (!is_noop(item->command))
2623 return error(_("unknown command %d"), item->command);
2625 todo_list->current++;
2626 if (res)
2627 return res;
2630 if (is_rebase_i(opts)) {
2631 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2632 struct stat st;
2634 /* Stopped in the middle, as planned? */
2635 if (todo_list->current < todo_list->nr)
2636 return 0;
2638 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2639 starts_with(head_ref.buf, "refs/")) {
2640 const char *msg;
2641 struct object_id head, orig;
2642 int res;
2644 if (get_oid("HEAD", &head)) {
2645 res = error(_("cannot read HEAD"));
2646 cleanup_head_ref:
2647 strbuf_release(&head_ref);
2648 strbuf_release(&buf);
2649 return res;
2651 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2652 get_oid_hex(buf.buf, &orig)) {
2653 res = error(_("could not read orig-head"));
2654 goto cleanup_head_ref;
2656 strbuf_reset(&buf);
2657 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2658 res = error(_("could not read 'onto'"));
2659 goto cleanup_head_ref;
2661 msg = reflog_message(opts, "finish", "%s onto %s",
2662 head_ref.buf, buf.buf);
2663 if (update_ref(msg, head_ref.buf, &head, &orig,
2664 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2665 res = error(_("could not update %s"),
2666 head_ref.buf);
2667 goto cleanup_head_ref;
2669 msg = reflog_message(opts, "finish", "returning to %s",
2670 head_ref.buf);
2671 if (create_symref("HEAD", head_ref.buf, msg)) {
2672 res = error(_("could not update HEAD to %s"),
2673 head_ref.buf);
2674 goto cleanup_head_ref;
2676 strbuf_reset(&buf);
2679 if (opts->verbose) {
2680 struct rev_info log_tree_opt;
2681 struct object_id orig, head;
2683 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2684 init_revisions(&log_tree_opt, NULL);
2685 log_tree_opt.diff = 1;
2686 log_tree_opt.diffopt.output_format =
2687 DIFF_FORMAT_DIFFSTAT;
2688 log_tree_opt.disable_stdin = 1;
2690 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2691 !get_oid(buf.buf, &orig) &&
2692 !get_oid("HEAD", &head)) {
2693 diff_tree_oid(&orig, &head, "",
2694 &log_tree_opt.diffopt);
2695 log_tree_diff_flush(&log_tree_opt);
2698 flush_rewritten_pending();
2699 if (!stat(rebase_path_rewritten_list(), &st) &&
2700 st.st_size > 0) {
2701 struct child_process child = CHILD_PROCESS_INIT;
2702 const char *post_rewrite_hook =
2703 find_hook("post-rewrite");
2705 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2706 child.git_cmd = 1;
2707 argv_array_push(&child.args, "notes");
2708 argv_array_push(&child.args, "copy");
2709 argv_array_push(&child.args, "--for-rewrite=rebase");
2710 /* we don't care if this copying failed */
2711 run_command(&child);
2713 if (post_rewrite_hook) {
2714 struct child_process hook = CHILD_PROCESS_INIT;
2716 hook.in = open(rebase_path_rewritten_list(),
2717 O_RDONLY);
2718 hook.stdout_to_stderr = 1;
2719 argv_array_push(&hook.args, post_rewrite_hook);
2720 argv_array_push(&hook.args, "rebase");
2721 /* we don't care if this hook failed */
2722 run_command(&hook);
2725 apply_autostash(opts);
2727 fprintf(stderr, "Successfully rebased and updated %s.\n",
2728 head_ref.buf);
2730 strbuf_release(&buf);
2731 strbuf_release(&head_ref);
2735 * Sequence of picks finished successfully; cleanup by
2736 * removing the .git/sequencer directory
2738 return sequencer_remove_state(opts);
2741 static int continue_single_pick(void)
2743 const char *argv[] = { "commit", NULL };
2745 if (!file_exists(git_path_cherry_pick_head()) &&
2746 !file_exists(git_path_revert_head()))
2747 return error(_("no cherry-pick or revert in progress"));
2748 return run_command_v_opt(argv, RUN_GIT_CMD);
2751 static int commit_staged_changes(struct replay_opts *opts)
2753 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2755 if (has_unstaged_changes(1))
2756 return error(_("cannot rebase: You have unstaged changes."));
2757 if (!has_uncommitted_changes(0)) {
2758 const char *cherry_pick_head = git_path_cherry_pick_head();
2760 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2761 return error(_("could not remove CHERRY_PICK_HEAD"));
2762 return 0;
2765 if (file_exists(rebase_path_amend())) {
2766 struct strbuf rev = STRBUF_INIT;
2767 struct object_id head, to_amend;
2769 if (get_oid("HEAD", &head))
2770 return error(_("cannot amend non-existing commit"));
2771 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2772 return error(_("invalid file: '%s'"), rebase_path_amend());
2773 if (get_oid_hex(rev.buf, &to_amend))
2774 return error(_("invalid contents: '%s'"),
2775 rebase_path_amend());
2776 if (oidcmp(&head, &to_amend))
2777 return error(_("\nYou have uncommitted changes in your "
2778 "working tree. Please, commit them\n"
2779 "first and then run 'git rebase "
2780 "--continue' again."));
2782 strbuf_release(&rev);
2783 flags |= AMEND_MSG;
2786 if (run_git_commit(rebase_path_message(), opts, flags))
2787 return error(_("could not commit staged changes."));
2788 unlink(rebase_path_amend());
2789 return 0;
2792 int sequencer_continue(struct replay_opts *opts)
2794 struct todo_list todo_list = TODO_LIST_INIT;
2795 int res;
2797 if (read_and_refresh_cache(opts))
2798 return -1;
2800 if (is_rebase_i(opts)) {
2801 if (commit_staged_changes(opts))
2802 return -1;
2803 } else if (!file_exists(get_todo_path(opts)))
2804 return continue_single_pick();
2805 if (read_populate_opts(opts))
2806 return -1;
2807 if ((res = read_populate_todo(&todo_list, opts)))
2808 goto release_todo_list;
2810 if (!is_rebase_i(opts)) {
2811 /* Verify that the conflict has been resolved */
2812 if (file_exists(git_path_cherry_pick_head()) ||
2813 file_exists(git_path_revert_head())) {
2814 res = continue_single_pick();
2815 if (res)
2816 goto release_todo_list;
2818 if (index_differs_from("HEAD", NULL, 0)) {
2819 res = error_dirty_index(opts);
2820 goto release_todo_list;
2822 todo_list.current++;
2823 } else if (file_exists(rebase_path_stopped_sha())) {
2824 struct strbuf buf = STRBUF_INIT;
2825 struct object_id oid;
2827 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2828 !get_oid_committish(buf.buf, &oid))
2829 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2830 strbuf_release(&buf);
2833 res = pick_commits(&todo_list, opts);
2834 release_todo_list:
2835 todo_list_release(&todo_list);
2836 return res;
2839 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2841 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2842 return do_pick_commit(opts->action == REPLAY_PICK ?
2843 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2846 int sequencer_pick_revisions(struct replay_opts *opts)
2848 struct todo_list todo_list = TODO_LIST_INIT;
2849 struct object_id oid;
2850 int i, res;
2852 assert(opts->revs);
2853 if (read_and_refresh_cache(opts))
2854 return -1;
2856 for (i = 0; i < opts->revs->pending.nr; i++) {
2857 struct object_id oid;
2858 const char *name = opts->revs->pending.objects[i].name;
2860 /* This happens when using --stdin. */
2861 if (!strlen(name))
2862 continue;
2864 if (!get_oid(name, &oid)) {
2865 if (!lookup_commit_reference_gently(&oid, 1)) {
2866 enum object_type type = sha1_object_info(oid.hash, NULL);
2867 return error(_("%s: can't cherry-pick a %s"),
2868 name, typename(type));
2870 } else
2871 return error(_("%s: bad revision"), name);
2875 * If we were called as "git cherry-pick <commit>", just
2876 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2877 * REVERT_HEAD, and don't touch the sequencer state.
2878 * This means it is possible to cherry-pick in the middle
2879 * of a cherry-pick sequence.
2881 if (opts->revs->cmdline.nr == 1 &&
2882 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2883 opts->revs->no_walk &&
2884 !opts->revs->cmdline.rev->flags) {
2885 struct commit *cmit;
2886 if (prepare_revision_walk(opts->revs))
2887 return error(_("revision walk setup failed"));
2888 cmit = get_revision(opts->revs);
2889 if (!cmit || get_revision(opts->revs))
2890 return error("BUG: expected exactly one commit from walk");
2891 return single_pick(cmit, opts);
2895 * Start a new cherry-pick/ revert sequence; but
2896 * first, make sure that an existing one isn't in
2897 * progress
2900 if (walk_revs_populate_todo(&todo_list, opts) ||
2901 create_seq_dir() < 0)
2902 return -1;
2903 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2904 return error(_("can't revert as initial commit"));
2905 if (save_head(oid_to_hex(&oid)))
2906 return -1;
2907 if (save_opts(opts))
2908 return -1;
2909 update_abort_safety_file();
2910 res = pick_commits(&todo_list, opts);
2911 todo_list_release(&todo_list);
2912 return res;
2915 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2917 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2918 struct strbuf sob = STRBUF_INIT;
2919 int has_footer;
2921 strbuf_addstr(&sob, sign_off_header);
2922 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2923 getenv("GIT_COMMITTER_EMAIL")));
2924 strbuf_addch(&sob, '\n');
2926 if (!ignore_footer)
2927 strbuf_complete_line(msgbuf);
2930 * If the whole message buffer is equal to the sob, pretend that we
2931 * found a conforming footer with a matching sob
2933 if (msgbuf->len - ignore_footer == sob.len &&
2934 !strncmp(msgbuf->buf, sob.buf, sob.len))
2935 has_footer = 3;
2936 else
2937 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2939 if (!has_footer) {
2940 const char *append_newlines = NULL;
2941 size_t len = msgbuf->len - ignore_footer;
2943 if (!len) {
2945 * The buffer is completely empty. Leave foom for
2946 * the title and body to be filled in by the user.
2948 append_newlines = "\n\n";
2949 } else if (len == 1) {
2951 * Buffer contains a single newline. Add another
2952 * so that we leave room for the title and body.
2954 append_newlines = "\n";
2955 } else if (msgbuf->buf[len - 2] != '\n') {
2957 * Buffer ends with a single newline. Add another
2958 * so that there is an empty line between the message
2959 * body and the sob.
2961 append_newlines = "\n";
2962 } /* else, the buffer already ends with two newlines. */
2964 if (append_newlines)
2965 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2966 append_newlines, strlen(append_newlines));
2969 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2970 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2971 sob.buf, sob.len);
2973 strbuf_release(&sob);
2976 int sequencer_make_script(FILE *out, int argc, const char **argv,
2977 unsigned flags)
2979 char *format = NULL;
2980 struct pretty_print_context pp = {0};
2981 struct strbuf buf = STRBUF_INIT;
2982 struct rev_info revs;
2983 struct commit *commit;
2984 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
2985 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
2987 init_revisions(&revs, NULL);
2988 revs.verbose_header = 1;
2989 revs.max_parents = 1;
2990 revs.cherry_pick = 1;
2991 revs.limited = 1;
2992 revs.reverse = 1;
2993 revs.right_only = 1;
2994 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2995 revs.topo_order = 1;
2997 revs.pretty_given = 1;
2998 git_config_get_string("rebase.instructionFormat", &format);
2999 if (!format || !*format) {
3000 free(format);
3001 format = xstrdup("%s");
3003 get_commit_format(format, &revs);
3004 free(format);
3005 pp.fmt = revs.commit_format;
3006 pp.output_encoding = get_log_output_encoding();
3008 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3009 return error(_("make_script: unhandled options"));
3011 if (prepare_revision_walk(&revs) < 0)
3012 return error(_("make_script: error preparing revisions"));
3014 while ((commit = get_revision(&revs))) {
3015 strbuf_reset(&buf);
3016 if (!keep_empty && is_original_commit_empty(commit))
3017 strbuf_addf(&buf, "%c ", comment_line_char);
3018 strbuf_addf(&buf, "%s %s ", insn,
3019 oid_to_hex(&commit->object.oid));
3020 pretty_print_commit(&pp, commit, &buf);
3021 strbuf_addch(&buf, '\n');
3022 fputs(buf.buf, out);
3024 strbuf_release(&buf);
3025 return 0;
3029 * Add commands after pick and (series of) squash/fixup commands
3030 * in the todo list.
3032 int sequencer_add_exec_commands(const char *commands)
3034 const char *todo_file = rebase_path_todo();
3035 struct todo_list todo_list = TODO_LIST_INIT;
3036 struct todo_item *item;
3037 struct strbuf *buf = &todo_list.buf;
3038 size_t offset = 0, commands_len = strlen(commands);
3039 int i, first;
3041 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3042 return error(_("could not read '%s'."), todo_file);
3044 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3045 todo_list_release(&todo_list);
3046 return error(_("unusable todo list: '%s'"), todo_file);
3049 first = 1;
3050 /* insert <commands> before every pick except the first one */
3051 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3052 if (item->command == TODO_PICK && !first) {
3053 strbuf_insert(buf, item->offset_in_buf + offset,
3054 commands, commands_len);
3055 offset += commands_len;
3057 first = 0;
3060 /* append final <commands> */
3061 strbuf_add(buf, commands, commands_len);
3063 i = write_message(buf->buf, buf->len, todo_file, 0);
3064 todo_list_release(&todo_list);
3065 return i;
3068 int transform_todos(unsigned flags)
3070 const char *todo_file = rebase_path_todo();
3071 struct todo_list todo_list = TODO_LIST_INIT;
3072 struct strbuf buf = STRBUF_INIT;
3073 struct todo_item *item;
3074 int i;
3076 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3077 return error(_("could not read '%s'."), todo_file);
3079 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3080 todo_list_release(&todo_list);
3081 return error(_("unusable todo list: '%s'"), todo_file);
3084 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3085 /* if the item is not a command write it and continue */
3086 if (item->command >= TODO_COMMENT) {
3087 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3088 continue;
3091 /* add command to the buffer */
3092 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3093 strbuf_addch(&buf, command_to_char(item->command));
3094 else
3095 strbuf_addstr(&buf, command_to_string(item->command));
3097 /* add commit id */
3098 if (item->commit) {
3099 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3100 short_commit_name(item->commit) :
3101 oid_to_hex(&item->commit->object.oid);
3103 strbuf_addf(&buf, " %s", oid);
3105 /* add all the rest */
3106 if (!item->arg_len)
3107 strbuf_addch(&buf, '\n');
3108 else
3109 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3112 i = write_message(buf.buf, buf.len, todo_file, 0);
3113 todo_list_release(&todo_list);
3114 return i;
3117 enum check_level {
3118 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3121 static enum check_level get_missing_commit_check_level(void)
3123 const char *value;
3125 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3126 !strcasecmp("ignore", value))
3127 return CHECK_IGNORE;
3128 if (!strcasecmp("warn", value))
3129 return CHECK_WARN;
3130 if (!strcasecmp("error", value))
3131 return CHECK_ERROR;
3132 warning(_("unrecognized setting %s for option "
3133 "rebase.missingCommitsCheck. Ignoring."), value);
3134 return CHECK_IGNORE;
3138 * Check if the user dropped some commits by mistake
3139 * Behaviour determined by rebase.missingCommitsCheck.
3140 * Check if there is an unrecognized command or a
3141 * bad SHA-1 in a command.
3143 int check_todo_list(void)
3145 enum check_level check_level = get_missing_commit_check_level();
3146 struct strbuf todo_file = STRBUF_INIT;
3147 struct todo_list todo_list = TODO_LIST_INIT;
3148 struct strbuf missing = STRBUF_INIT;
3149 int advise_to_edit_todo = 0, res = 0, fd, i;
3151 strbuf_addstr(&todo_file, rebase_path_todo());
3152 fd = open(todo_file.buf, O_RDONLY);
3153 if (fd < 0) {
3154 res = error_errno(_("could not open '%s'"), todo_file.buf);
3155 goto leave_check;
3157 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3158 close(fd);
3159 res = error(_("could not read '%s'."), todo_file.buf);
3160 goto leave_check;
3162 close(fd);
3163 advise_to_edit_todo = res =
3164 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3166 if (res || check_level == CHECK_IGNORE)
3167 goto leave_check;
3169 /* Mark the commits in git-rebase-todo as seen */
3170 for (i = 0; i < todo_list.nr; i++) {
3171 struct commit *commit = todo_list.items[i].commit;
3172 if (commit)
3173 commit->util = (void *)1;
3176 todo_list_release(&todo_list);
3177 strbuf_addstr(&todo_file, ".backup");
3178 fd = open(todo_file.buf, O_RDONLY);
3179 if (fd < 0) {
3180 res = error_errno(_("could not open '%s'"), todo_file.buf);
3181 goto leave_check;
3183 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3184 close(fd);
3185 res = error(_("could not read '%s'."), todo_file.buf);
3186 goto leave_check;
3188 close(fd);
3189 strbuf_release(&todo_file);
3190 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3192 /* Find commits in git-rebase-todo.backup yet unseen */
3193 for (i = todo_list.nr - 1; i >= 0; i--) {
3194 struct todo_item *item = todo_list.items + i;
3195 struct commit *commit = item->commit;
3196 if (commit && !commit->util) {
3197 strbuf_addf(&missing, " - %s %.*s\n",
3198 short_commit_name(commit),
3199 item->arg_len, item->arg);
3200 commit->util = (void *)1;
3204 /* Warn about missing commits */
3205 if (!missing.len)
3206 goto leave_check;
3208 if (check_level == CHECK_ERROR)
3209 advise_to_edit_todo = res = 1;
3211 fprintf(stderr,
3212 _("Warning: some commits may have been dropped accidentally.\n"
3213 "Dropped commits (newer to older):\n"));
3215 /* Make the list user-friendly and display */
3216 fputs(missing.buf, stderr);
3217 strbuf_release(&missing);
3219 fprintf(stderr, _("To avoid this message, use \"drop\" to "
3220 "explicitly remove a commit.\n\n"
3221 "Use 'git config rebase.missingCommitsCheck' to change "
3222 "the level of warnings.\n"
3223 "The possible behaviours are: ignore, warn, error.\n\n"));
3225 leave_check:
3226 strbuf_release(&todo_file);
3227 todo_list_release(&todo_list);
3229 if (advise_to_edit_todo)
3230 fprintf(stderr,
3231 _("You can fix this with 'git rebase --edit-todo' "
3232 "and then run 'git rebase --continue'.\n"
3233 "Or you can abort the rebase with 'git rebase"
3234 " --abort'.\n"));
3236 return res;
3239 static int rewrite_file(const char *path, const char *buf, size_t len)
3241 int rc = 0;
3242 int fd = open(path, O_WRONLY | O_TRUNC);
3243 if (fd < 0)
3244 return error_errno(_("could not open '%s' for writing"), path);
3245 if (write_in_full(fd, buf, len) < 0)
3246 rc = error_errno(_("could not write to '%s'"), path);
3247 if (close(fd) && !rc)
3248 rc = error_errno(_("could not close '%s'"), path);
3249 return rc;
3252 /* skip picking commits whose parents are unchanged */
3253 int skip_unnecessary_picks(void)
3255 const char *todo_file = rebase_path_todo();
3256 struct strbuf buf = STRBUF_INIT;
3257 struct todo_list todo_list = TODO_LIST_INIT;
3258 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3259 int fd, i;
3261 if (!read_oneliner(&buf, rebase_path_onto(), 0))
3262 return error(_("could not read 'onto'"));
3263 if (get_oid(buf.buf, &onto_oid)) {
3264 strbuf_release(&buf);
3265 return error(_("need a HEAD to fixup"));
3267 strbuf_release(&buf);
3269 fd = open(todo_file, O_RDONLY);
3270 if (fd < 0) {
3271 return error_errno(_("could not open '%s'"), todo_file);
3273 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3274 close(fd);
3275 return error(_("could not read '%s'."), todo_file);
3277 close(fd);
3278 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3279 todo_list_release(&todo_list);
3280 return -1;
3283 for (i = 0; i < todo_list.nr; i++) {
3284 struct todo_item *item = todo_list.items + i;
3286 if (item->command >= TODO_NOOP)
3287 continue;
3288 if (item->command != TODO_PICK)
3289 break;
3290 if (parse_commit(item->commit)) {
3291 todo_list_release(&todo_list);
3292 return error(_("could not parse commit '%s'"),
3293 oid_to_hex(&item->commit->object.oid));
3295 if (!item->commit->parents)
3296 break; /* root commit */
3297 if (item->commit->parents->next)
3298 break; /* merge commit */
3299 parent_oid = &item->commit->parents->item->object.oid;
3300 if (hashcmp(parent_oid->hash, oid->hash))
3301 break;
3302 oid = &item->commit->object.oid;
3304 if (i > 0) {
3305 int offset = i < todo_list.nr ?
3306 todo_list.items[i].offset_in_buf : todo_list.buf.len;
3307 const char *done_path = rebase_path_done();
3309 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3310 if (fd < 0) {
3311 error_errno(_("could not open '%s' for writing"),
3312 done_path);
3313 todo_list_release(&todo_list);
3314 return -1;
3316 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3317 error_errno(_("could not write to '%s'"), done_path);
3318 todo_list_release(&todo_list);
3319 close(fd);
3320 return -1;
3322 close(fd);
3324 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3325 todo_list.buf.len - offset) < 0) {
3326 todo_list_release(&todo_list);
3327 return -1;
3330 todo_list.current = i;
3331 if (is_fixup(peek_command(&todo_list, 0)))
3332 record_in_rewritten(oid, peek_command(&todo_list, 0));
3335 todo_list_release(&todo_list);
3336 printf("%s\n", oid_to_hex(oid));
3338 return 0;
3341 struct subject2item_entry {
3342 struct hashmap_entry entry;
3343 int i;
3344 char subject[FLEX_ARRAY];
3347 static int subject2item_cmp(const void *fndata,
3348 const struct subject2item_entry *a,
3349 const struct subject2item_entry *b, const void *key)
3351 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3355 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3356 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3357 * after the former, and change "pick" to "fixup"/"squash".
3359 * Note that if the config has specified a custom instruction format, each log
3360 * message will have to be retrieved from the commit (as the oneline in the
3361 * script cannot be trusted) in order to normalize the autosquash arrangement.
3363 int rearrange_squash(void)
3365 const char *todo_file = rebase_path_todo();
3366 struct todo_list todo_list = TODO_LIST_INIT;
3367 struct hashmap subject2item;
3368 int res = 0, rearranged = 0, *next, *tail, fd, i;
3369 char **subjects;
3371 fd = open(todo_file, O_RDONLY);
3372 if (fd < 0)
3373 return error_errno(_("could not open '%s'"), todo_file);
3374 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3375 close(fd);
3376 return error(_("could not read '%s'."), todo_file);
3378 close(fd);
3379 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3380 todo_list_release(&todo_list);
3381 return -1;
3385 * The hashmap maps onelines to the respective todo list index.
3387 * If any items need to be rearranged, the next[i] value will indicate
3388 * which item was moved directly after the i'th.
3390 * In that case, last[i] will indicate the index of the latest item to
3391 * be moved to appear after the i'th.
3393 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3394 NULL, todo_list.nr);
3395 ALLOC_ARRAY(next, todo_list.nr);
3396 ALLOC_ARRAY(tail, todo_list.nr);
3397 ALLOC_ARRAY(subjects, todo_list.nr);
3398 for (i = 0; i < todo_list.nr; i++) {
3399 struct strbuf buf = STRBUF_INIT;
3400 struct todo_item *item = todo_list.items + i;
3401 const char *commit_buffer, *subject, *p;
3402 size_t subject_len;
3403 int i2 = -1;
3404 struct subject2item_entry *entry;
3406 next[i] = tail[i] = -1;
3407 if (item->command >= TODO_EXEC) {
3408 subjects[i] = NULL;
3409 continue;
3412 if (is_fixup(item->command)) {
3413 todo_list_release(&todo_list);
3414 return error(_("the script was already rearranged."));
3417 item->commit->util = item;
3419 parse_commit(item->commit);
3420 commit_buffer = get_commit_buffer(item->commit, NULL);
3421 find_commit_subject(commit_buffer, &subject);
3422 format_subject(&buf, subject, " ");
3423 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3424 unuse_commit_buffer(item->commit, commit_buffer);
3425 if ((skip_prefix(subject, "fixup! ", &p) ||
3426 skip_prefix(subject, "squash! ", &p))) {
3427 struct commit *commit2;
3429 for (;;) {
3430 while (isspace(*p))
3431 p++;
3432 if (!skip_prefix(p, "fixup! ", &p) &&
3433 !skip_prefix(p, "squash! ", &p))
3434 break;
3437 if ((entry = hashmap_get_from_hash(&subject2item,
3438 strhash(p), p)))
3439 /* found by title */
3440 i2 = entry->i;
3441 else if (!strchr(p, ' ') &&
3442 (commit2 =
3443 lookup_commit_reference_by_name(p)) &&
3444 commit2->util)
3445 /* found by commit name */
3446 i2 = (struct todo_item *)commit2->util
3447 - todo_list.items;
3448 else {
3449 /* copy can be a prefix of the commit subject */
3450 for (i2 = 0; i2 < i; i2++)
3451 if (subjects[i2] &&
3452 starts_with(subjects[i2], p))
3453 break;
3454 if (i2 == i)
3455 i2 = -1;
3458 if (i2 >= 0) {
3459 rearranged = 1;
3460 todo_list.items[i].command =
3461 starts_with(subject, "fixup!") ?
3462 TODO_FIXUP : TODO_SQUASH;
3463 if (next[i2] < 0)
3464 next[i2] = i;
3465 else
3466 next[tail[i2]] = i;
3467 tail[i2] = i;
3468 } else if (!hashmap_get_from_hash(&subject2item,
3469 strhash(subject), subject)) {
3470 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3471 entry->i = i;
3472 hashmap_entry_init(entry, strhash(entry->subject));
3473 hashmap_put(&subject2item, entry);
3477 if (rearranged) {
3478 struct strbuf buf = STRBUF_INIT;
3480 for (i = 0; i < todo_list.nr; i++) {
3481 enum todo_command command = todo_list.items[i].command;
3482 int cur = i;
3485 * Initially, all commands are 'pick's. If it is a
3486 * fixup or a squash now, we have rearranged it.
3488 if (is_fixup(command))
3489 continue;
3491 while (cur >= 0) {
3492 int offset = todo_list.items[cur].offset_in_buf;
3493 int end_offset = cur + 1 < todo_list.nr ?
3494 todo_list.items[cur + 1].offset_in_buf :
3495 todo_list.buf.len;
3496 char *bol = todo_list.buf.buf + offset;
3497 char *eol = todo_list.buf.buf + end_offset;
3499 /* replace 'pick', by 'fixup' or 'squash' */
3500 command = todo_list.items[cur].command;
3501 if (is_fixup(command)) {
3502 strbuf_addstr(&buf,
3503 todo_command_info[command].str);
3504 bol += strcspn(bol, " \t");
3507 strbuf_add(&buf, bol, eol - bol);
3509 cur = next[cur];
3513 res = rewrite_file(todo_file, buf.buf, buf.len);
3514 strbuf_release(&buf);
3517 free(next);
3518 free(tail);
3519 for (i = 0; i < todo_list.nr; i++)
3520 free(subjects[i]);
3521 free(subjects);
3522 hashmap_free(&subject2item, 1);
3523 todo_list_release(&todo_list);
3525 return res;