rebase --rebase-merges: adjust man page for octopus support
[alt-git.git] / sequencer.c
blobbcc43699cd92fa517b06746a833e1181ff5e275d
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"
26 #include "unpack-trees.h"
27 #include "worktree.h"
28 #include "oidmap.h"
29 #include "oidset.h"
30 #include "commit-slab.h"
31 #include "alias.h"
33 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
35 const char sign_off_header[] = "Signed-off-by: ";
36 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
38 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
40 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
42 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
43 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
44 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
45 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
47 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
49 * The file containing rebase commands, comments, and empty lines.
50 * This file is created by "git rebase -i" then edited by the user. As
51 * the lines are processed, they are removed from the front of this
52 * file and written to the tail of 'done'.
54 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
56 * The rebase command lines that have already been processed. A line
57 * is moved here when it is first handled, before any associated user
58 * actions.
60 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
62 * The file to keep track of how many commands were already processed (e.g.
63 * for the prompt).
65 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
67 * The file to keep track of how many commands are to be processed in total
68 * (e.g. for the prompt).
70 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
72 * The commit message that is planned to be used for any changes that
73 * need to be committed following a user interaction.
75 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
77 * The file into which is accumulated the suggested commit message for
78 * squash/fixup commands. When the first of a series of squash/fixups
79 * is seen, the file is created and the commit message from the
80 * previous commit and from the first squash/fixup commit are written
81 * to it. The commit message for each subsequent squash/fixup commit
82 * is appended to the file as it is processed.
84 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
86 * If the current series of squash/fixups has not yet included a squash
87 * command, then this file exists and holds the commit message of the
88 * original "pick" commit. (If the series ends without a "squash"
89 * command, then this can be used as the commit message of the combined
90 * commit without opening the editor.)
92 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
94 * This file contains the list fixup/squash commands that have been
95 * accumulated into message-fixup or message-squash so far.
97 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
99 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
100 * GIT_AUTHOR_DATE that will be used for the commit that is currently
101 * being rebased.
103 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
105 * When an "edit" rebase command is being processed, the SHA1 of the
106 * commit to be edited is recorded in this file. When "git rebase
107 * --continue" is executed, if there are any staged changes then they
108 * will be amended to the HEAD commit, but only provided the HEAD
109 * commit is still the commit to be edited. When any other rebase
110 * command is processed, this file is deleted.
112 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
114 * When we stop at a given patch via the "edit" command, this file contains
115 * the abbreviated commit name of the corresponding patch.
117 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
119 * For the post-rewrite hook, we make a list of rewritten commits and
120 * their new sha1s. The rewritten-pending list keeps the sha1s of
121 * commits that have been processed, but not committed yet,
122 * e.g. because they are waiting for a 'squash' command.
124 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
125 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
126 "rebase-merge/rewritten-pending")
129 * The path of the file containig the OID of the "squash onto" commit, i.e.
130 * the dummy commit used for `reset [new root]`.
132 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
135 * The path of the file listing refs that need to be deleted after the rebase
136 * finishes. This is used by the `label` command to record the need for cleanup.
138 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
141 * The following files are written by git-rebase just after parsing the
142 * command-line (and are only consumed, not modified, by the sequencer).
144 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
145 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
146 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
147 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
148 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
149 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
150 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
151 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
152 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
153 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
155 static int git_sequencer_config(const char *k, const char *v, void *cb)
157 struct replay_opts *opts = cb;
158 int status;
160 if (!strcmp(k, "commit.cleanup")) {
161 const char *s;
163 status = git_config_string(&s, k, v);
164 if (status)
165 return status;
167 if (!strcmp(s, "verbatim"))
168 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
169 else if (!strcmp(s, "whitespace"))
170 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
171 else if (!strcmp(s, "strip"))
172 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
173 else if (!strcmp(s, "scissors"))
174 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
175 else
176 warning(_("invalid commit message cleanup mode '%s'"),
179 free((char *)s);
180 return status;
183 if (!strcmp(k, "commit.gpgsign")) {
184 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
185 return 0;
188 status = git_gpg_config(k, v, NULL);
189 if (status)
190 return status;
192 return git_diff_basic_config(k, v, NULL);
195 void sequencer_init_config(struct replay_opts *opts)
197 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
198 git_config(git_sequencer_config, opts);
201 static inline int is_rebase_i(const struct replay_opts *opts)
203 return opts->action == REPLAY_INTERACTIVE_REBASE;
206 static const char *get_dir(const struct replay_opts *opts)
208 if (is_rebase_i(opts))
209 return rebase_path();
210 return git_path_seq_dir();
213 static const char *get_todo_path(const struct replay_opts *opts)
215 if (is_rebase_i(opts))
216 return rebase_path_todo();
217 return git_path_todo_file();
221 * Returns 0 for non-conforming footer
222 * Returns 1 for conforming footer
223 * Returns 2 when sob exists within conforming footer
224 * Returns 3 when sob exists within conforming footer as last entry
226 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
227 int ignore_footer)
229 struct trailer_info info;
230 int i;
231 int found_sob = 0, found_sob_last = 0;
233 trailer_info_get(&info, sb->buf);
235 if (info.trailer_start == info.trailer_end)
236 return 0;
238 for (i = 0; i < info.trailer_nr; i++)
239 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
240 found_sob = 1;
241 if (i == info.trailer_nr - 1)
242 found_sob_last = 1;
245 trailer_info_release(&info);
247 if (found_sob_last)
248 return 3;
249 if (found_sob)
250 return 2;
251 return 1;
254 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
256 static struct strbuf buf = STRBUF_INIT;
258 strbuf_reset(&buf);
259 if (opts->gpg_sign)
260 sq_quotef(&buf, "-S%s", opts->gpg_sign);
261 return buf.buf;
264 int sequencer_remove_state(struct replay_opts *opts)
266 struct strbuf buf = STRBUF_INIT;
267 int i;
269 if (is_rebase_i(opts) &&
270 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
271 char *p = buf.buf;
272 while (*p) {
273 char *eol = strchr(p, '\n');
274 if (eol)
275 *eol = '\0';
276 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
277 warning(_("could not delete '%s'"), p);
278 if (!eol)
279 break;
280 p = eol + 1;
284 free(opts->gpg_sign);
285 free(opts->strategy);
286 for (i = 0; i < opts->xopts_nr; i++)
287 free(opts->xopts[i]);
288 free(opts->xopts);
289 strbuf_release(&opts->current_fixups);
291 strbuf_reset(&buf);
292 strbuf_addstr(&buf, get_dir(opts));
293 remove_dir_recursively(&buf, 0);
294 strbuf_release(&buf);
296 return 0;
299 static const char *action_name(const struct replay_opts *opts)
301 switch (opts->action) {
302 case REPLAY_REVERT:
303 return N_("revert");
304 case REPLAY_PICK:
305 return N_("cherry-pick");
306 case REPLAY_INTERACTIVE_REBASE:
307 return N_("rebase -i");
309 die(_("Unknown action: %d"), opts->action);
312 struct commit_message {
313 char *parent_label;
314 char *label;
315 char *subject;
316 const char *message;
319 static const char *short_commit_name(struct commit *commit)
321 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
324 static int get_message(struct commit *commit, struct commit_message *out)
326 const char *abbrev, *subject;
327 int subject_len;
329 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
330 abbrev = short_commit_name(commit);
332 subject_len = find_commit_subject(out->message, &subject);
334 out->subject = xmemdupz(subject, subject_len);
335 out->label = xstrfmt("%s... %s", abbrev, out->subject);
336 out->parent_label = xstrfmt("parent of %s", out->label);
338 return 0;
341 static void free_message(struct commit *commit, struct commit_message *msg)
343 free(msg->parent_label);
344 free(msg->label);
345 free(msg->subject);
346 unuse_commit_buffer(commit, msg->message);
349 static void print_advice(int show_hint, struct replay_opts *opts)
351 char *msg = getenv("GIT_CHERRY_PICK_HELP");
353 if (msg) {
354 fprintf(stderr, "%s\n", msg);
356 * A conflict has occurred but the porcelain
357 * (typically rebase --interactive) wants to take care
358 * of the commit itself so remove CHERRY_PICK_HEAD
360 unlink(git_path_cherry_pick_head());
361 return;
364 if (show_hint) {
365 if (opts->no_commit)
366 advise(_("after resolving the conflicts, mark the corrected paths\n"
367 "with 'git add <paths>' or 'git rm <paths>'"));
368 else
369 advise(_("after resolving the conflicts, mark the corrected paths\n"
370 "with 'git add <paths>' or 'git rm <paths>'\n"
371 "and commit the result with 'git commit'"));
375 static int write_message(const void *buf, size_t len, const char *filename,
376 int append_eol)
378 struct lock_file msg_file = LOCK_INIT;
380 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
381 if (msg_fd < 0)
382 return error_errno(_("could not lock '%s'"), filename);
383 if (write_in_full(msg_fd, buf, len) < 0) {
384 error_errno(_("could not write to '%s'"), filename);
385 rollback_lock_file(&msg_file);
386 return -1;
388 if (append_eol && write(msg_fd, "\n", 1) < 0) {
389 error_errno(_("could not write eol to '%s'"), filename);
390 rollback_lock_file(&msg_file);
391 return -1;
393 if (commit_lock_file(&msg_file) < 0)
394 return error(_("failed to finalize '%s'"), filename);
396 return 0;
400 * Reads a file that was presumably written by a shell script, i.e. with an
401 * end-of-line marker that needs to be stripped.
403 * Note that only the last end-of-line marker is stripped, consistent with the
404 * behavior of "$(cat path)" in a shell script.
406 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
408 static int read_oneliner(struct strbuf *buf,
409 const char *path, int skip_if_empty)
411 int orig_len = buf->len;
413 if (!file_exists(path))
414 return 0;
416 if (strbuf_read_file(buf, path, 0) < 0) {
417 warning_errno(_("could not read '%s'"), path);
418 return 0;
421 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
422 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
423 --buf->len;
424 buf->buf[buf->len] = '\0';
427 if (skip_if_empty && buf->len == orig_len)
428 return 0;
430 return 1;
433 static struct tree *empty_tree(void)
435 return lookup_tree(the_hash_algo->empty_tree);
438 static int error_dirty_index(struct replay_opts *opts)
440 if (read_cache_unmerged())
441 return error_resolve_conflict(_(action_name(opts)));
443 error(_("your local changes would be overwritten by %s."),
444 _(action_name(opts)));
446 if (advice_commit_before_merge)
447 advise(_("commit your changes or stash them to proceed."));
448 return -1;
451 static void update_abort_safety_file(void)
453 struct object_id head;
455 /* Do nothing on a single-pick */
456 if (!file_exists(git_path_seq_dir()))
457 return;
459 if (!get_oid("HEAD", &head))
460 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
461 else
462 write_file(git_path_abort_safety_file(), "%s", "");
465 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
466 int unborn, struct replay_opts *opts)
468 struct ref_transaction *transaction;
469 struct strbuf sb = STRBUF_INIT;
470 struct strbuf err = STRBUF_INIT;
472 read_cache();
473 if (checkout_fast_forward(from, to, 1))
474 return -1; /* the callee should have complained already */
476 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
478 transaction = ref_transaction_begin(&err);
479 if (!transaction ||
480 ref_transaction_update(transaction, "HEAD",
481 to, unborn && !is_rebase_i(opts) ?
482 &null_oid : from,
483 0, sb.buf, &err) ||
484 ref_transaction_commit(transaction, &err)) {
485 ref_transaction_free(transaction);
486 error("%s", err.buf);
487 strbuf_release(&sb);
488 strbuf_release(&err);
489 return -1;
492 strbuf_release(&sb);
493 strbuf_release(&err);
494 ref_transaction_free(transaction);
495 update_abort_safety_file();
496 return 0;
499 void append_conflicts_hint(struct strbuf *msgbuf)
501 int i;
503 strbuf_addch(msgbuf, '\n');
504 strbuf_commented_addf(msgbuf, "Conflicts:\n");
505 for (i = 0; i < active_nr;) {
506 const struct cache_entry *ce = active_cache[i++];
507 if (ce_stage(ce)) {
508 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
509 while (i < active_nr && !strcmp(ce->name,
510 active_cache[i]->name))
511 i++;
516 static int do_recursive_merge(struct commit *base, struct commit *next,
517 const char *base_label, const char *next_label,
518 struct object_id *head, struct strbuf *msgbuf,
519 struct replay_opts *opts)
521 struct merge_options o;
522 struct tree *result, *next_tree, *base_tree, *head_tree;
523 int clean;
524 char **xopt;
525 struct lock_file index_lock = LOCK_INIT;
527 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
528 return -1;
530 read_cache();
532 init_merge_options(&o);
533 o.ancestor = base ? base_label : "(empty tree)";
534 o.branch1 = "HEAD";
535 o.branch2 = next ? next_label : "(empty tree)";
536 if (is_rebase_i(opts))
537 o.buffer_output = 2;
538 o.show_rename_progress = 1;
540 head_tree = parse_tree_indirect(head);
541 next_tree = next ? get_commit_tree(next) : empty_tree();
542 base_tree = base ? get_commit_tree(base) : empty_tree();
544 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
545 parse_merge_opt(&o, *xopt);
547 clean = merge_trees(&o,
548 head_tree,
549 next_tree, base_tree, &result);
550 if (is_rebase_i(opts) && clean <= 0)
551 fputs(o.obuf.buf, stdout);
552 strbuf_release(&o.obuf);
553 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
554 if (clean < 0) {
555 rollback_lock_file(&index_lock);
556 return clean;
559 if (write_locked_index(&the_index, &index_lock,
560 COMMIT_LOCK | SKIP_IF_UNCHANGED))
562 * TRANSLATORS: %s will be "revert", "cherry-pick" or
563 * "rebase -i".
565 return error(_("%s: Unable to write new index file"),
566 _(action_name(opts)));
568 if (!clean)
569 append_conflicts_hint(msgbuf);
571 return !clean;
574 static struct object_id *get_cache_tree_oid(void)
576 if (!active_cache_tree)
577 active_cache_tree = cache_tree();
579 if (!cache_tree_fully_valid(active_cache_tree))
580 if (cache_tree_update(&the_index, 0)) {
581 error(_("unable to update cache tree"));
582 return NULL;
585 return &active_cache_tree->oid;
588 static int is_index_unchanged(void)
590 struct object_id head_oid, *cache_tree_oid;
591 struct commit *head_commit;
593 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
594 return error(_("could not resolve HEAD commit"));
596 head_commit = lookup_commit(&head_oid);
599 * If head_commit is NULL, check_commit, called from
600 * lookup_commit, would have indicated that head_commit is not
601 * a commit object already. parse_commit() will return failure
602 * without further complaints in such a case. Otherwise, if
603 * the commit is invalid, parse_commit() will complain. So
604 * there is nothing for us to say here. Just return failure.
606 if (parse_commit(head_commit))
607 return -1;
609 if (!(cache_tree_oid = get_cache_tree_oid()))
610 return -1;
612 return !oidcmp(cache_tree_oid, get_commit_tree_oid(head_commit));
615 static int write_author_script(const char *message)
617 struct strbuf buf = STRBUF_INIT;
618 const char *eol;
619 int res;
621 for (;;)
622 if (!*message || starts_with(message, "\n")) {
623 missing_author:
624 /* Missing 'author' line? */
625 unlink(rebase_path_author_script());
626 return 0;
627 } else if (skip_prefix(message, "author ", &message))
628 break;
629 else if ((eol = strchr(message, '\n')))
630 message = eol + 1;
631 else
632 goto missing_author;
634 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
635 while (*message && *message != '\n' && *message != '\r')
636 if (skip_prefix(message, " <", &message))
637 break;
638 else if (*message != '\'')
639 strbuf_addch(&buf, *(message++));
640 else
641 strbuf_addf(&buf, "'\\\\%c'", *(message++));
642 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
643 while (*message && *message != '\n' && *message != '\r')
644 if (skip_prefix(message, "> ", &message))
645 break;
646 else if (*message != '\'')
647 strbuf_addch(&buf, *(message++));
648 else
649 strbuf_addf(&buf, "'\\\\%c'", *(message++));
650 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
651 while (*message && *message != '\n' && *message != '\r')
652 if (*message != '\'')
653 strbuf_addch(&buf, *(message++));
654 else
655 strbuf_addf(&buf, "'\\\\%c'", *(message++));
656 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
657 strbuf_release(&buf);
658 return res;
662 * Read a list of environment variable assignments (such as the author-script
663 * file) into an environment block. Returns -1 on error, 0 otherwise.
665 static int read_env_script(struct argv_array *env)
667 struct strbuf script = STRBUF_INIT;
668 int i, count = 0;
669 char *p, *p2;
671 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
672 return -1;
674 for (p = script.buf; *p; p++)
675 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
676 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
677 else if (*p == '\'')
678 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
679 else if (*p == '\n') {
680 *p = '\0';
681 count++;
684 for (i = 0, p = script.buf; i < count; i++) {
685 argv_array_push(env, p);
686 p += strlen(p) + 1;
689 return 0;
692 static char *get_author(const char *message)
694 size_t len;
695 const char *a;
697 a = find_commit_header(message, "author", &len);
698 if (a)
699 return xmemdupz(a, len);
701 return NULL;
704 /* Read author-script and return an ident line (author <email> timestamp) */
705 static const char *read_author_ident(struct strbuf *buf)
707 const char *keys[] = {
708 "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
710 char *in, *out, *eol;
711 int i = 0, len;
713 if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
714 return NULL;
716 /* dequote values and construct ident line in-place */
717 for (in = out = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
718 if (!skip_prefix(in, keys[i], (const char **)&in)) {
719 warning("could not parse '%s' (looking for '%s'",
720 rebase_path_author_script(), keys[i]);
721 return NULL;
724 eol = strchrnul(in, '\n');
725 *eol = '\0';
726 sq_dequote(in);
727 len = strlen(in);
729 if (i > 0) /* separate values by spaces */
730 *(out++) = ' ';
731 if (i == 1) /* email needs to be surrounded by <...> */
732 *(out++) = '<';
733 memmove(out, in, len);
734 out += len;
735 if (i == 1) /* email needs to be surrounded by <...> */
736 *(out++) = '>';
737 in = eol + 1;
740 if (i < 3) {
741 warning("could not parse '%s' (looking for '%s')",
742 rebase_path_author_script(), keys[i]);
743 return NULL;
746 buf->len = out - buf->buf;
747 return buf->buf;
750 static const char staged_changes_advice[] =
751 N_("you have staged changes in your working tree\n"
752 "If these changes are meant to be squashed into the previous commit, run:\n"
753 "\n"
754 " git commit --amend %s\n"
755 "\n"
756 "If they are meant to go into a new commit, run:\n"
757 "\n"
758 " git commit %s\n"
759 "\n"
760 "In both cases, once you're done, continue with:\n"
761 "\n"
762 " git rebase --continue\n");
764 #define ALLOW_EMPTY (1<<0)
765 #define EDIT_MSG (1<<1)
766 #define AMEND_MSG (1<<2)
767 #define CLEANUP_MSG (1<<3)
768 #define VERIFY_MSG (1<<4)
769 #define CREATE_ROOT_COMMIT (1<<5)
772 * If we are cherry-pick, and if the merge did not result in
773 * hand-editing, we will hit this commit and inherit the original
774 * author date and name.
776 * If we are revert, or if our cherry-pick results in a hand merge,
777 * we had better say that the current user is responsible for that.
779 * An exception is when run_git_commit() is called during an
780 * interactive rebase: in that case, we will want to retain the
781 * author metadata.
783 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
784 unsigned int flags)
786 struct child_process cmd = CHILD_PROCESS_INIT;
787 const char *value;
789 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
790 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
791 const char *author = is_rebase_i(opts) ?
792 read_author_ident(&script) : NULL;
793 struct object_id root_commit, *cache_tree_oid;
794 int res = 0;
796 if (!defmsg)
797 BUG("root commit without message");
799 if (!(cache_tree_oid = get_cache_tree_oid()))
800 res = -1;
802 if (!res)
803 res = strbuf_read_file(&msg, defmsg, 0);
805 if (res <= 0)
806 res = error_errno(_("could not read '%s'"), defmsg);
807 else
808 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
809 NULL, &root_commit, author,
810 opts->gpg_sign);
812 strbuf_release(&msg);
813 strbuf_release(&script);
814 if (!res) {
815 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
816 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
817 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
818 UPDATE_REFS_MSG_ON_ERR);
820 return res < 0 ? error(_("writing root commit")) : 0;
823 cmd.git_cmd = 1;
825 if (is_rebase_i(opts)) {
826 if (!(flags & EDIT_MSG)) {
827 cmd.stdout_to_stderr = 1;
828 cmd.err = -1;
831 if (read_env_script(&cmd.env_array)) {
832 const char *gpg_opt = gpg_sign_opt_quoted(opts);
834 return error(_(staged_changes_advice),
835 gpg_opt, gpg_opt);
839 argv_array_push(&cmd.args, "commit");
841 if (!(flags & VERIFY_MSG))
842 argv_array_push(&cmd.args, "-n");
843 if ((flags & AMEND_MSG))
844 argv_array_push(&cmd.args, "--amend");
845 if (opts->gpg_sign)
846 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
847 if (defmsg)
848 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
849 else if (!(flags & EDIT_MSG))
850 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
851 if ((flags & CLEANUP_MSG))
852 argv_array_push(&cmd.args, "--cleanup=strip");
853 if ((flags & EDIT_MSG))
854 argv_array_push(&cmd.args, "-e");
855 else if (!(flags & CLEANUP_MSG) &&
856 !opts->signoff && !opts->record_origin &&
857 git_config_get_value("commit.cleanup", &value))
858 argv_array_push(&cmd.args, "--cleanup=verbatim");
860 if ((flags & ALLOW_EMPTY))
861 argv_array_push(&cmd.args, "--allow-empty");
863 if (opts->allow_empty_message)
864 argv_array_push(&cmd.args, "--allow-empty-message");
866 if (cmd.err == -1) {
867 /* hide stderr on success */
868 struct strbuf buf = STRBUF_INIT;
869 int rc = pipe_command(&cmd,
870 NULL, 0,
871 /* stdout is already redirected */
872 NULL, 0,
873 &buf, 0);
874 if (rc)
875 fputs(buf.buf, stderr);
876 strbuf_release(&buf);
877 return rc;
880 return run_command(&cmd);
883 static int rest_is_empty(const struct strbuf *sb, int start)
885 int i, eol;
886 const char *nl;
888 /* Check if the rest is just whitespace and Signed-off-by's. */
889 for (i = start; i < sb->len; i++) {
890 nl = memchr(sb->buf + i, '\n', sb->len - i);
891 if (nl)
892 eol = nl - sb->buf;
893 else
894 eol = sb->len;
896 if (strlen(sign_off_header) <= eol - i &&
897 starts_with(sb->buf + i, sign_off_header)) {
898 i = eol;
899 continue;
901 while (i < eol)
902 if (!isspace(sb->buf[i++]))
903 return 0;
906 return 1;
910 * Find out if the message in the strbuf contains only whitespace and
911 * Signed-off-by lines.
913 int message_is_empty(const struct strbuf *sb,
914 enum commit_msg_cleanup_mode cleanup_mode)
916 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
917 return 0;
918 return rest_is_empty(sb, 0);
922 * See if the user edited the message in the editor or left what
923 * was in the template intact
925 int template_untouched(const struct strbuf *sb, const char *template_file,
926 enum commit_msg_cleanup_mode cleanup_mode)
928 struct strbuf tmpl = STRBUF_INIT;
929 const char *start;
931 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
932 return 0;
934 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
935 return 0;
937 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
938 if (!skip_prefix(sb->buf, tmpl.buf, &start))
939 start = sb->buf;
940 strbuf_release(&tmpl);
941 return rest_is_empty(sb, start - sb->buf);
944 int update_head_with_reflog(const struct commit *old_head,
945 const struct object_id *new_head,
946 const char *action, const struct strbuf *msg,
947 struct strbuf *err)
949 struct ref_transaction *transaction;
950 struct strbuf sb = STRBUF_INIT;
951 const char *nl;
952 int ret = 0;
954 if (action) {
955 strbuf_addstr(&sb, action);
956 strbuf_addstr(&sb, ": ");
959 nl = strchr(msg->buf, '\n');
960 if (nl) {
961 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
962 } else {
963 strbuf_addbuf(&sb, msg);
964 strbuf_addch(&sb, '\n');
967 transaction = ref_transaction_begin(err);
968 if (!transaction ||
969 ref_transaction_update(transaction, "HEAD", new_head,
970 old_head ? &old_head->object.oid : &null_oid,
971 0, sb.buf, err) ||
972 ref_transaction_commit(transaction, err)) {
973 ret = -1;
975 ref_transaction_free(transaction);
976 strbuf_release(&sb);
978 return ret;
981 static int run_rewrite_hook(const struct object_id *oldoid,
982 const struct object_id *newoid)
984 struct child_process proc = CHILD_PROCESS_INIT;
985 const char *argv[3];
986 int code;
987 struct strbuf sb = STRBUF_INIT;
989 argv[0] = find_hook("post-rewrite");
990 if (!argv[0])
991 return 0;
993 argv[1] = "amend";
994 argv[2] = NULL;
996 proc.argv = argv;
997 proc.in = -1;
998 proc.stdout_to_stderr = 1;
1000 code = start_command(&proc);
1001 if (code)
1002 return code;
1003 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1004 sigchain_push(SIGPIPE, SIG_IGN);
1005 write_in_full(proc.in, sb.buf, sb.len);
1006 close(proc.in);
1007 strbuf_release(&sb);
1008 sigchain_pop(SIGPIPE);
1009 return finish_command(&proc);
1012 void commit_post_rewrite(const struct commit *old_head,
1013 const struct object_id *new_head)
1015 struct notes_rewrite_cfg *cfg;
1017 cfg = init_copy_notes_for_rewrite("amend");
1018 if (cfg) {
1019 /* we are amending, so old_head is not NULL */
1020 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1021 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1023 run_rewrite_hook(&old_head->object.oid, new_head);
1026 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1028 struct argv_array hook_env = ARGV_ARRAY_INIT;
1029 int ret;
1030 const char *name;
1032 name = git_path_commit_editmsg();
1033 if (write_message(msg->buf, msg->len, name, 0))
1034 return -1;
1036 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1037 argv_array_push(&hook_env, "GIT_EDITOR=:");
1038 if (commit)
1039 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1040 "commit", commit, NULL);
1041 else
1042 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1043 "message", NULL);
1044 if (ret)
1045 ret = error(_("'prepare-commit-msg' hook failed"));
1046 argv_array_clear(&hook_env);
1048 return ret;
1051 static const char implicit_ident_advice_noconfig[] =
1052 N_("Your name and email address were configured automatically based\n"
1053 "on your username and hostname. Please check that they are accurate.\n"
1054 "You can suppress this message by setting them explicitly. Run the\n"
1055 "following command and follow the instructions in your editor to edit\n"
1056 "your configuration file:\n"
1057 "\n"
1058 " git config --global --edit\n"
1059 "\n"
1060 "After doing this, you may fix the identity used for this commit with:\n"
1061 "\n"
1062 " git commit --amend --reset-author\n");
1064 static const char implicit_ident_advice_config[] =
1065 N_("Your name and email address were configured automatically based\n"
1066 "on your username and hostname. Please check that they are accurate.\n"
1067 "You can suppress this message by setting them explicitly:\n"
1068 "\n"
1069 " git config --global user.name \"Your Name\"\n"
1070 " git config --global user.email you@example.com\n"
1071 "\n"
1072 "After doing this, you may fix the identity used for this commit with:\n"
1073 "\n"
1074 " git commit --amend --reset-author\n");
1076 static const char *implicit_ident_advice(void)
1078 char *user_config = expand_user_path("~/.gitconfig", 0);
1079 char *xdg_config = xdg_config_home("config");
1080 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1082 free(user_config);
1083 free(xdg_config);
1085 if (config_exists)
1086 return _(implicit_ident_advice_config);
1087 else
1088 return _(implicit_ident_advice_noconfig);
1092 void print_commit_summary(const char *prefix, const struct object_id *oid,
1093 unsigned int flags)
1095 struct rev_info rev;
1096 struct commit *commit;
1097 struct strbuf format = STRBUF_INIT;
1098 const char *head;
1099 struct pretty_print_context pctx = {0};
1100 struct strbuf author_ident = STRBUF_INIT;
1101 struct strbuf committer_ident = STRBUF_INIT;
1103 commit = lookup_commit(oid);
1104 if (!commit)
1105 die(_("couldn't look up newly created commit"));
1106 if (parse_commit(commit))
1107 die(_("could not parse newly created commit"));
1109 strbuf_addstr(&format, "format:%h] %s");
1111 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1112 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1113 if (strbuf_cmp(&author_ident, &committer_ident)) {
1114 strbuf_addstr(&format, "\n Author: ");
1115 strbuf_addbuf_percentquote(&format, &author_ident);
1117 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1118 struct strbuf date = STRBUF_INIT;
1120 format_commit_message(commit, "%ad", &date, &pctx);
1121 strbuf_addstr(&format, "\n Date: ");
1122 strbuf_addbuf_percentquote(&format, &date);
1123 strbuf_release(&date);
1125 if (!committer_ident_sufficiently_given()) {
1126 strbuf_addstr(&format, "\n Committer: ");
1127 strbuf_addbuf_percentquote(&format, &committer_ident);
1128 if (advice_implicit_identity) {
1129 strbuf_addch(&format, '\n');
1130 strbuf_addstr(&format, implicit_ident_advice());
1133 strbuf_release(&author_ident);
1134 strbuf_release(&committer_ident);
1136 init_revisions(&rev, prefix);
1137 setup_revisions(0, NULL, &rev, NULL);
1139 rev.diff = 1;
1140 rev.diffopt.output_format =
1141 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1143 rev.verbose_header = 1;
1144 rev.show_root_diff = 1;
1145 get_commit_format(format.buf, &rev);
1146 rev.always_show_header = 0;
1147 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1148 rev.diffopt.break_opt = 0;
1149 diff_setup_done(&rev.diffopt);
1151 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1152 if (!head)
1153 die_errno(_("unable to resolve HEAD after creating commit"));
1154 if (!strcmp(head, "HEAD"))
1155 head = _("detached HEAD");
1156 else
1157 skip_prefix(head, "refs/heads/", &head);
1158 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1159 _(" (root-commit)") : "");
1161 if (!log_tree_commit(&rev, commit)) {
1162 rev.always_show_header = 1;
1163 rev.use_terminator = 1;
1164 log_tree_commit(&rev, commit);
1167 strbuf_release(&format);
1170 static int parse_head(struct commit **head)
1172 struct commit *current_head;
1173 struct object_id oid;
1175 if (get_oid("HEAD", &oid)) {
1176 current_head = NULL;
1177 } else {
1178 current_head = lookup_commit_reference(&oid);
1179 if (!current_head)
1180 return error(_("could not parse HEAD"));
1181 if (oidcmp(&oid, &current_head->object.oid)) {
1182 warning(_("HEAD %s is not a commit!"),
1183 oid_to_hex(&oid));
1185 if (parse_commit(current_head))
1186 return error(_("could not parse HEAD commit"));
1188 *head = current_head;
1190 return 0;
1194 * Try to commit without forking 'git commit'. In some cases we need
1195 * to run 'git commit' to display an error message
1197 * Returns:
1198 * -1 - error unable to commit
1199 * 0 - success
1200 * 1 - run 'git commit'
1202 static int try_to_commit(struct strbuf *msg, const char *author,
1203 struct replay_opts *opts, unsigned int flags,
1204 struct object_id *oid)
1206 struct object_id tree;
1207 struct commit *current_head;
1208 struct commit_list *parents = NULL;
1209 struct commit_extra_header *extra = NULL;
1210 struct strbuf err = STRBUF_INIT;
1211 struct strbuf commit_msg = STRBUF_INIT;
1212 char *amend_author = NULL;
1213 const char *hook_commit = NULL;
1214 enum commit_msg_cleanup_mode cleanup;
1215 int res = 0;
1217 if (parse_head(&current_head))
1218 return -1;
1220 if (flags & AMEND_MSG) {
1221 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1222 const char *out_enc = get_commit_output_encoding();
1223 const char *message = logmsg_reencode(current_head, NULL,
1224 out_enc);
1226 if (!msg) {
1227 const char *orig_message = NULL;
1229 find_commit_subject(message, &orig_message);
1230 msg = &commit_msg;
1231 strbuf_addstr(msg, orig_message);
1232 hook_commit = "HEAD";
1234 author = amend_author = get_author(message);
1235 unuse_commit_buffer(current_head, message);
1236 if (!author) {
1237 res = error(_("unable to parse commit author"));
1238 goto out;
1240 parents = copy_commit_list(current_head->parents);
1241 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1242 } else if (current_head) {
1243 commit_list_insert(current_head, &parents);
1246 if (write_cache_as_tree(&tree, 0, NULL)) {
1247 res = error(_("git write-tree failed to write a tree"));
1248 goto out;
1251 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1252 get_commit_tree_oid(current_head) :
1253 the_hash_algo->empty_tree, &tree)) {
1254 res = 1; /* run 'git commit' to display error message */
1255 goto out;
1258 if (find_hook("prepare-commit-msg")) {
1259 res = run_prepare_commit_msg_hook(msg, hook_commit);
1260 if (res)
1261 goto out;
1262 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1263 2048) < 0) {
1264 res = error_errno(_("unable to read commit message "
1265 "from '%s'"),
1266 git_path_commit_editmsg());
1267 goto out;
1269 msg = &commit_msg;
1272 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1273 opts->default_msg_cleanup;
1275 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1276 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1277 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1278 res = 1; /* run 'git commit' to display error message */
1279 goto out;
1282 reset_ident_date();
1284 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1285 oid, author, opts->gpg_sign, extra)) {
1286 res = error(_("failed to write commit object"));
1287 goto out;
1290 if (update_head_with_reflog(current_head, oid,
1291 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1292 res = error("%s", err.buf);
1293 goto out;
1296 if (flags & AMEND_MSG)
1297 commit_post_rewrite(current_head, oid);
1299 out:
1300 free_commit_extra_headers(extra);
1301 strbuf_release(&err);
1302 strbuf_release(&commit_msg);
1303 free(amend_author);
1305 return res;
1308 static int do_commit(const char *msg_file, const char *author,
1309 struct replay_opts *opts, unsigned int flags)
1311 int res = 1;
1313 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1314 !(flags & CREATE_ROOT_COMMIT)) {
1315 struct object_id oid;
1316 struct strbuf sb = STRBUF_INIT;
1318 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1319 return error_errno(_("unable to read commit message "
1320 "from '%s'"),
1321 msg_file);
1323 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1324 &oid);
1325 strbuf_release(&sb);
1326 if (!res) {
1327 unlink(git_path_cherry_pick_head());
1328 unlink(git_path_merge_msg());
1329 if (!is_rebase_i(opts))
1330 print_commit_summary(NULL, &oid,
1331 SUMMARY_SHOW_AUTHOR_DATE);
1332 return res;
1335 if (res == 1)
1336 return run_git_commit(msg_file, opts, flags);
1338 return res;
1341 static int is_original_commit_empty(struct commit *commit)
1343 const struct object_id *ptree_oid;
1345 if (parse_commit(commit))
1346 return error(_("could not parse commit %s"),
1347 oid_to_hex(&commit->object.oid));
1348 if (commit->parents) {
1349 struct commit *parent = commit->parents->item;
1350 if (parse_commit(parent))
1351 return error(_("could not parse parent commit %s"),
1352 oid_to_hex(&parent->object.oid));
1353 ptree_oid = get_commit_tree_oid(parent);
1354 } else {
1355 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1358 return !oidcmp(ptree_oid, get_commit_tree_oid(commit));
1362 * Do we run "git commit" with "--allow-empty"?
1364 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1366 int index_unchanged, empty_commit;
1369 * Three cases:
1371 * (1) we do not allow empty at all and error out.
1373 * (2) we allow ones that were initially empty, but
1374 * forbid the ones that become empty;
1376 * (3) we allow both.
1378 if (!opts->allow_empty)
1379 return 0; /* let "git commit" barf as necessary */
1381 index_unchanged = is_index_unchanged();
1382 if (index_unchanged < 0)
1383 return index_unchanged;
1384 if (!index_unchanged)
1385 return 0; /* we do not have to say --allow-empty */
1387 if (opts->keep_redundant_commits)
1388 return 1;
1390 empty_commit = is_original_commit_empty(commit);
1391 if (empty_commit < 0)
1392 return empty_commit;
1393 if (!empty_commit)
1394 return 0;
1395 else
1396 return 1;
1400 * Note that ordering matters in this enum. Not only must it match the mapping
1401 * below, it is also divided into several sections that matter. When adding
1402 * new commands, make sure you add it in the right section.
1404 enum todo_command {
1405 /* commands that handle commits */
1406 TODO_PICK = 0,
1407 TODO_REVERT,
1408 TODO_EDIT,
1409 TODO_REWORD,
1410 TODO_FIXUP,
1411 TODO_SQUASH,
1412 /* commands that do something else than handling a single commit */
1413 TODO_EXEC,
1414 TODO_LABEL,
1415 TODO_RESET,
1416 TODO_MERGE,
1417 /* commands that do nothing but are counted for reporting progress */
1418 TODO_NOOP,
1419 TODO_DROP,
1420 /* comments (not counted for reporting progress) */
1421 TODO_COMMENT
1424 static struct {
1425 char c;
1426 const char *str;
1427 } todo_command_info[] = {
1428 { 'p', "pick" },
1429 { 0, "revert" },
1430 { 'e', "edit" },
1431 { 'r', "reword" },
1432 { 'f', "fixup" },
1433 { 's', "squash" },
1434 { 'x', "exec" },
1435 { 'l', "label" },
1436 { 't', "reset" },
1437 { 'm', "merge" },
1438 { 0, "noop" },
1439 { 'd', "drop" },
1440 { 0, NULL }
1443 static const char *command_to_string(const enum todo_command command)
1445 if (command < TODO_COMMENT)
1446 return todo_command_info[command].str;
1447 die("Unknown command: %d", command);
1450 static char command_to_char(const enum todo_command command)
1452 if (command < TODO_COMMENT && todo_command_info[command].c)
1453 return todo_command_info[command].c;
1454 return comment_line_char;
1457 static int is_noop(const enum todo_command command)
1459 return TODO_NOOP <= command;
1462 static int is_fixup(enum todo_command command)
1464 return command == TODO_FIXUP || command == TODO_SQUASH;
1467 /* Does this command create a (non-merge) commit? */
1468 static int is_pick_or_similar(enum todo_command command)
1470 switch (command) {
1471 case TODO_PICK:
1472 case TODO_REVERT:
1473 case TODO_EDIT:
1474 case TODO_REWORD:
1475 case TODO_FIXUP:
1476 case TODO_SQUASH:
1477 return 1;
1478 default:
1479 return 0;
1483 static int update_squash_messages(enum todo_command command,
1484 struct commit *commit, struct replay_opts *opts)
1486 struct strbuf buf = STRBUF_INIT;
1487 int res;
1488 const char *message, *body;
1490 if (opts->current_fixup_count > 0) {
1491 struct strbuf header = STRBUF_INIT;
1492 char *eol;
1494 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1495 return error(_("could not read '%s'"),
1496 rebase_path_squash_msg());
1498 eol = buf.buf[0] != comment_line_char ?
1499 buf.buf : strchrnul(buf.buf, '\n');
1501 strbuf_addf(&header, "%c ", comment_line_char);
1502 strbuf_addf(&header, _("This is a combination of %d commits."),
1503 opts->current_fixup_count + 2);
1504 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1505 strbuf_release(&header);
1506 } else {
1507 struct object_id head;
1508 struct commit *head_commit;
1509 const char *head_message, *body;
1511 if (get_oid("HEAD", &head))
1512 return error(_("need a HEAD to fixup"));
1513 if (!(head_commit = lookup_commit_reference(&head)))
1514 return error(_("could not read HEAD"));
1515 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1516 return error(_("could not read HEAD's commit message"));
1518 find_commit_subject(head_message, &body);
1519 if (write_message(body, strlen(body),
1520 rebase_path_fixup_msg(), 0)) {
1521 unuse_commit_buffer(head_commit, head_message);
1522 return error(_("cannot write '%s'"),
1523 rebase_path_fixup_msg());
1526 strbuf_addf(&buf, "%c ", comment_line_char);
1527 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1528 strbuf_addf(&buf, "\n%c ", comment_line_char);
1529 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1530 strbuf_addstr(&buf, "\n\n");
1531 strbuf_addstr(&buf, body);
1533 unuse_commit_buffer(head_commit, head_message);
1536 if (!(message = get_commit_buffer(commit, NULL)))
1537 return error(_("could not read commit message of %s"),
1538 oid_to_hex(&commit->object.oid));
1539 find_commit_subject(message, &body);
1541 if (command == TODO_SQUASH) {
1542 unlink(rebase_path_fixup_msg());
1543 strbuf_addf(&buf, "\n%c ", comment_line_char);
1544 strbuf_addf(&buf, _("This is the commit message #%d:"),
1545 ++opts->current_fixup_count);
1546 strbuf_addstr(&buf, "\n\n");
1547 strbuf_addstr(&buf, body);
1548 } else if (command == TODO_FIXUP) {
1549 strbuf_addf(&buf, "\n%c ", comment_line_char);
1550 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1551 ++opts->current_fixup_count);
1552 strbuf_addstr(&buf, "\n\n");
1553 strbuf_add_commented_lines(&buf, body, strlen(body));
1554 } else
1555 return error(_("unknown command: %d"), command);
1556 unuse_commit_buffer(commit, message);
1558 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1559 strbuf_release(&buf);
1561 if (!res) {
1562 strbuf_addf(&opts->current_fixups, "%s%s %s",
1563 opts->current_fixups.len ? "\n" : "",
1564 command_to_string(command),
1565 oid_to_hex(&commit->object.oid));
1566 res = write_message(opts->current_fixups.buf,
1567 opts->current_fixups.len,
1568 rebase_path_current_fixups(), 0);
1571 return res;
1574 static void flush_rewritten_pending(void) {
1575 struct strbuf buf = STRBUF_INIT;
1576 struct object_id newoid;
1577 FILE *out;
1579 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1580 !get_oid("HEAD", &newoid) &&
1581 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1582 char *bol = buf.buf, *eol;
1584 while (*bol) {
1585 eol = strchrnul(bol, '\n');
1586 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1587 bol, oid_to_hex(&newoid));
1588 if (!*eol)
1589 break;
1590 bol = eol + 1;
1592 fclose(out);
1593 unlink(rebase_path_rewritten_pending());
1595 strbuf_release(&buf);
1598 static void record_in_rewritten(struct object_id *oid,
1599 enum todo_command next_command) {
1600 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1602 if (!out)
1603 return;
1605 fprintf(out, "%s\n", oid_to_hex(oid));
1606 fclose(out);
1608 if (!is_fixup(next_command))
1609 flush_rewritten_pending();
1612 static int do_pick_commit(enum todo_command command, struct commit *commit,
1613 struct replay_opts *opts, int final_fixup)
1615 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1616 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1617 struct object_id head;
1618 struct commit *base, *next, *parent;
1619 const char *base_label, *next_label;
1620 char *author = NULL;
1621 struct commit_message msg = { NULL, NULL, NULL, NULL };
1622 struct strbuf msgbuf = STRBUF_INIT;
1623 int res, unborn = 0, allow;
1625 if (opts->no_commit) {
1627 * We do not intend to commit immediately. We just want to
1628 * merge the differences in, so let's compute the tree
1629 * that represents the "current" state for merge-recursive
1630 * to work on.
1632 if (write_cache_as_tree(&head, 0, NULL))
1633 return error(_("your index file is unmerged."));
1634 } else {
1635 unborn = get_oid("HEAD", &head);
1636 /* Do we want to generate a root commit? */
1637 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1638 !oidcmp(&head, &opts->squash_onto)) {
1639 if (is_fixup(command))
1640 return error(_("cannot fixup root commit"));
1641 flags |= CREATE_ROOT_COMMIT;
1642 unborn = 1;
1643 } else if (unborn)
1644 oidcpy(&head, the_hash_algo->empty_tree);
1645 if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
1646 NULL, 0))
1647 return error_dirty_index(opts);
1649 discard_cache();
1651 if (!commit->parents)
1652 parent = NULL;
1653 else if (commit->parents->next) {
1654 /* Reverting or cherry-picking a merge commit */
1655 int cnt;
1656 struct commit_list *p;
1658 if (!opts->mainline)
1659 return error(_("commit %s is a merge but no -m option was given."),
1660 oid_to_hex(&commit->object.oid));
1662 for (cnt = 1, p = commit->parents;
1663 cnt != opts->mainline && p;
1664 cnt++)
1665 p = p->next;
1666 if (cnt != opts->mainline || !p)
1667 return error(_("commit %s does not have parent %d"),
1668 oid_to_hex(&commit->object.oid), opts->mainline);
1669 parent = p->item;
1670 } else if (0 < opts->mainline)
1671 return error(_("mainline was specified but commit %s is not a merge."),
1672 oid_to_hex(&commit->object.oid));
1673 else
1674 parent = commit->parents->item;
1676 if (get_message(commit, &msg) != 0)
1677 return error(_("cannot get commit message for %s"),
1678 oid_to_hex(&commit->object.oid));
1680 if (opts->allow_ff && !is_fixup(command) &&
1681 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1682 (!parent && unborn))) {
1683 if (is_rebase_i(opts))
1684 write_author_script(msg.message);
1685 res = fast_forward_to(&commit->object.oid, &head, unborn,
1686 opts);
1687 if (res || command != TODO_REWORD)
1688 goto leave;
1689 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1690 msg_file = NULL;
1691 goto fast_forward_edit;
1693 if (parent && parse_commit(parent) < 0)
1694 /* TRANSLATORS: The first %s will be a "todo" command like
1695 "revert" or "pick", the second %s a SHA1. */
1696 return error(_("%s: cannot parse parent commit %s"),
1697 command_to_string(command),
1698 oid_to_hex(&parent->object.oid));
1701 * "commit" is an existing commit. We would want to apply
1702 * the difference it introduces since its first parent "prev"
1703 * on top of the current HEAD if we are cherry-pick. Or the
1704 * reverse of it if we are revert.
1707 if (command == TODO_REVERT) {
1708 base = commit;
1709 base_label = msg.label;
1710 next = parent;
1711 next_label = msg.parent_label;
1712 strbuf_addstr(&msgbuf, "Revert \"");
1713 strbuf_addstr(&msgbuf, msg.subject);
1714 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1715 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1717 if (commit->parents && commit->parents->next) {
1718 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1719 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1721 strbuf_addstr(&msgbuf, ".\n");
1722 } else {
1723 const char *p;
1725 base = parent;
1726 base_label = msg.parent_label;
1727 next = commit;
1728 next_label = msg.label;
1730 /* Append the commit log message to msgbuf. */
1731 if (find_commit_subject(msg.message, &p))
1732 strbuf_addstr(&msgbuf, p);
1734 if (opts->record_origin) {
1735 strbuf_complete_line(&msgbuf);
1736 if (!has_conforming_footer(&msgbuf, NULL, 0))
1737 strbuf_addch(&msgbuf, '\n');
1738 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1739 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1740 strbuf_addstr(&msgbuf, ")\n");
1742 if (!is_fixup(command))
1743 author = get_author(msg.message);
1746 if (command == TODO_REWORD)
1747 flags |= EDIT_MSG | VERIFY_MSG;
1748 else if (is_fixup(command)) {
1749 if (update_squash_messages(command, commit, opts))
1750 return -1;
1751 flags |= AMEND_MSG;
1752 if (!final_fixup)
1753 msg_file = rebase_path_squash_msg();
1754 else if (file_exists(rebase_path_fixup_msg())) {
1755 flags |= CLEANUP_MSG;
1756 msg_file = rebase_path_fixup_msg();
1757 } else {
1758 const char *dest = git_path_squash_msg();
1759 unlink(dest);
1760 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1761 return error(_("could not rename '%s' to '%s'"),
1762 rebase_path_squash_msg(), dest);
1763 unlink(git_path_merge_msg());
1764 msg_file = dest;
1765 flags |= EDIT_MSG;
1769 if (opts->signoff && !is_fixup(command))
1770 append_signoff(&msgbuf, 0, 0);
1772 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1773 res = -1;
1774 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1775 res = do_recursive_merge(base, next, base_label, next_label,
1776 &head, &msgbuf, opts);
1777 if (res < 0)
1778 goto leave;
1780 res |= write_message(msgbuf.buf, msgbuf.len,
1781 git_path_merge_msg(), 0);
1782 } else {
1783 struct commit_list *common = NULL;
1784 struct commit_list *remotes = NULL;
1786 res = write_message(msgbuf.buf, msgbuf.len,
1787 git_path_merge_msg(), 0);
1789 commit_list_insert(base, &common);
1790 commit_list_insert(next, &remotes);
1791 res |= try_merge_command(opts->strategy,
1792 opts->xopts_nr, (const char **)opts->xopts,
1793 common, oid_to_hex(&head), remotes);
1794 free_commit_list(common);
1795 free_commit_list(remotes);
1797 strbuf_release(&msgbuf);
1800 * If the merge was clean or if it failed due to conflict, we write
1801 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1802 * However, if the merge did not even start, then we don't want to
1803 * write it at all.
1805 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1806 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1807 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1808 res = -1;
1809 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1810 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1811 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1812 res = -1;
1814 if (res) {
1815 error(command == TODO_REVERT
1816 ? _("could not revert %s... %s")
1817 : _("could not apply %s... %s"),
1818 short_commit_name(commit), msg.subject);
1819 print_advice(res == 1, opts);
1820 rerere(opts->allow_rerere_auto);
1821 goto leave;
1824 allow = allow_empty(opts, commit);
1825 if (allow < 0) {
1826 res = allow;
1827 goto leave;
1828 } else if (allow)
1829 flags |= ALLOW_EMPTY;
1830 if (!opts->no_commit) {
1831 fast_forward_edit:
1832 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1833 res = do_commit(msg_file, author, opts, flags);
1834 else
1835 res = error(_("unable to parse commit author"));
1838 if (!res && final_fixup) {
1839 unlink(rebase_path_fixup_msg());
1840 unlink(rebase_path_squash_msg());
1841 unlink(rebase_path_current_fixups());
1842 strbuf_reset(&opts->current_fixups);
1843 opts->current_fixup_count = 0;
1846 leave:
1847 free_message(commit, &msg);
1848 free(author);
1849 update_abort_safety_file();
1851 return res;
1854 static int prepare_revs(struct replay_opts *opts)
1857 * picking (but not reverting) ranges (but not individual revisions)
1858 * should be done in reverse
1860 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1861 opts->revs->reverse ^= 1;
1863 if (prepare_revision_walk(opts->revs))
1864 return error(_("revision walk setup failed"));
1866 if (!opts->revs->commits)
1867 return error(_("empty commit set passed"));
1868 return 0;
1871 static int read_and_refresh_cache(struct replay_opts *opts)
1873 struct lock_file index_lock = LOCK_INIT;
1874 int index_fd = hold_locked_index(&index_lock, 0);
1875 if (read_index_preload(&the_index, NULL) < 0) {
1876 rollback_lock_file(&index_lock);
1877 return error(_("git %s: failed to read the index"),
1878 _(action_name(opts)));
1880 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1881 if (index_fd >= 0) {
1882 if (write_locked_index(&the_index, &index_lock,
1883 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1884 return error(_("git %s: failed to refresh the index"),
1885 _(action_name(opts)));
1888 return 0;
1891 enum todo_item_flags {
1892 TODO_EDIT_MERGE_MSG = 1
1895 struct todo_item {
1896 enum todo_command command;
1897 struct commit *commit;
1898 unsigned int flags;
1899 const char *arg;
1900 int arg_len;
1901 size_t offset_in_buf;
1904 struct todo_list {
1905 struct strbuf buf;
1906 struct todo_item *items;
1907 int nr, alloc, current;
1908 int done_nr, total_nr;
1909 struct stat_data stat;
1912 #define TODO_LIST_INIT { STRBUF_INIT }
1914 static void todo_list_release(struct todo_list *todo_list)
1916 strbuf_release(&todo_list->buf);
1917 FREE_AND_NULL(todo_list->items);
1918 todo_list->nr = todo_list->alloc = 0;
1921 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1923 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1924 return todo_list->items + todo_list->nr++;
1927 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1929 struct object_id commit_oid;
1930 char *end_of_object_name;
1931 int i, saved, status, padding;
1933 item->flags = 0;
1935 /* left-trim */
1936 bol += strspn(bol, " \t");
1938 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1939 item->command = TODO_COMMENT;
1940 item->commit = NULL;
1941 item->arg = bol;
1942 item->arg_len = eol - bol;
1943 return 0;
1946 for (i = 0; i < TODO_COMMENT; i++)
1947 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1948 item->command = i;
1949 break;
1950 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1951 bol++;
1952 item->command = i;
1953 break;
1955 if (i >= TODO_COMMENT)
1956 return -1;
1958 /* Eat up extra spaces/ tabs before object name */
1959 padding = strspn(bol, " \t");
1960 bol += padding;
1962 if (item->command == TODO_NOOP) {
1963 if (bol != eol)
1964 return error(_("%s does not accept arguments: '%s'"),
1965 command_to_string(item->command), bol);
1966 item->commit = NULL;
1967 item->arg = bol;
1968 item->arg_len = eol - bol;
1969 return 0;
1972 if (!padding)
1973 return error(_("missing arguments for %s"),
1974 command_to_string(item->command));
1976 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1977 item->command == TODO_RESET) {
1978 item->commit = NULL;
1979 item->arg = bol;
1980 item->arg_len = (int)(eol - bol);
1981 return 0;
1984 if (item->command == TODO_MERGE) {
1985 if (skip_prefix(bol, "-C", &bol))
1986 bol += strspn(bol, " \t");
1987 else if (skip_prefix(bol, "-c", &bol)) {
1988 bol += strspn(bol, " \t");
1989 item->flags |= TODO_EDIT_MERGE_MSG;
1990 } else {
1991 item->flags |= TODO_EDIT_MERGE_MSG;
1992 item->commit = NULL;
1993 item->arg = bol;
1994 item->arg_len = (int)(eol - bol);
1995 return 0;
1999 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2000 saved = *end_of_object_name;
2001 *end_of_object_name = '\0';
2002 status = get_oid(bol, &commit_oid);
2003 *end_of_object_name = saved;
2005 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2006 item->arg_len = (int)(eol - item->arg);
2008 if (status < 0)
2009 return -1;
2011 item->commit = lookup_commit_reference(&commit_oid);
2012 return !item->commit;
2015 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2017 struct todo_item *item;
2018 char *p = buf, *next_p;
2019 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2021 for (i = 1; *p; i++, p = next_p) {
2022 char *eol = strchrnul(p, '\n');
2024 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2026 if (p != eol && eol[-1] == '\r')
2027 eol--; /* strip Carriage Return */
2029 item = append_new_todo(todo_list);
2030 item->offset_in_buf = p - todo_list->buf.buf;
2031 if (parse_insn_line(item, p, eol)) {
2032 res = error(_("invalid line %d: %.*s"),
2033 i, (int)(eol - p), p);
2034 item->command = TODO_NOOP;
2037 if (fixup_okay)
2038 ; /* do nothing */
2039 else if (is_fixup(item->command))
2040 return error(_("cannot '%s' without a previous commit"),
2041 command_to_string(item->command));
2042 else if (!is_noop(item->command))
2043 fixup_okay = 1;
2046 return res;
2049 static int count_commands(struct todo_list *todo_list)
2051 int count = 0, i;
2053 for (i = 0; i < todo_list->nr; i++)
2054 if (todo_list->items[i].command != TODO_COMMENT)
2055 count++;
2057 return count;
2060 static int get_item_line_offset(struct todo_list *todo_list, int index)
2062 return index < todo_list->nr ?
2063 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2066 static const char *get_item_line(struct todo_list *todo_list, int index)
2068 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2071 static int get_item_line_length(struct todo_list *todo_list, int index)
2073 return get_item_line_offset(todo_list, index + 1)
2074 - get_item_line_offset(todo_list, index);
2077 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2079 int fd;
2080 ssize_t len;
2082 fd = open(path, O_RDONLY);
2083 if (fd < 0)
2084 return error_errno(_("could not open '%s'"), path);
2085 len = strbuf_read(sb, fd, 0);
2086 close(fd);
2087 if (len < 0)
2088 return error(_("could not read '%s'."), path);
2089 return len;
2092 static int read_populate_todo(struct todo_list *todo_list,
2093 struct replay_opts *opts)
2095 struct stat st;
2096 const char *todo_file = get_todo_path(opts);
2097 int res;
2099 strbuf_reset(&todo_list->buf);
2100 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2101 return -1;
2103 res = stat(todo_file, &st);
2104 if (res)
2105 return error(_("could not stat '%s'"), todo_file);
2106 fill_stat_data(&todo_list->stat, &st);
2108 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2109 if (res) {
2110 if (is_rebase_i(opts))
2111 return error(_("please fix this using "
2112 "'git rebase --edit-todo'."));
2113 return error(_("unusable instruction sheet: '%s'"), todo_file);
2116 if (!todo_list->nr &&
2117 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2118 return error(_("no commits parsed."));
2120 if (!is_rebase_i(opts)) {
2121 enum todo_command valid =
2122 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2123 int i;
2125 for (i = 0; i < todo_list->nr; i++)
2126 if (valid == todo_list->items[i].command)
2127 continue;
2128 else if (valid == TODO_PICK)
2129 return error(_("cannot cherry-pick during a revert."));
2130 else
2131 return error(_("cannot revert during a cherry-pick."));
2134 if (is_rebase_i(opts)) {
2135 struct todo_list done = TODO_LIST_INIT;
2136 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2138 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2139 !parse_insn_buffer(done.buf.buf, &done))
2140 todo_list->done_nr = count_commands(&done);
2141 else
2142 todo_list->done_nr = 0;
2144 todo_list->total_nr = todo_list->done_nr
2145 + count_commands(todo_list);
2146 todo_list_release(&done);
2148 if (f) {
2149 fprintf(f, "%d\n", todo_list->total_nr);
2150 fclose(f);
2154 return 0;
2157 static int git_config_string_dup(char **dest,
2158 const char *var, const char *value)
2160 if (!value)
2161 return config_error_nonbool(var);
2162 free(*dest);
2163 *dest = xstrdup(value);
2164 return 0;
2167 static int populate_opts_cb(const char *key, const char *value, void *data)
2169 struct replay_opts *opts = data;
2170 int error_flag = 1;
2172 if (!value)
2173 error_flag = 0;
2174 else if (!strcmp(key, "options.no-commit"))
2175 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2176 else if (!strcmp(key, "options.edit"))
2177 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2178 else if (!strcmp(key, "options.signoff"))
2179 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2180 else if (!strcmp(key, "options.record-origin"))
2181 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2182 else if (!strcmp(key, "options.allow-ff"))
2183 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2184 else if (!strcmp(key, "options.mainline"))
2185 opts->mainline = git_config_int(key, value);
2186 else if (!strcmp(key, "options.strategy"))
2187 git_config_string_dup(&opts->strategy, key, value);
2188 else if (!strcmp(key, "options.gpg-sign"))
2189 git_config_string_dup(&opts->gpg_sign, key, value);
2190 else if (!strcmp(key, "options.strategy-option")) {
2191 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2192 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2193 } else if (!strcmp(key, "options.allow-rerere-auto"))
2194 opts->allow_rerere_auto =
2195 git_config_bool_or_int(key, value, &error_flag) ?
2196 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2197 else
2198 return error(_("invalid key: %s"), key);
2200 if (!error_flag)
2201 return error(_("invalid value for %s: %s"), key, value);
2203 return 0;
2206 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2208 int i;
2210 strbuf_reset(buf);
2211 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2212 return;
2213 opts->strategy = strbuf_detach(buf, NULL);
2214 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2215 return;
2217 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2218 for (i = 0; i < opts->xopts_nr; i++) {
2219 const char *arg = opts->xopts[i];
2221 skip_prefix(arg, "--", &arg);
2222 opts->xopts[i] = xstrdup(arg);
2226 static int read_populate_opts(struct replay_opts *opts)
2228 if (is_rebase_i(opts)) {
2229 struct strbuf buf = STRBUF_INIT;
2231 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2232 if (!starts_with(buf.buf, "-S"))
2233 strbuf_reset(&buf);
2234 else {
2235 free(opts->gpg_sign);
2236 opts->gpg_sign = xstrdup(buf.buf + 2);
2238 strbuf_reset(&buf);
2241 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2242 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2243 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2244 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2245 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2246 strbuf_reset(&buf);
2249 if (file_exists(rebase_path_verbose()))
2250 opts->verbose = 1;
2252 if (file_exists(rebase_path_signoff())) {
2253 opts->allow_ff = 0;
2254 opts->signoff = 1;
2257 read_strategy_opts(opts, &buf);
2258 strbuf_release(&buf);
2260 if (read_oneliner(&opts->current_fixups,
2261 rebase_path_current_fixups(), 1)) {
2262 const char *p = opts->current_fixups.buf;
2263 opts->current_fixup_count = 1;
2264 while ((p = strchr(p, '\n'))) {
2265 opts->current_fixup_count++;
2266 p++;
2270 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2271 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2272 return error(_("unusable squash-onto"));
2273 opts->have_squash_onto = 1;
2276 return 0;
2279 if (!file_exists(git_path_opts_file()))
2280 return 0;
2282 * The function git_parse_source(), called from git_config_from_file(),
2283 * may die() in case of a syntactically incorrect file. We do not care
2284 * about this case, though, because we wrote that file ourselves, so we
2285 * are pretty certain that it is syntactically correct.
2287 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2288 return error(_("malformed options sheet: '%s'"),
2289 git_path_opts_file());
2290 return 0;
2293 static int walk_revs_populate_todo(struct todo_list *todo_list,
2294 struct replay_opts *opts)
2296 enum todo_command command = opts->action == REPLAY_PICK ?
2297 TODO_PICK : TODO_REVERT;
2298 const char *command_string = todo_command_info[command].str;
2299 struct commit *commit;
2301 if (prepare_revs(opts))
2302 return -1;
2304 while ((commit = get_revision(opts->revs))) {
2305 struct todo_item *item = append_new_todo(todo_list);
2306 const char *commit_buffer = get_commit_buffer(commit, NULL);
2307 const char *subject;
2308 int subject_len;
2310 item->command = command;
2311 item->commit = commit;
2312 item->arg = NULL;
2313 item->arg_len = 0;
2314 item->offset_in_buf = todo_list->buf.len;
2315 subject_len = find_commit_subject(commit_buffer, &subject);
2316 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2317 short_commit_name(commit), subject_len, subject);
2318 unuse_commit_buffer(commit, commit_buffer);
2320 return 0;
2323 static int create_seq_dir(void)
2325 if (file_exists(git_path_seq_dir())) {
2326 error(_("a cherry-pick or revert is already in progress"));
2327 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2328 return -1;
2329 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2330 return error_errno(_("could not create sequencer directory '%s'"),
2331 git_path_seq_dir());
2332 return 0;
2335 static int save_head(const char *head)
2337 struct lock_file head_lock = LOCK_INIT;
2338 struct strbuf buf = STRBUF_INIT;
2339 int fd;
2340 ssize_t written;
2342 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2343 if (fd < 0)
2344 return error_errno(_("could not lock HEAD"));
2345 strbuf_addf(&buf, "%s\n", head);
2346 written = write_in_full(fd, buf.buf, buf.len);
2347 strbuf_release(&buf);
2348 if (written < 0) {
2349 error_errno(_("could not write to '%s'"), git_path_head_file());
2350 rollback_lock_file(&head_lock);
2351 return -1;
2353 if (commit_lock_file(&head_lock) < 0)
2354 return error(_("failed to finalize '%s'"), git_path_head_file());
2355 return 0;
2358 static int rollback_is_safe(void)
2360 struct strbuf sb = STRBUF_INIT;
2361 struct object_id expected_head, actual_head;
2363 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2364 strbuf_trim(&sb);
2365 if (get_oid_hex(sb.buf, &expected_head)) {
2366 strbuf_release(&sb);
2367 die(_("could not parse %s"), git_path_abort_safety_file());
2369 strbuf_release(&sb);
2371 else if (errno == ENOENT)
2372 oidclr(&expected_head);
2373 else
2374 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2376 if (get_oid("HEAD", &actual_head))
2377 oidclr(&actual_head);
2379 return !oidcmp(&actual_head, &expected_head);
2382 static int reset_for_rollback(const struct object_id *oid)
2384 const char *argv[4]; /* reset --merge <arg> + NULL */
2386 argv[0] = "reset";
2387 argv[1] = "--merge";
2388 argv[2] = oid_to_hex(oid);
2389 argv[3] = NULL;
2390 return run_command_v_opt(argv, RUN_GIT_CMD);
2393 static int rollback_single_pick(void)
2395 struct object_id head_oid;
2397 if (!file_exists(git_path_cherry_pick_head()) &&
2398 !file_exists(git_path_revert_head()))
2399 return error(_("no cherry-pick or revert in progress"));
2400 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2401 return error(_("cannot resolve HEAD"));
2402 if (is_null_oid(&head_oid))
2403 return error(_("cannot abort from a branch yet to be born"));
2404 return reset_for_rollback(&head_oid);
2407 int sequencer_rollback(struct replay_opts *opts)
2409 FILE *f;
2410 struct object_id oid;
2411 struct strbuf buf = STRBUF_INIT;
2412 const char *p;
2414 f = fopen(git_path_head_file(), "r");
2415 if (!f && errno == ENOENT) {
2417 * There is no multiple-cherry-pick in progress.
2418 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2419 * a single-cherry-pick in progress, abort that.
2421 return rollback_single_pick();
2423 if (!f)
2424 return error_errno(_("cannot open '%s'"), git_path_head_file());
2425 if (strbuf_getline_lf(&buf, f)) {
2426 error(_("cannot read '%s': %s"), git_path_head_file(),
2427 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2428 fclose(f);
2429 goto fail;
2431 fclose(f);
2432 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2433 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2434 git_path_head_file());
2435 goto fail;
2437 if (is_null_oid(&oid)) {
2438 error(_("cannot abort from a branch yet to be born"));
2439 goto fail;
2442 if (!rollback_is_safe()) {
2443 /* Do not error, just do not rollback */
2444 warning(_("You seem to have moved HEAD. "
2445 "Not rewinding, check your HEAD!"));
2446 } else
2447 if (reset_for_rollback(&oid))
2448 goto fail;
2449 strbuf_release(&buf);
2450 return sequencer_remove_state(opts);
2451 fail:
2452 strbuf_release(&buf);
2453 return -1;
2456 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2458 struct lock_file todo_lock = LOCK_INIT;
2459 const char *todo_path = get_todo_path(opts);
2460 int next = todo_list->current, offset, fd;
2463 * rebase -i writes "git-rebase-todo" without the currently executing
2464 * command, appending it to "done" instead.
2466 if (is_rebase_i(opts))
2467 next++;
2469 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2470 if (fd < 0)
2471 return error_errno(_("could not lock '%s'"), todo_path);
2472 offset = get_item_line_offset(todo_list, next);
2473 if (write_in_full(fd, todo_list->buf.buf + offset,
2474 todo_list->buf.len - offset) < 0)
2475 return error_errno(_("could not write to '%s'"), todo_path);
2476 if (commit_lock_file(&todo_lock) < 0)
2477 return error(_("failed to finalize '%s'"), todo_path);
2479 if (is_rebase_i(opts) && next > 0) {
2480 const char *done = rebase_path_done();
2481 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2482 int ret = 0;
2484 if (fd < 0)
2485 return 0;
2486 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2487 get_item_line_length(todo_list, next - 1))
2488 < 0)
2489 ret = error_errno(_("could not write to '%s'"), done);
2490 if (close(fd) < 0)
2491 ret = error_errno(_("failed to finalize '%s'"), done);
2492 return ret;
2494 return 0;
2497 static int save_opts(struct replay_opts *opts)
2499 const char *opts_file = git_path_opts_file();
2500 int res = 0;
2502 if (opts->no_commit)
2503 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2504 if (opts->edit)
2505 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2506 if (opts->signoff)
2507 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2508 if (opts->record_origin)
2509 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2510 if (opts->allow_ff)
2511 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2512 if (opts->mainline) {
2513 struct strbuf buf = STRBUF_INIT;
2514 strbuf_addf(&buf, "%d", opts->mainline);
2515 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2516 strbuf_release(&buf);
2518 if (opts->strategy)
2519 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2520 if (opts->gpg_sign)
2521 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2522 if (opts->xopts) {
2523 int i;
2524 for (i = 0; i < opts->xopts_nr; i++)
2525 res |= git_config_set_multivar_in_file_gently(opts_file,
2526 "options.strategy-option",
2527 opts->xopts[i], "^$", 0);
2529 if (opts->allow_rerere_auto)
2530 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2531 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2532 "true" : "false");
2533 return res;
2536 static int make_patch(struct commit *commit, struct replay_opts *opts)
2538 struct strbuf buf = STRBUF_INIT;
2539 struct rev_info log_tree_opt;
2540 const char *subject, *p;
2541 int res = 0;
2543 p = short_commit_name(commit);
2544 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2545 return -1;
2546 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2547 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2548 res |= error(_("could not update %s"), "REBASE_HEAD");
2550 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2551 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2552 init_revisions(&log_tree_opt, NULL);
2553 log_tree_opt.abbrev = 0;
2554 log_tree_opt.diff = 1;
2555 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2556 log_tree_opt.disable_stdin = 1;
2557 log_tree_opt.no_commit_id = 1;
2558 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2559 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2560 if (!log_tree_opt.diffopt.file)
2561 res |= error_errno(_("could not open '%s'"), buf.buf);
2562 else {
2563 res |= log_tree_commit(&log_tree_opt, commit);
2564 fclose(log_tree_opt.diffopt.file);
2566 strbuf_reset(&buf);
2568 strbuf_addf(&buf, "%s/message", get_dir(opts));
2569 if (!file_exists(buf.buf)) {
2570 const char *commit_buffer = get_commit_buffer(commit, NULL);
2571 find_commit_subject(commit_buffer, &subject);
2572 res |= write_message(subject, strlen(subject), buf.buf, 1);
2573 unuse_commit_buffer(commit, commit_buffer);
2575 strbuf_release(&buf);
2577 return res;
2580 static int intend_to_amend(void)
2582 struct object_id head;
2583 char *p;
2585 if (get_oid("HEAD", &head))
2586 return error(_("cannot read HEAD"));
2588 p = oid_to_hex(&head);
2589 return write_message(p, strlen(p), rebase_path_amend(), 1);
2592 static int error_with_patch(struct commit *commit,
2593 const char *subject, int subject_len,
2594 struct replay_opts *opts, int exit_code, int to_amend)
2596 if (make_patch(commit, opts))
2597 return -1;
2599 if (to_amend) {
2600 if (intend_to_amend())
2601 return -1;
2603 fprintf(stderr, "You can amend the commit now, with\n"
2604 "\n"
2605 " git commit --amend %s\n"
2606 "\n"
2607 "Once you are satisfied with your changes, run\n"
2608 "\n"
2609 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2610 } else if (exit_code)
2611 fprintf(stderr, "Could not apply %s... %.*s\n",
2612 short_commit_name(commit), subject_len, subject);
2614 return exit_code;
2617 static int error_failed_squash(struct commit *commit,
2618 struct replay_opts *opts, int subject_len, const char *subject)
2620 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2621 return error(_("could not copy '%s' to '%s'"),
2622 rebase_path_squash_msg(), rebase_path_message());
2623 unlink(git_path_merge_msg());
2624 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2625 return error(_("could not copy '%s' to '%s'"),
2626 rebase_path_message(), git_path_merge_msg());
2627 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2630 static int do_exec(const char *command_line)
2632 struct argv_array child_env = ARGV_ARRAY_INIT;
2633 const char *child_argv[] = { NULL, NULL };
2634 int dirty, status;
2636 fprintf(stderr, "Executing: %s\n", command_line);
2637 child_argv[0] = command_line;
2638 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2639 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2640 child_env.argv);
2642 /* force re-reading of the cache */
2643 if (discard_cache() < 0 || read_cache() < 0)
2644 return error(_("could not read index"));
2646 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2648 if (status) {
2649 warning(_("execution failed: %s\n%s"
2650 "You can fix the problem, and then run\n"
2651 "\n"
2652 " git rebase --continue\n"
2653 "\n"),
2654 command_line,
2655 dirty ? N_("and made changes to the index and/or the "
2656 "working tree\n") : "");
2657 if (status == 127)
2658 /* command not found */
2659 status = 1;
2660 } else if (dirty) {
2661 warning(_("execution succeeded: %s\nbut "
2662 "left changes to the index and/or the working tree\n"
2663 "Commit or stash your changes, and then run\n"
2664 "\n"
2665 " git rebase --continue\n"
2666 "\n"), command_line);
2667 status = 1;
2670 argv_array_clear(&child_env);
2672 return status;
2675 static int safe_append(const char *filename, const char *fmt, ...)
2677 va_list ap;
2678 struct lock_file lock = LOCK_INIT;
2679 int fd = hold_lock_file_for_update(&lock, filename,
2680 LOCK_REPORT_ON_ERROR);
2681 struct strbuf buf = STRBUF_INIT;
2683 if (fd < 0)
2684 return -1;
2686 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2687 error_errno(_("could not read '%s'"), filename);
2688 rollback_lock_file(&lock);
2689 return -1;
2691 strbuf_complete(&buf, '\n');
2692 va_start(ap, fmt);
2693 strbuf_vaddf(&buf, fmt, ap);
2694 va_end(ap);
2696 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2697 error_errno(_("could not write to '%s'"), filename);
2698 strbuf_release(&buf);
2699 rollback_lock_file(&lock);
2700 return -1;
2702 if (commit_lock_file(&lock) < 0) {
2703 strbuf_release(&buf);
2704 rollback_lock_file(&lock);
2705 return error(_("failed to finalize '%s'"), filename);
2708 strbuf_release(&buf);
2709 return 0;
2712 static int do_label(const char *name, int len)
2714 struct ref_store *refs = get_main_ref_store(the_repository);
2715 struct ref_transaction *transaction;
2716 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2717 struct strbuf msg = STRBUF_INIT;
2718 int ret = 0;
2719 struct object_id head_oid;
2721 if (len == 1 && *name == '#')
2722 return error("Illegal label name: '%.*s'", len, name);
2724 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2725 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2727 transaction = ref_store_transaction_begin(refs, &err);
2728 if (!transaction) {
2729 error("%s", err.buf);
2730 ret = -1;
2731 } else if (get_oid("HEAD", &head_oid)) {
2732 error(_("could not read HEAD"));
2733 ret = -1;
2734 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2735 NULL, 0, msg.buf, &err) < 0 ||
2736 ref_transaction_commit(transaction, &err)) {
2737 error("%s", err.buf);
2738 ret = -1;
2740 ref_transaction_free(transaction);
2741 strbuf_release(&err);
2742 strbuf_release(&msg);
2744 if (!ret)
2745 ret = safe_append(rebase_path_refs_to_delete(),
2746 "%s\n", ref_name.buf);
2747 strbuf_release(&ref_name);
2749 return ret;
2752 static const char *reflog_message(struct replay_opts *opts,
2753 const char *sub_action, const char *fmt, ...);
2755 static int do_reset(const char *name, int len, struct replay_opts *opts)
2757 struct strbuf ref_name = STRBUF_INIT;
2758 struct object_id oid;
2759 struct lock_file lock = LOCK_INIT;
2760 struct tree_desc desc;
2761 struct tree *tree;
2762 struct unpack_trees_options unpack_tree_opts;
2763 int ret = 0, i;
2765 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2766 return -1;
2768 if (len == 10 && !strncmp("[new root]", name, len)) {
2769 if (!opts->have_squash_onto) {
2770 const char *hex;
2771 if (commit_tree("", 0, the_hash_algo->empty_tree,
2772 NULL, &opts->squash_onto,
2773 NULL, NULL))
2774 return error(_("writing fake root commit"));
2775 opts->have_squash_onto = 1;
2776 hex = oid_to_hex(&opts->squash_onto);
2777 if (write_message(hex, strlen(hex),
2778 rebase_path_squash_onto(), 0))
2779 return error(_("writing squash-onto"));
2781 oidcpy(&oid, &opts->squash_onto);
2782 } else {
2783 /* Determine the length of the label */
2784 for (i = 0; i < len; i++)
2785 if (isspace(name[i]))
2786 len = i;
2788 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2789 if (get_oid(ref_name.buf, &oid) &&
2790 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2791 error(_("could not read '%s'"), ref_name.buf);
2792 rollback_lock_file(&lock);
2793 strbuf_release(&ref_name);
2794 return -1;
2798 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2799 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2800 unpack_tree_opts.head_idx = 1;
2801 unpack_tree_opts.src_index = &the_index;
2802 unpack_tree_opts.dst_index = &the_index;
2803 unpack_tree_opts.fn = oneway_merge;
2804 unpack_tree_opts.merge = 1;
2805 unpack_tree_opts.update = 1;
2807 if (read_cache_unmerged()) {
2808 rollback_lock_file(&lock);
2809 strbuf_release(&ref_name);
2810 return error_resolve_conflict(_(action_name(opts)));
2813 if (!fill_tree_descriptor(&desc, &oid)) {
2814 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2815 rollback_lock_file(&lock);
2816 free((void *)desc.buffer);
2817 strbuf_release(&ref_name);
2818 return -1;
2821 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2822 rollback_lock_file(&lock);
2823 free((void *)desc.buffer);
2824 strbuf_release(&ref_name);
2825 return -1;
2828 tree = parse_tree_indirect(&oid);
2829 prime_cache_tree(&the_index, tree);
2831 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2832 ret = error(_("could not write index"));
2833 free((void *)desc.buffer);
2835 if (!ret)
2836 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2837 len, name), "HEAD", &oid,
2838 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2840 strbuf_release(&ref_name);
2841 return ret;
2844 static struct commit *lookup_label(const char *label, int len,
2845 struct strbuf *buf)
2847 struct commit *commit;
2849 strbuf_reset(buf);
2850 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
2851 commit = lookup_commit_reference_by_name(buf->buf);
2852 if (!commit) {
2853 /* fall back to non-rewritten ref or commit */
2854 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
2855 commit = lookup_commit_reference_by_name(buf->buf);
2858 if (!commit)
2859 error(_("could not resolve '%s'"), buf->buf);
2861 return commit;
2864 static int do_merge(struct commit *commit, const char *arg, int arg_len,
2865 int flags, struct replay_opts *opts)
2867 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2868 EDIT_MSG | VERIFY_MSG : 0;
2869 struct strbuf ref_name = STRBUF_INIT;
2870 struct commit *head_commit, *merge_commit, *i;
2871 struct commit_list *bases, *j, *reversed = NULL;
2872 struct commit_list *to_merge = NULL, **tail = &to_merge;
2873 struct merge_options o;
2874 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
2875 static struct lock_file lock;
2876 const char *p;
2878 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2879 ret = -1;
2880 goto leave_merge;
2883 head_commit = lookup_commit_reference_by_name("HEAD");
2884 if (!head_commit) {
2885 ret = error(_("cannot merge without a current revision"));
2886 goto leave_merge;
2890 * For octopus merges, the arg starts with the list of revisions to be
2891 * merged. The list is optionally followed by '#' and the oneline.
2893 merge_arg_len = oneline_offset = arg_len;
2894 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
2895 if (!*p)
2896 break;
2897 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2898 p += 1 + strspn(p + 1, " \t\n");
2899 oneline_offset = p - arg;
2900 break;
2902 k = strcspn(p, " \t\n");
2903 if (!k)
2904 continue;
2905 merge_commit = lookup_label(p, k, &ref_name);
2906 if (!merge_commit) {
2907 ret = error(_("unable to parse '%.*s'"), k, p);
2908 goto leave_merge;
2910 tail = &commit_list_insert(merge_commit, tail)->next;
2911 p += k;
2912 merge_arg_len = p - arg;
2915 if (!to_merge) {
2916 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
2917 goto leave_merge;
2920 if (opts->have_squash_onto &&
2921 !oidcmp(&head_commit->object.oid, &opts->squash_onto)) {
2923 * When the user tells us to "merge" something into a
2924 * "[new root]", let's simply fast-forward to the merge head.
2926 rollback_lock_file(&lock);
2927 if (to_merge->next)
2928 ret = error(_("octopus merge cannot be executed on "
2929 "top of a [new root]"));
2930 else
2931 ret = fast_forward_to(&to_merge->item->object.oid,
2932 &head_commit->object.oid, 0,
2933 opts);
2934 goto leave_merge;
2937 if (commit) {
2938 const char *message = get_commit_buffer(commit, NULL);
2939 const char *body;
2940 int len;
2942 if (!message) {
2943 ret = error(_("could not get commit message of '%s'"),
2944 oid_to_hex(&commit->object.oid));
2945 goto leave_merge;
2947 write_author_script(message);
2948 find_commit_subject(message, &body);
2949 len = strlen(body);
2950 ret = write_message(body, len, git_path_merge_msg(), 0);
2951 unuse_commit_buffer(commit, message);
2952 if (ret) {
2953 error_errno(_("could not write '%s'"),
2954 git_path_merge_msg());
2955 goto leave_merge;
2957 } else {
2958 struct strbuf buf = STRBUF_INIT;
2959 int len;
2961 strbuf_addf(&buf, "author %s", git_author_info(0));
2962 write_author_script(buf.buf);
2963 strbuf_reset(&buf);
2965 if (oneline_offset < arg_len) {
2966 p = arg + oneline_offset;
2967 len = arg_len - oneline_offset;
2968 } else {
2969 strbuf_addf(&buf, "Merge %s '%.*s'",
2970 to_merge->next ? "branches" : "branch",
2971 merge_arg_len, arg);
2972 p = buf.buf;
2973 len = buf.len;
2976 ret = write_message(p, len, git_path_merge_msg(), 0);
2977 strbuf_release(&buf);
2978 if (ret) {
2979 error_errno(_("could not write '%s'"),
2980 git_path_merge_msg());
2981 goto leave_merge;
2986 * If HEAD is not identical to the first parent of the original merge
2987 * commit, we cannot fast-forward.
2989 can_fast_forward = opts->allow_ff && commit && commit->parents &&
2990 !oidcmp(&commit->parents->item->object.oid,
2991 &head_commit->object.oid);
2994 * If any merge head is different from the original one, we cannot
2995 * fast-forward.
2997 if (can_fast_forward) {
2998 struct commit_list *p = commit->parents->next;
3000 for (j = to_merge; j && p; j = j->next, p = p->next)
3001 if (oidcmp(&j->item->object.oid,
3002 &p->item->object.oid)) {
3003 can_fast_forward = 0;
3004 break;
3007 * If the number of merge heads differs from the original merge
3008 * commit, we cannot fast-forward.
3010 if (j || p)
3011 can_fast_forward = 0;
3014 if (can_fast_forward) {
3015 rollback_lock_file(&lock);
3016 ret = fast_forward_to(&commit->object.oid,
3017 &head_commit->object.oid, 0, opts);
3018 goto leave_merge;
3021 if (to_merge->next) {
3022 /* Octopus merge */
3023 struct child_process cmd = CHILD_PROCESS_INIT;
3025 if (read_env_script(&cmd.env_array)) {
3026 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3028 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3029 goto leave_merge;
3032 cmd.git_cmd = 1;
3033 argv_array_push(&cmd.args, "merge");
3034 argv_array_push(&cmd.args, "-s");
3035 argv_array_push(&cmd.args, "octopus");
3036 argv_array_push(&cmd.args, "--no-edit");
3037 argv_array_push(&cmd.args, "--no-ff");
3038 argv_array_push(&cmd.args, "--no-log");
3039 argv_array_push(&cmd.args, "--no-stat");
3040 argv_array_push(&cmd.args, "-F");
3041 argv_array_push(&cmd.args, git_path_merge_msg());
3042 if (opts->gpg_sign)
3043 argv_array_push(&cmd.args, opts->gpg_sign);
3045 /* Add the tips to be merged */
3046 for (j = to_merge; j; j = j->next)
3047 argv_array_push(&cmd.args,
3048 oid_to_hex(&j->item->object.oid));
3050 strbuf_release(&ref_name);
3051 unlink(git_path_cherry_pick_head());
3052 rollback_lock_file(&lock);
3054 rollback_lock_file(&lock);
3055 ret = run_command(&cmd);
3057 /* force re-reading of the cache */
3058 if (!ret && (discard_cache() < 0 || read_cache() < 0))
3059 ret = error(_("could not read index"));
3060 goto leave_merge;
3063 merge_commit = to_merge->item;
3064 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3065 git_path_merge_head(), 0);
3066 write_message("no-ff", 5, git_path_merge_mode(), 0);
3068 bases = get_merge_bases(head_commit, merge_commit);
3069 if (bases && !oidcmp(&merge_commit->object.oid,
3070 &bases->item->object.oid)) {
3071 ret = 0;
3072 /* skip merging an ancestor of HEAD */
3073 goto leave_merge;
3076 for (j = bases; j; j = j->next)
3077 commit_list_insert(j->item, &reversed);
3078 free_commit_list(bases);
3080 read_cache();
3081 init_merge_options(&o);
3082 o.branch1 = "HEAD";
3083 o.branch2 = ref_name.buf;
3084 o.buffer_output = 2;
3086 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3087 if (ret <= 0)
3088 fputs(o.obuf.buf, stdout);
3089 strbuf_release(&o.obuf);
3090 if (ret < 0) {
3091 error(_("could not even attempt to merge '%.*s'"),
3092 merge_arg_len, arg);
3093 goto leave_merge;
3096 * The return value of merge_recursive() is 1 on clean, and 0 on
3097 * unclean merge.
3099 * Let's reverse that, so that do_merge() returns 0 upon success and
3100 * 1 upon failed merge (keeping the return value -1 for the cases where
3101 * we will want to reschedule the `merge` command).
3103 ret = !ret;
3105 if (active_cache_changed &&
3106 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3107 ret = error(_("merge: Unable to write new index file"));
3108 goto leave_merge;
3111 rollback_lock_file(&lock);
3112 if (ret)
3113 rerere(opts->allow_rerere_auto);
3114 else
3116 * In case of problems, we now want to return a positive
3117 * value (a negative one would indicate that the `merge`
3118 * command needs to be rescheduled).
3120 ret = !!run_git_commit(git_path_merge_msg(), opts,
3121 run_commit_flags);
3123 leave_merge:
3124 strbuf_release(&ref_name);
3125 rollback_lock_file(&lock);
3126 free_commit_list(to_merge);
3127 return ret;
3130 static int is_final_fixup(struct todo_list *todo_list)
3132 int i = todo_list->current;
3134 if (!is_fixup(todo_list->items[i].command))
3135 return 0;
3137 while (++i < todo_list->nr)
3138 if (is_fixup(todo_list->items[i].command))
3139 return 0;
3140 else if (!is_noop(todo_list->items[i].command))
3141 break;
3142 return 1;
3145 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3147 int i;
3149 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3150 if (!is_noop(todo_list->items[i].command))
3151 return todo_list->items[i].command;
3153 return -1;
3156 static int apply_autostash(struct replay_opts *opts)
3158 struct strbuf stash_sha1 = STRBUF_INIT;
3159 struct child_process child = CHILD_PROCESS_INIT;
3160 int ret = 0;
3162 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3163 strbuf_release(&stash_sha1);
3164 return 0;
3166 strbuf_trim(&stash_sha1);
3168 child.git_cmd = 1;
3169 child.no_stdout = 1;
3170 child.no_stderr = 1;
3171 argv_array_push(&child.args, "stash");
3172 argv_array_push(&child.args, "apply");
3173 argv_array_push(&child.args, stash_sha1.buf);
3174 if (!run_command(&child))
3175 fprintf(stderr, _("Applied autostash.\n"));
3176 else {
3177 struct child_process store = CHILD_PROCESS_INIT;
3179 store.git_cmd = 1;
3180 argv_array_push(&store.args, "stash");
3181 argv_array_push(&store.args, "store");
3182 argv_array_push(&store.args, "-m");
3183 argv_array_push(&store.args, "autostash");
3184 argv_array_push(&store.args, "-q");
3185 argv_array_push(&store.args, stash_sha1.buf);
3186 if (run_command(&store))
3187 ret = error(_("cannot store %s"), stash_sha1.buf);
3188 else
3189 fprintf(stderr,
3190 _("Applying autostash resulted in conflicts.\n"
3191 "Your changes are safe in the stash.\n"
3192 "You can run \"git stash pop\" or"
3193 " \"git stash drop\" at any time.\n"));
3196 strbuf_release(&stash_sha1);
3197 return ret;
3200 static const char *reflog_message(struct replay_opts *opts,
3201 const char *sub_action, const char *fmt, ...)
3203 va_list ap;
3204 static struct strbuf buf = STRBUF_INIT;
3206 va_start(ap, fmt);
3207 strbuf_reset(&buf);
3208 strbuf_addstr(&buf, action_name(opts));
3209 if (sub_action)
3210 strbuf_addf(&buf, " (%s)", sub_action);
3211 if (fmt) {
3212 strbuf_addstr(&buf, ": ");
3213 strbuf_vaddf(&buf, fmt, ap);
3215 va_end(ap);
3217 return buf.buf;
3220 static const char rescheduled_advice[] =
3221 N_("Could not execute the todo command\n"
3222 "\n"
3223 " %.*s"
3224 "\n"
3225 "It has been rescheduled; To edit the command before continuing, please\n"
3226 "edit the todo list first:\n"
3227 "\n"
3228 " git rebase --edit-todo\n"
3229 " git rebase --continue\n");
3231 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3233 int res = 0, reschedule = 0;
3235 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3236 if (opts->allow_ff)
3237 assert(!(opts->signoff || opts->no_commit ||
3238 opts->record_origin || opts->edit));
3239 if (read_and_refresh_cache(opts))
3240 return -1;
3242 while (todo_list->current < todo_list->nr) {
3243 struct todo_item *item = todo_list->items + todo_list->current;
3244 if (save_todo(todo_list, opts))
3245 return -1;
3246 if (is_rebase_i(opts)) {
3247 if (item->command != TODO_COMMENT) {
3248 FILE *f = fopen(rebase_path_msgnum(), "w");
3250 todo_list->done_nr++;
3252 if (f) {
3253 fprintf(f, "%d\n", todo_list->done_nr);
3254 fclose(f);
3256 fprintf(stderr, "Rebasing (%d/%d)%s",
3257 todo_list->done_nr,
3258 todo_list->total_nr,
3259 opts->verbose ? "\n" : "\r");
3261 unlink(rebase_path_message());
3262 unlink(rebase_path_author_script());
3263 unlink(rebase_path_stopped_sha());
3264 unlink(rebase_path_amend());
3265 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3267 if (item->command <= TODO_SQUASH) {
3268 if (is_rebase_i(opts))
3269 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3270 command_to_string(item->command), NULL),
3272 res = do_pick_commit(item->command, item->commit,
3273 opts, is_final_fixup(todo_list));
3274 if (is_rebase_i(opts) && res < 0) {
3275 /* Reschedule */
3276 advise(_(rescheduled_advice),
3277 get_item_line_length(todo_list,
3278 todo_list->current),
3279 get_item_line(todo_list,
3280 todo_list->current));
3281 todo_list->current--;
3282 if (save_todo(todo_list, opts))
3283 return -1;
3285 if (item->command == TODO_EDIT) {
3286 struct commit *commit = item->commit;
3287 if (!res)
3288 fprintf(stderr,
3289 _("Stopped at %s... %.*s\n"),
3290 short_commit_name(commit),
3291 item->arg_len, item->arg);
3292 return error_with_patch(commit,
3293 item->arg, item->arg_len, opts, res,
3294 !res);
3296 if (is_rebase_i(opts) && !res)
3297 record_in_rewritten(&item->commit->object.oid,
3298 peek_command(todo_list, 1));
3299 if (res && is_fixup(item->command)) {
3300 if (res == 1)
3301 intend_to_amend();
3302 return error_failed_squash(item->commit, opts,
3303 item->arg_len, item->arg);
3304 } else if (res && is_rebase_i(opts) && item->commit)
3305 return res | error_with_patch(item->commit,
3306 item->arg, item->arg_len, opts, res,
3307 item->command == TODO_REWORD);
3308 } else if (item->command == TODO_EXEC) {
3309 char *end_of_arg = (char *)(item->arg + item->arg_len);
3310 int saved = *end_of_arg;
3311 struct stat st;
3313 *end_of_arg = '\0';
3314 res = do_exec(item->arg);
3315 *end_of_arg = saved;
3317 /* Reread the todo file if it has changed. */
3318 if (res)
3319 ; /* fall through */
3320 else if (stat(get_todo_path(opts), &st))
3321 res = error_errno(_("could not stat '%s'"),
3322 get_todo_path(opts));
3323 else if (match_stat_data(&todo_list->stat, &st)) {
3324 todo_list_release(todo_list);
3325 if (read_populate_todo(todo_list, opts))
3326 res = -1; /* message was printed */
3327 /* `current` will be incremented below */
3328 todo_list->current = -1;
3330 } else if (item->command == TODO_LABEL) {
3331 if ((res = do_label(item->arg, item->arg_len)))
3332 reschedule = 1;
3333 } else if (item->command == TODO_RESET) {
3334 if ((res = do_reset(item->arg, item->arg_len, opts)))
3335 reschedule = 1;
3336 } else if (item->command == TODO_MERGE) {
3337 if ((res = do_merge(item->commit,
3338 item->arg, item->arg_len,
3339 item->flags, opts)) < 0)
3340 reschedule = 1;
3341 else if (item->commit)
3342 record_in_rewritten(&item->commit->object.oid,
3343 peek_command(todo_list, 1));
3344 if (res > 0)
3345 /* failed with merge conflicts */
3346 return error_with_patch(item->commit,
3347 item->arg,
3348 item->arg_len, opts,
3349 res, 0);
3350 } else if (!is_noop(item->command))
3351 return error(_("unknown command %d"), item->command);
3353 if (reschedule) {
3354 advise(_(rescheduled_advice),
3355 get_item_line_length(todo_list,
3356 todo_list->current),
3357 get_item_line(todo_list, todo_list->current));
3358 todo_list->current--;
3359 if (save_todo(todo_list, opts))
3360 return -1;
3361 if (item->commit)
3362 return error_with_patch(item->commit,
3363 item->arg,
3364 item->arg_len, opts,
3365 res, 0);
3368 todo_list->current++;
3369 if (res)
3370 return res;
3373 if (is_rebase_i(opts)) {
3374 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3375 struct stat st;
3377 /* Stopped in the middle, as planned? */
3378 if (todo_list->current < todo_list->nr)
3379 return 0;
3381 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3382 starts_with(head_ref.buf, "refs/")) {
3383 const char *msg;
3384 struct object_id head, orig;
3385 int res;
3387 if (get_oid("HEAD", &head)) {
3388 res = error(_("cannot read HEAD"));
3389 cleanup_head_ref:
3390 strbuf_release(&head_ref);
3391 strbuf_release(&buf);
3392 return res;
3394 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3395 get_oid_hex(buf.buf, &orig)) {
3396 res = error(_("could not read orig-head"));
3397 goto cleanup_head_ref;
3399 strbuf_reset(&buf);
3400 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3401 res = error(_("could not read 'onto'"));
3402 goto cleanup_head_ref;
3404 msg = reflog_message(opts, "finish", "%s onto %s",
3405 head_ref.buf, buf.buf);
3406 if (update_ref(msg, head_ref.buf, &head, &orig,
3407 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3408 res = error(_("could not update %s"),
3409 head_ref.buf);
3410 goto cleanup_head_ref;
3412 msg = reflog_message(opts, "finish", "returning to %s",
3413 head_ref.buf);
3414 if (create_symref("HEAD", head_ref.buf, msg)) {
3415 res = error(_("could not update HEAD to %s"),
3416 head_ref.buf);
3417 goto cleanup_head_ref;
3419 strbuf_reset(&buf);
3422 if (opts->verbose) {
3423 struct rev_info log_tree_opt;
3424 struct object_id orig, head;
3426 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3427 init_revisions(&log_tree_opt, NULL);
3428 log_tree_opt.diff = 1;
3429 log_tree_opt.diffopt.output_format =
3430 DIFF_FORMAT_DIFFSTAT;
3431 log_tree_opt.disable_stdin = 1;
3433 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3434 !get_oid(buf.buf, &orig) &&
3435 !get_oid("HEAD", &head)) {
3436 diff_tree_oid(&orig, &head, "",
3437 &log_tree_opt.diffopt);
3438 log_tree_diff_flush(&log_tree_opt);
3441 flush_rewritten_pending();
3442 if (!stat(rebase_path_rewritten_list(), &st) &&
3443 st.st_size > 0) {
3444 struct child_process child = CHILD_PROCESS_INIT;
3445 const char *post_rewrite_hook =
3446 find_hook("post-rewrite");
3448 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3449 child.git_cmd = 1;
3450 argv_array_push(&child.args, "notes");
3451 argv_array_push(&child.args, "copy");
3452 argv_array_push(&child.args, "--for-rewrite=rebase");
3453 /* we don't care if this copying failed */
3454 run_command(&child);
3456 if (post_rewrite_hook) {
3457 struct child_process hook = CHILD_PROCESS_INIT;
3459 hook.in = open(rebase_path_rewritten_list(),
3460 O_RDONLY);
3461 hook.stdout_to_stderr = 1;
3462 argv_array_push(&hook.args, post_rewrite_hook);
3463 argv_array_push(&hook.args, "rebase");
3464 /* we don't care if this hook failed */
3465 run_command(&hook);
3468 apply_autostash(opts);
3470 fprintf(stderr, "Successfully rebased and updated %s.\n",
3471 head_ref.buf);
3473 strbuf_release(&buf);
3474 strbuf_release(&head_ref);
3478 * Sequence of picks finished successfully; cleanup by
3479 * removing the .git/sequencer directory
3481 return sequencer_remove_state(opts);
3484 static int continue_single_pick(void)
3486 const char *argv[] = { "commit", NULL };
3488 if (!file_exists(git_path_cherry_pick_head()) &&
3489 !file_exists(git_path_revert_head()))
3490 return error(_("no cherry-pick or revert in progress"));
3491 return run_command_v_opt(argv, RUN_GIT_CMD);
3494 static int commit_staged_changes(struct replay_opts *opts,
3495 struct todo_list *todo_list)
3497 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3498 unsigned int final_fixup = 0, is_clean;
3500 if (has_unstaged_changes(1))
3501 return error(_("cannot rebase: You have unstaged changes."));
3503 is_clean = !has_uncommitted_changes(0);
3505 if (file_exists(rebase_path_amend())) {
3506 struct strbuf rev = STRBUF_INIT;
3507 struct object_id head, to_amend;
3509 if (get_oid("HEAD", &head))
3510 return error(_("cannot amend non-existing commit"));
3511 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3512 return error(_("invalid file: '%s'"), rebase_path_amend());
3513 if (get_oid_hex(rev.buf, &to_amend))
3514 return error(_("invalid contents: '%s'"),
3515 rebase_path_amend());
3516 if (!is_clean && oidcmp(&head, &to_amend))
3517 return error(_("\nYou have uncommitted changes in your "
3518 "working tree. Please, commit them\n"
3519 "first and then run 'git rebase "
3520 "--continue' again."));
3522 * When skipping a failed fixup/squash, we need to edit the
3523 * commit message, the current fixup list and count, and if it
3524 * was the last fixup/squash in the chain, we need to clean up
3525 * the commit message and if there was a squash, let the user
3526 * edit it.
3528 if (is_clean && !oidcmp(&head, &to_amend) &&
3529 opts->current_fixup_count > 0 &&
3530 file_exists(rebase_path_stopped_sha())) {
3531 const char *p = opts->current_fixups.buf;
3532 int len = opts->current_fixups.len;
3534 opts->current_fixup_count--;
3535 if (!len)
3536 BUG("Incorrect current_fixups:\n%s", p);
3537 while (len && p[len - 1] != '\n')
3538 len--;
3539 strbuf_setlen(&opts->current_fixups, len);
3540 if (write_message(p, len, rebase_path_current_fixups(),
3541 0) < 0)
3542 return error(_("could not write file: '%s'"),
3543 rebase_path_current_fixups());
3546 * If a fixup/squash in a fixup/squash chain failed, the
3547 * commit message is already correct, no need to commit
3548 * it again.
3550 * Only if it is the final command in the fixup/squash
3551 * chain, and only if the chain is longer than a single
3552 * fixup/squash command (which was just skipped), do we
3553 * actually need to re-commit with a cleaned up commit
3554 * message.
3556 if (opts->current_fixup_count > 0 &&
3557 !is_fixup(peek_command(todo_list, 0))) {
3558 final_fixup = 1;
3560 * If there was not a single "squash" in the
3561 * chain, we only need to clean up the commit
3562 * message, no need to bother the user with
3563 * opening the commit message in the editor.
3565 if (!starts_with(p, "squash ") &&
3566 !strstr(p, "\nsquash "))
3567 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3568 } else if (is_fixup(peek_command(todo_list, 0))) {
3570 * We need to update the squash message to skip
3571 * the latest commit message.
3573 struct commit *commit;
3574 const char *path = rebase_path_squash_msg();
3576 if (parse_head(&commit) ||
3577 !(p = get_commit_buffer(commit, NULL)) ||
3578 write_message(p, strlen(p), path, 0)) {
3579 unuse_commit_buffer(commit, p);
3580 return error(_("could not write file: "
3581 "'%s'"), path);
3583 unuse_commit_buffer(commit, p);
3587 strbuf_release(&rev);
3588 flags |= AMEND_MSG;
3591 if (is_clean) {
3592 const char *cherry_pick_head = git_path_cherry_pick_head();
3594 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3595 return error(_("could not remove CHERRY_PICK_HEAD"));
3596 if (!final_fixup)
3597 return 0;
3600 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3601 opts, flags))
3602 return error(_("could not commit staged changes."));
3603 unlink(rebase_path_amend());
3604 if (final_fixup) {
3605 unlink(rebase_path_fixup_msg());
3606 unlink(rebase_path_squash_msg());
3608 if (opts->current_fixup_count > 0) {
3610 * Whether final fixup or not, we just cleaned up the commit
3611 * message...
3613 unlink(rebase_path_current_fixups());
3614 strbuf_reset(&opts->current_fixups);
3615 opts->current_fixup_count = 0;
3617 return 0;
3620 int sequencer_continue(struct replay_opts *opts)
3622 struct todo_list todo_list = TODO_LIST_INIT;
3623 int res;
3625 if (read_and_refresh_cache(opts))
3626 return -1;
3628 if (read_populate_opts(opts))
3629 return -1;
3630 if (is_rebase_i(opts)) {
3631 if ((res = read_populate_todo(&todo_list, opts)))
3632 goto release_todo_list;
3633 if (commit_staged_changes(opts, &todo_list))
3634 return -1;
3635 } else if (!file_exists(get_todo_path(opts)))
3636 return continue_single_pick();
3637 else if ((res = read_populate_todo(&todo_list, opts)))
3638 goto release_todo_list;
3640 if (!is_rebase_i(opts)) {
3641 /* Verify that the conflict has been resolved */
3642 if (file_exists(git_path_cherry_pick_head()) ||
3643 file_exists(git_path_revert_head())) {
3644 res = continue_single_pick();
3645 if (res)
3646 goto release_todo_list;
3648 if (index_differs_from("HEAD", NULL, 0)) {
3649 res = error_dirty_index(opts);
3650 goto release_todo_list;
3652 todo_list.current++;
3653 } else if (file_exists(rebase_path_stopped_sha())) {
3654 struct strbuf buf = STRBUF_INIT;
3655 struct object_id oid;
3657 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3658 !get_oid_committish(buf.buf, &oid))
3659 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3660 strbuf_release(&buf);
3663 res = pick_commits(&todo_list, opts);
3664 release_todo_list:
3665 todo_list_release(&todo_list);
3666 return res;
3669 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3671 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3672 return do_pick_commit(opts->action == REPLAY_PICK ?
3673 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3676 int sequencer_pick_revisions(struct replay_opts *opts)
3678 struct todo_list todo_list = TODO_LIST_INIT;
3679 struct object_id oid;
3680 int i, res;
3682 assert(opts->revs);
3683 if (read_and_refresh_cache(opts))
3684 return -1;
3686 for (i = 0; i < opts->revs->pending.nr; i++) {
3687 struct object_id oid;
3688 const char *name = opts->revs->pending.objects[i].name;
3690 /* This happens when using --stdin. */
3691 if (!strlen(name))
3692 continue;
3694 if (!get_oid(name, &oid)) {
3695 if (!lookup_commit_reference_gently(&oid, 1)) {
3696 enum object_type type = oid_object_info(the_repository,
3697 &oid,
3698 NULL);
3699 return error(_("%s: can't cherry-pick a %s"),
3700 name, type_name(type));
3702 } else
3703 return error(_("%s: bad revision"), name);
3707 * If we were called as "git cherry-pick <commit>", just
3708 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3709 * REVERT_HEAD, and don't touch the sequencer state.
3710 * This means it is possible to cherry-pick in the middle
3711 * of a cherry-pick sequence.
3713 if (opts->revs->cmdline.nr == 1 &&
3714 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3715 opts->revs->no_walk &&
3716 !opts->revs->cmdline.rev->flags) {
3717 struct commit *cmit;
3718 if (prepare_revision_walk(opts->revs))
3719 return error(_("revision walk setup failed"));
3720 cmit = get_revision(opts->revs);
3721 if (!cmit || get_revision(opts->revs))
3722 return error("BUG: expected exactly one commit from walk");
3723 return single_pick(cmit, opts);
3727 * Start a new cherry-pick/ revert sequence; but
3728 * first, make sure that an existing one isn't in
3729 * progress
3732 if (walk_revs_populate_todo(&todo_list, opts) ||
3733 create_seq_dir() < 0)
3734 return -1;
3735 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3736 return error(_("can't revert as initial commit"));
3737 if (save_head(oid_to_hex(&oid)))
3738 return -1;
3739 if (save_opts(opts))
3740 return -1;
3741 update_abort_safety_file();
3742 res = pick_commits(&todo_list, opts);
3743 todo_list_release(&todo_list);
3744 return res;
3747 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3749 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3750 struct strbuf sob = STRBUF_INIT;
3751 int has_footer;
3753 strbuf_addstr(&sob, sign_off_header);
3754 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3755 getenv("GIT_COMMITTER_EMAIL")));
3756 strbuf_addch(&sob, '\n');
3758 if (!ignore_footer)
3759 strbuf_complete_line(msgbuf);
3762 * If the whole message buffer is equal to the sob, pretend that we
3763 * found a conforming footer with a matching sob
3765 if (msgbuf->len - ignore_footer == sob.len &&
3766 !strncmp(msgbuf->buf, sob.buf, sob.len))
3767 has_footer = 3;
3768 else
3769 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3771 if (!has_footer) {
3772 const char *append_newlines = NULL;
3773 size_t len = msgbuf->len - ignore_footer;
3775 if (!len) {
3777 * The buffer is completely empty. Leave foom for
3778 * the title and body to be filled in by the user.
3780 append_newlines = "\n\n";
3781 } else if (len == 1) {
3783 * Buffer contains a single newline. Add another
3784 * so that we leave room for the title and body.
3786 append_newlines = "\n";
3787 } else if (msgbuf->buf[len - 2] != '\n') {
3789 * Buffer ends with a single newline. Add another
3790 * so that there is an empty line between the message
3791 * body and the sob.
3793 append_newlines = "\n";
3794 } /* else, the buffer already ends with two newlines. */
3796 if (append_newlines)
3797 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3798 append_newlines, strlen(append_newlines));
3801 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3802 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3803 sob.buf, sob.len);
3805 strbuf_release(&sob);
3808 struct labels_entry {
3809 struct hashmap_entry entry;
3810 char label[FLEX_ARRAY];
3813 static int labels_cmp(const void *fndata, const struct labels_entry *a,
3814 const struct labels_entry *b, const void *key)
3816 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3819 struct string_entry {
3820 struct oidmap_entry entry;
3821 char string[FLEX_ARRAY];
3824 struct label_state {
3825 struct oidmap commit2label;
3826 struct hashmap labels;
3827 struct strbuf buf;
3830 static const char *label_oid(struct object_id *oid, const char *label,
3831 struct label_state *state)
3833 struct labels_entry *labels_entry;
3834 struct string_entry *string_entry;
3835 struct object_id dummy;
3836 size_t len;
3837 int i;
3839 string_entry = oidmap_get(&state->commit2label, oid);
3840 if (string_entry)
3841 return string_entry->string;
3844 * For "uninteresting" commits, i.e. commits that are not to be
3845 * rebased, and which can therefore not be labeled, we use a unique
3846 * abbreviation of the commit name. This is slightly more complicated
3847 * than calling find_unique_abbrev() because we also need to make
3848 * sure that the abbreviation does not conflict with any other
3849 * label.
3851 * We disallow "interesting" commits to be labeled by a string that
3852 * is a valid full-length hash, to ensure that we always can find an
3853 * abbreviation for any uninteresting commit's names that does not
3854 * clash with any other label.
3856 if (!label) {
3857 char *p;
3859 strbuf_reset(&state->buf);
3860 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3861 label = p = state->buf.buf;
3863 find_unique_abbrev_r(p, oid, default_abbrev);
3866 * We may need to extend the abbreviated hash so that there is
3867 * no conflicting label.
3869 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3870 size_t i = strlen(p) + 1;
3872 oid_to_hex_r(p, oid);
3873 for (; i < GIT_SHA1_HEXSZ; i++) {
3874 char save = p[i];
3875 p[i] = '\0';
3876 if (!hashmap_get_from_hash(&state->labels,
3877 strihash(p), p))
3878 break;
3879 p[i] = save;
3882 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
3883 !get_oid_hex(label, &dummy)) ||
3884 (len == 1 && *label == '#') ||
3885 hashmap_get_from_hash(&state->labels,
3886 strihash(label), label)) {
3888 * If the label already exists, or if the label is a valid full
3889 * OID, or the label is a '#' (which we use as a separator
3890 * between merge heads and oneline), we append a dash and a
3891 * number to make it unique.
3893 struct strbuf *buf = &state->buf;
3895 strbuf_reset(buf);
3896 strbuf_add(buf, label, len);
3898 for (i = 2; ; i++) {
3899 strbuf_setlen(buf, len);
3900 strbuf_addf(buf, "-%d", i);
3901 if (!hashmap_get_from_hash(&state->labels,
3902 strihash(buf->buf),
3903 buf->buf))
3904 break;
3907 label = buf->buf;
3910 FLEX_ALLOC_STR(labels_entry, label, label);
3911 hashmap_entry_init(labels_entry, strihash(label));
3912 hashmap_add(&state->labels, labels_entry);
3914 FLEX_ALLOC_STR(string_entry, string, label);
3915 oidcpy(&string_entry->entry.oid, oid);
3916 oidmap_put(&state->commit2label, string_entry);
3918 return string_entry->string;
3921 static int make_script_with_merges(struct pretty_print_context *pp,
3922 struct rev_info *revs, FILE *out,
3923 unsigned flags)
3925 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3926 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
3927 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3928 struct strbuf label = STRBUF_INIT;
3929 struct commit_list *commits = NULL, **tail = &commits, *iter;
3930 struct commit_list *tips = NULL, **tips_tail = &tips;
3931 struct commit *commit;
3932 struct oidmap commit2todo = OIDMAP_INIT;
3933 struct string_entry *entry;
3934 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3935 shown = OIDSET_INIT;
3936 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3938 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3939 const char *cmd_pick = abbr ? "p" : "pick",
3940 *cmd_label = abbr ? "l" : "label",
3941 *cmd_reset = abbr ? "t" : "reset",
3942 *cmd_merge = abbr ? "m" : "merge";
3944 oidmap_init(&commit2todo, 0);
3945 oidmap_init(&state.commit2label, 0);
3946 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3947 strbuf_init(&state.buf, 32);
3949 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3950 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3951 FLEX_ALLOC_STR(entry, string, "onto");
3952 oidcpy(&entry->entry.oid, oid);
3953 oidmap_put(&state.commit2label, entry);
3957 * First phase:
3958 * - get onelines for all commits
3959 * - gather all branch tips (i.e. 2nd or later parents of merges)
3960 * - label all branch tips
3962 while ((commit = get_revision(revs))) {
3963 struct commit_list *to_merge;
3964 const char *p1, *p2;
3965 struct object_id *oid;
3966 int is_empty;
3968 tail = &commit_list_insert(commit, tail)->next;
3969 oidset_insert(&interesting, &commit->object.oid);
3971 is_empty = is_original_commit_empty(commit);
3972 if (!is_empty && (commit->object.flags & PATCHSAME))
3973 continue;
3975 strbuf_reset(&oneline);
3976 pretty_print_commit(pp, commit, &oneline);
3978 to_merge = commit->parents ? commit->parents->next : NULL;
3979 if (!to_merge) {
3980 /* non-merge commit: easy case */
3981 strbuf_reset(&buf);
3982 if (!keep_empty && is_empty)
3983 strbuf_addf(&buf, "%c ", comment_line_char);
3984 strbuf_addf(&buf, "%s %s %s", cmd_pick,
3985 oid_to_hex(&commit->object.oid),
3986 oneline.buf);
3988 FLEX_ALLOC_STR(entry, string, buf.buf);
3989 oidcpy(&entry->entry.oid, &commit->object.oid);
3990 oidmap_put(&commit2todo, entry);
3992 continue;
3995 /* Create a label */
3996 strbuf_reset(&label);
3997 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3998 (p1 = strchr(p1, '\'')) &&
3999 (p2 = strchr(++p1, '\'')))
4000 strbuf_add(&label, p1, p2 - p1);
4001 else if (skip_prefix(oneline.buf, "Merge pull request ",
4002 &p1) &&
4003 (p1 = strstr(p1, " from ")))
4004 strbuf_addstr(&label, p1 + strlen(" from "));
4005 else
4006 strbuf_addbuf(&label, &oneline);
4008 for (p1 = label.buf; *p1; p1++)
4009 if (isspace(*p1))
4010 *(char *)p1 = '-';
4012 strbuf_reset(&buf);
4013 strbuf_addf(&buf, "%s -C %s",
4014 cmd_merge, oid_to_hex(&commit->object.oid));
4016 /* label the tips of merged branches */
4017 for (; to_merge; to_merge = to_merge->next) {
4018 oid = &to_merge->item->object.oid;
4019 strbuf_addch(&buf, ' ');
4021 if (!oidset_contains(&interesting, oid)) {
4022 strbuf_addstr(&buf, label_oid(oid, NULL,
4023 &state));
4024 continue;
4027 tips_tail = &commit_list_insert(to_merge->item,
4028 tips_tail)->next;
4030 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4032 strbuf_addf(&buf, " # %s", oneline.buf);
4034 FLEX_ALLOC_STR(entry, string, buf.buf);
4035 oidcpy(&entry->entry.oid, &commit->object.oid);
4036 oidmap_put(&commit2todo, entry);
4040 * Second phase:
4041 * - label branch points
4042 * - add HEAD to the branch tips
4044 for (iter = commits; iter; iter = iter->next) {
4045 struct commit_list *parent = iter->item->parents;
4046 for (; parent; parent = parent->next) {
4047 struct object_id *oid = &parent->item->object.oid;
4048 if (!oidset_contains(&interesting, oid))
4049 continue;
4050 if (!oidset_contains(&child_seen, oid))
4051 oidset_insert(&child_seen, oid);
4052 else
4053 label_oid(oid, "branch-point", &state);
4056 /* Add HEAD as implict "tip of branch" */
4057 if (!iter->next)
4058 tips_tail = &commit_list_insert(iter->item,
4059 tips_tail)->next;
4063 * Third phase: output the todo list. This is a bit tricky, as we
4064 * want to avoid jumping back and forth between revisions. To
4065 * accomplish that goal, we walk backwards from the branch tips,
4066 * gathering commits not yet shown, reversing the list on the fly,
4067 * then outputting that list (labeling revisions as needed).
4069 fprintf(out, "%s onto\n", cmd_label);
4070 for (iter = tips; iter; iter = iter->next) {
4071 struct commit_list *list = NULL, *iter2;
4073 commit = iter->item;
4074 if (oidset_contains(&shown, &commit->object.oid))
4075 continue;
4076 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4078 if (entry)
4079 fprintf(out, "\n# Branch %s\n", entry->string);
4080 else
4081 fprintf(out, "\n");
4083 while (oidset_contains(&interesting, &commit->object.oid) &&
4084 !oidset_contains(&shown, &commit->object.oid)) {
4085 commit_list_insert(commit, &list);
4086 if (!commit->parents) {
4087 commit = NULL;
4088 break;
4090 commit = commit->parents->item;
4093 if (!commit)
4094 fprintf(out, "%s %s\n", cmd_reset,
4095 rebase_cousins ? "onto" : "[new root]");
4096 else {
4097 const char *to = NULL;
4099 entry = oidmap_get(&state.commit2label,
4100 &commit->object.oid);
4101 if (entry)
4102 to = entry->string;
4103 else if (!rebase_cousins)
4104 to = label_oid(&commit->object.oid, NULL,
4105 &state);
4107 if (!to || !strcmp(to, "onto"))
4108 fprintf(out, "%s onto\n", cmd_reset);
4109 else {
4110 strbuf_reset(&oneline);
4111 pretty_print_commit(pp, commit, &oneline);
4112 fprintf(out, "%s %s # %s\n",
4113 cmd_reset, to, oneline.buf);
4117 for (iter2 = list; iter2; iter2 = iter2->next) {
4118 struct object_id *oid = &iter2->item->object.oid;
4119 entry = oidmap_get(&commit2todo, oid);
4120 /* only show if not already upstream */
4121 if (entry)
4122 fprintf(out, "%s\n", entry->string);
4123 entry = oidmap_get(&state.commit2label, oid);
4124 if (entry)
4125 fprintf(out, "%s %s\n",
4126 cmd_label, entry->string);
4127 oidset_insert(&shown, oid);
4130 free_commit_list(list);
4133 free_commit_list(commits);
4134 free_commit_list(tips);
4136 strbuf_release(&label);
4137 strbuf_release(&oneline);
4138 strbuf_release(&buf);
4140 oidmap_free(&commit2todo, 1);
4141 oidmap_free(&state.commit2label, 1);
4142 hashmap_free(&state.labels, 1);
4143 strbuf_release(&state.buf);
4145 return 0;
4148 int sequencer_make_script(FILE *out, int argc, const char **argv,
4149 unsigned flags)
4151 char *format = NULL;
4152 struct pretty_print_context pp = {0};
4153 struct strbuf buf = STRBUF_INIT;
4154 struct rev_info revs;
4155 struct commit *commit;
4156 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4157 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4158 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4160 init_revisions(&revs, NULL);
4161 revs.verbose_header = 1;
4162 if (!rebase_merges)
4163 revs.max_parents = 1;
4164 revs.cherry_mark = 1;
4165 revs.limited = 1;
4166 revs.reverse = 1;
4167 revs.right_only = 1;
4168 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4169 revs.topo_order = 1;
4171 revs.pretty_given = 1;
4172 git_config_get_string("rebase.instructionFormat", &format);
4173 if (!format || !*format) {
4174 free(format);
4175 format = xstrdup("%s");
4177 get_commit_format(format, &revs);
4178 free(format);
4179 pp.fmt = revs.commit_format;
4180 pp.output_encoding = get_log_output_encoding();
4182 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4183 return error(_("make_script: unhandled options"));
4185 if (prepare_revision_walk(&revs) < 0)
4186 return error(_("make_script: error preparing revisions"));
4188 if (rebase_merges)
4189 return make_script_with_merges(&pp, &revs, out, flags);
4191 while ((commit = get_revision(&revs))) {
4192 int is_empty = is_original_commit_empty(commit);
4194 if (!is_empty && (commit->object.flags & PATCHSAME))
4195 continue;
4196 strbuf_reset(&buf);
4197 if (!keep_empty && is_empty)
4198 strbuf_addf(&buf, "%c ", comment_line_char);
4199 strbuf_addf(&buf, "%s %s ", insn,
4200 oid_to_hex(&commit->object.oid));
4201 pretty_print_commit(&pp, commit, &buf);
4202 strbuf_addch(&buf, '\n');
4203 fputs(buf.buf, out);
4205 strbuf_release(&buf);
4206 return 0;
4210 * Add commands after pick and (series of) squash/fixup commands
4211 * in the todo list.
4213 int sequencer_add_exec_commands(const char *commands)
4215 const char *todo_file = rebase_path_todo();
4216 struct todo_list todo_list = TODO_LIST_INIT;
4217 struct todo_item *item;
4218 struct strbuf *buf = &todo_list.buf;
4219 size_t offset = 0, commands_len = strlen(commands);
4220 int i, first;
4222 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4223 return error(_("could not read '%s'."), todo_file);
4225 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4226 todo_list_release(&todo_list);
4227 return error(_("unusable todo list: '%s'"), todo_file);
4230 first = 1;
4231 /* insert <commands> before every pick except the first one */
4232 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4233 if (item->command == TODO_PICK && !first) {
4234 strbuf_insert(buf, item->offset_in_buf + offset,
4235 commands, commands_len);
4236 offset += commands_len;
4238 first = 0;
4241 /* append final <commands> */
4242 strbuf_add(buf, commands, commands_len);
4244 i = write_message(buf->buf, buf->len, todo_file, 0);
4245 todo_list_release(&todo_list);
4246 return i;
4249 int transform_todos(unsigned flags)
4251 const char *todo_file = rebase_path_todo();
4252 struct todo_list todo_list = TODO_LIST_INIT;
4253 struct strbuf buf = STRBUF_INIT;
4254 struct todo_item *item;
4255 int i;
4257 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4258 return error(_("could not read '%s'."), todo_file);
4260 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4261 todo_list_release(&todo_list);
4262 return error(_("unusable todo list: '%s'"), todo_file);
4265 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4266 /* if the item is not a command write it and continue */
4267 if (item->command >= TODO_COMMENT) {
4268 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4269 continue;
4272 /* add command to the buffer */
4273 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4274 strbuf_addch(&buf, command_to_char(item->command));
4275 else
4276 strbuf_addstr(&buf, command_to_string(item->command));
4278 /* add commit id */
4279 if (item->commit) {
4280 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4281 short_commit_name(item->commit) :
4282 oid_to_hex(&item->commit->object.oid);
4284 if (item->command == TODO_MERGE) {
4285 if (item->flags & TODO_EDIT_MERGE_MSG)
4286 strbuf_addstr(&buf, " -c");
4287 else
4288 strbuf_addstr(&buf, " -C");
4291 strbuf_addf(&buf, " %s", oid);
4294 /* add all the rest */
4295 if (!item->arg_len)
4296 strbuf_addch(&buf, '\n');
4297 else
4298 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4301 i = write_message(buf.buf, buf.len, todo_file, 0);
4302 todo_list_release(&todo_list);
4303 return i;
4306 enum check_level {
4307 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
4310 static enum check_level get_missing_commit_check_level(void)
4312 const char *value;
4314 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4315 !strcasecmp("ignore", value))
4316 return CHECK_IGNORE;
4317 if (!strcasecmp("warn", value))
4318 return CHECK_WARN;
4319 if (!strcasecmp("error", value))
4320 return CHECK_ERROR;
4321 warning(_("unrecognized setting %s for option "
4322 "rebase.missingCommitsCheck. Ignoring."), value);
4323 return CHECK_IGNORE;
4326 define_commit_slab(commit_seen, unsigned char);
4328 * Check if the user dropped some commits by mistake
4329 * Behaviour determined by rebase.missingCommitsCheck.
4330 * Check if there is an unrecognized command or a
4331 * bad SHA-1 in a command.
4333 int check_todo_list(void)
4335 enum check_level check_level = get_missing_commit_check_level();
4336 struct strbuf todo_file = STRBUF_INIT;
4337 struct todo_list todo_list = TODO_LIST_INIT;
4338 struct strbuf missing = STRBUF_INIT;
4339 int advise_to_edit_todo = 0, res = 0, i;
4340 struct commit_seen commit_seen;
4342 init_commit_seen(&commit_seen);
4344 strbuf_addstr(&todo_file, rebase_path_todo());
4345 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4346 res = -1;
4347 goto leave_check;
4349 advise_to_edit_todo = res =
4350 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4352 if (res || check_level == CHECK_IGNORE)
4353 goto leave_check;
4355 /* Mark the commits in git-rebase-todo as seen */
4356 for (i = 0; i < todo_list.nr; i++) {
4357 struct commit *commit = todo_list.items[i].commit;
4358 if (commit)
4359 *commit_seen_at(&commit_seen, commit) = 1;
4362 todo_list_release(&todo_list);
4363 strbuf_addstr(&todo_file, ".backup");
4364 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4365 res = -1;
4366 goto leave_check;
4368 strbuf_release(&todo_file);
4369 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4371 /* Find commits in git-rebase-todo.backup yet unseen */
4372 for (i = todo_list.nr - 1; i >= 0; i--) {
4373 struct todo_item *item = todo_list.items + i;
4374 struct commit *commit = item->commit;
4375 if (commit && !*commit_seen_at(&commit_seen, commit)) {
4376 strbuf_addf(&missing, " - %s %.*s\n",
4377 short_commit_name(commit),
4378 item->arg_len, item->arg);
4379 *commit_seen_at(&commit_seen, commit) = 1;
4383 /* Warn about missing commits */
4384 if (!missing.len)
4385 goto leave_check;
4387 if (check_level == CHECK_ERROR)
4388 advise_to_edit_todo = res = 1;
4390 fprintf(stderr,
4391 _("Warning: some commits may have been dropped accidentally.\n"
4392 "Dropped commits (newer to older):\n"));
4394 /* Make the list user-friendly and display */
4395 fputs(missing.buf, stderr);
4396 strbuf_release(&missing);
4398 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4399 "explicitly remove a commit.\n\n"
4400 "Use 'git config rebase.missingCommitsCheck' to change "
4401 "the level of warnings.\n"
4402 "The possible behaviours are: ignore, warn, error.\n\n"));
4404 leave_check:
4405 clear_commit_seen(&commit_seen);
4406 strbuf_release(&todo_file);
4407 todo_list_release(&todo_list);
4409 if (advise_to_edit_todo)
4410 fprintf(stderr,
4411 _("You can fix this with 'git rebase --edit-todo' "
4412 "and then run 'git rebase --continue'.\n"
4413 "Or you can abort the rebase with 'git rebase"
4414 " --abort'.\n"));
4416 return res;
4419 static int rewrite_file(const char *path, const char *buf, size_t len)
4421 int rc = 0;
4422 int fd = open(path, O_WRONLY | O_TRUNC);
4423 if (fd < 0)
4424 return error_errno(_("could not open '%s' for writing"), path);
4425 if (write_in_full(fd, buf, len) < 0)
4426 rc = error_errno(_("could not write to '%s'"), path);
4427 if (close(fd) && !rc)
4428 rc = error_errno(_("could not close '%s'"), path);
4429 return rc;
4432 /* skip picking commits whose parents are unchanged */
4433 int skip_unnecessary_picks(void)
4435 const char *todo_file = rebase_path_todo();
4436 struct strbuf buf = STRBUF_INIT;
4437 struct todo_list todo_list = TODO_LIST_INIT;
4438 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4439 int fd, i;
4441 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4442 return error(_("could not read 'onto'"));
4443 if (get_oid(buf.buf, &onto_oid)) {
4444 strbuf_release(&buf);
4445 return error(_("need a HEAD to fixup"));
4447 strbuf_release(&buf);
4449 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4450 return -1;
4451 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4452 todo_list_release(&todo_list);
4453 return -1;
4456 for (i = 0; i < todo_list.nr; i++) {
4457 struct todo_item *item = todo_list.items + i;
4459 if (item->command >= TODO_NOOP)
4460 continue;
4461 if (item->command != TODO_PICK)
4462 break;
4463 if (parse_commit(item->commit)) {
4464 todo_list_release(&todo_list);
4465 return error(_("could not parse commit '%s'"),
4466 oid_to_hex(&item->commit->object.oid));
4468 if (!item->commit->parents)
4469 break; /* root commit */
4470 if (item->commit->parents->next)
4471 break; /* merge commit */
4472 parent_oid = &item->commit->parents->item->object.oid;
4473 if (hashcmp(parent_oid->hash, oid->hash))
4474 break;
4475 oid = &item->commit->object.oid;
4477 if (i > 0) {
4478 int offset = get_item_line_offset(&todo_list, i);
4479 const char *done_path = rebase_path_done();
4481 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4482 if (fd < 0) {
4483 error_errno(_("could not open '%s' for writing"),
4484 done_path);
4485 todo_list_release(&todo_list);
4486 return -1;
4488 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4489 error_errno(_("could not write to '%s'"), done_path);
4490 todo_list_release(&todo_list);
4491 close(fd);
4492 return -1;
4494 close(fd);
4496 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4497 todo_list.buf.len - offset) < 0) {
4498 todo_list_release(&todo_list);
4499 return -1;
4502 todo_list.current = i;
4503 if (is_fixup(peek_command(&todo_list, 0)))
4504 record_in_rewritten(oid, peek_command(&todo_list, 0));
4507 todo_list_release(&todo_list);
4508 printf("%s\n", oid_to_hex(oid));
4510 return 0;
4513 struct subject2item_entry {
4514 struct hashmap_entry entry;
4515 int i;
4516 char subject[FLEX_ARRAY];
4519 static int subject2item_cmp(const void *fndata,
4520 const struct subject2item_entry *a,
4521 const struct subject2item_entry *b, const void *key)
4523 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4526 define_commit_slab(commit_todo_item, struct todo_item *);
4529 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4530 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4531 * after the former, and change "pick" to "fixup"/"squash".
4533 * Note that if the config has specified a custom instruction format, each log
4534 * message will have to be retrieved from the commit (as the oneline in the
4535 * script cannot be trusted) in order to normalize the autosquash arrangement.
4537 int rearrange_squash(void)
4539 const char *todo_file = rebase_path_todo();
4540 struct todo_list todo_list = TODO_LIST_INIT;
4541 struct hashmap subject2item;
4542 int res = 0, rearranged = 0, *next, *tail, i;
4543 char **subjects;
4544 struct commit_todo_item commit_todo;
4546 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4547 return -1;
4548 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4549 todo_list_release(&todo_list);
4550 return -1;
4553 init_commit_todo_item(&commit_todo);
4555 * The hashmap maps onelines to the respective todo list index.
4557 * If any items need to be rearranged, the next[i] value will indicate
4558 * which item was moved directly after the i'th.
4560 * In that case, last[i] will indicate the index of the latest item to
4561 * be moved to appear after the i'th.
4563 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4564 NULL, todo_list.nr);
4565 ALLOC_ARRAY(next, todo_list.nr);
4566 ALLOC_ARRAY(tail, todo_list.nr);
4567 ALLOC_ARRAY(subjects, todo_list.nr);
4568 for (i = 0; i < todo_list.nr; i++) {
4569 struct strbuf buf = STRBUF_INIT;
4570 struct todo_item *item = todo_list.items + i;
4571 const char *commit_buffer, *subject, *p;
4572 size_t subject_len;
4573 int i2 = -1;
4574 struct subject2item_entry *entry;
4576 next[i] = tail[i] = -1;
4577 if (!item->commit || item->command == TODO_DROP) {
4578 subjects[i] = NULL;
4579 continue;
4582 if (is_fixup(item->command)) {
4583 todo_list_release(&todo_list);
4584 clear_commit_todo_item(&commit_todo);
4585 return error(_("the script was already rearranged."));
4588 *commit_todo_item_at(&commit_todo, item->commit) = item;
4590 parse_commit(item->commit);
4591 commit_buffer = get_commit_buffer(item->commit, NULL);
4592 find_commit_subject(commit_buffer, &subject);
4593 format_subject(&buf, subject, " ");
4594 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4595 unuse_commit_buffer(item->commit, commit_buffer);
4596 if ((skip_prefix(subject, "fixup! ", &p) ||
4597 skip_prefix(subject, "squash! ", &p))) {
4598 struct commit *commit2;
4600 for (;;) {
4601 while (isspace(*p))
4602 p++;
4603 if (!skip_prefix(p, "fixup! ", &p) &&
4604 !skip_prefix(p, "squash! ", &p))
4605 break;
4608 if ((entry = hashmap_get_from_hash(&subject2item,
4609 strhash(p), p)))
4610 /* found by title */
4611 i2 = entry->i;
4612 else if (!strchr(p, ' ') &&
4613 (commit2 =
4614 lookup_commit_reference_by_name(p)) &&
4615 *commit_todo_item_at(&commit_todo, commit2))
4616 /* found by commit name */
4617 i2 = *commit_todo_item_at(&commit_todo, commit2)
4618 - todo_list.items;
4619 else {
4620 /* copy can be a prefix of the commit subject */
4621 for (i2 = 0; i2 < i; i2++)
4622 if (subjects[i2] &&
4623 starts_with(subjects[i2], p))
4624 break;
4625 if (i2 == i)
4626 i2 = -1;
4629 if (i2 >= 0) {
4630 rearranged = 1;
4631 todo_list.items[i].command =
4632 starts_with(subject, "fixup!") ?
4633 TODO_FIXUP : TODO_SQUASH;
4634 if (next[i2] < 0)
4635 next[i2] = i;
4636 else
4637 next[tail[i2]] = i;
4638 tail[i2] = i;
4639 } else if (!hashmap_get_from_hash(&subject2item,
4640 strhash(subject), subject)) {
4641 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4642 entry->i = i;
4643 hashmap_entry_init(entry, strhash(entry->subject));
4644 hashmap_put(&subject2item, entry);
4648 if (rearranged) {
4649 struct strbuf buf = STRBUF_INIT;
4651 for (i = 0; i < todo_list.nr; i++) {
4652 enum todo_command command = todo_list.items[i].command;
4653 int cur = i;
4656 * Initially, all commands are 'pick's. If it is a
4657 * fixup or a squash now, we have rearranged it.
4659 if (is_fixup(command))
4660 continue;
4662 while (cur >= 0) {
4663 const char *bol =
4664 get_item_line(&todo_list, cur);
4665 const char *eol =
4666 get_item_line(&todo_list, cur + 1);
4668 /* replace 'pick', by 'fixup' or 'squash' */
4669 command = todo_list.items[cur].command;
4670 if (is_fixup(command)) {
4671 strbuf_addstr(&buf,
4672 todo_command_info[command].str);
4673 bol += strcspn(bol, " \t");
4676 strbuf_add(&buf, bol, eol - bol);
4678 cur = next[cur];
4682 res = rewrite_file(todo_file, buf.buf, buf.len);
4683 strbuf_release(&buf);
4686 free(next);
4687 free(tail);
4688 for (i = 0; i < todo_list.nr; i++)
4689 free(subjects[i]);
4690 free(subjects);
4691 hashmap_free(&subject2item, 1);
4692 todo_list_release(&todo_list);
4694 clear_commit_todo_item(&commit_todo);
4695 return res;