commit: move post-rewrite code to libgit
[git/gitster.git] / sequencer.c
blob5529e5df1cbe9045b000ecbff6c28a0bee736ccc
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "sequencer.h"
8 #include "tag.h"
9 #include "run-command.h"
10 #include "exec_cmd.h"
11 #include "utf8.h"
12 #include "cache-tree.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "rerere.h"
16 #include "merge-recursive.h"
17 #include "refs.h"
18 #include "argv-array.h"
19 #include "quote.h"
20 #include "trailer.h"
21 #include "log-tree.h"
22 #include "wt-status.h"
23 #include "hashmap.h"
24 #include "notes-utils.h"
25 #include "sigchain.h"
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
32 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
34 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
35 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
36 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
37 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
39 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
41 * The file containing rebase commands, comments, and empty lines.
42 * This file is created by "git rebase -i" then edited by the user. As
43 * the lines are processed, they are removed from the front of this
44 * file and written to the tail of 'done'.
46 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
48 * The rebase command lines that have already been processed. A line
49 * is moved here when it is first handled, before any associated user
50 * actions.
52 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
54 * The file to keep track of how many commands were already processed (e.g.
55 * for the prompt).
57 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
59 * The file to keep track of how many commands are to be processed in total
60 * (e.g. for the prompt).
62 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
64 * The commit message that is planned to be used for any changes that
65 * need to be committed following a user interaction.
67 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
69 * The file into which is accumulated the suggested commit message for
70 * squash/fixup commands. When the first of a series of squash/fixups
71 * is seen, the file is created and the commit message from the
72 * previous commit and from the first squash/fixup commit are written
73 * to it. The commit message for each subsequent squash/fixup commit
74 * is appended to the file as it is processed.
76 * The first line of the file is of the form
77 * # This is a combination of $count commits.
78 * where $count is the number of commits whose messages have been
79 * written to the file so far (including the initial "pick" commit).
80 * Each time that a commit message is processed, this line is read and
81 * updated. It is deleted just before the combined commit is made.
83 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
85 * If the current series of squash/fixups has not yet included a squash
86 * command, then this file exists and holds the commit message of the
87 * original "pick" commit. (If the series ends without a "squash"
88 * command, then this can be used as the commit message of the combined
89 * commit without opening the editor.)
91 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
93 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
94 * GIT_AUTHOR_DATE that will be used for the commit that is currently
95 * being rebased.
97 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
99 * When an "edit" rebase command is being processed, the SHA1 of the
100 * commit to be edited is recorded in this file. When "git rebase
101 * --continue" is executed, if there are any staged changes then they
102 * will be amended to the HEAD commit, but only provided the HEAD
103 * commit is still the commit to be edited. When any other rebase
104 * command is processed, this file is deleted.
106 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
108 * When we stop at a given patch via the "edit" command, this file contains
109 * the abbreviated commit name of the corresponding patch.
111 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
113 * For the post-rewrite hook, we make a list of rewritten commits and
114 * their new sha1s. The rewritten-pending list keeps the sha1s of
115 * commits that have been processed, but not committed yet,
116 * e.g. because they are waiting for a 'squash' command.
118 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
119 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
120 "rebase-merge/rewritten-pending")
122 * The following files are written by git-rebase just after parsing the
123 * command-line (and are only consumed, not modified, by the sequencer).
125 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
126 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
127 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
128 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
129 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
130 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
131 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
132 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
133 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
135 static inline int is_rebase_i(const struct replay_opts *opts)
137 return opts->action == REPLAY_INTERACTIVE_REBASE;
140 static const char *get_dir(const struct replay_opts *opts)
142 if (is_rebase_i(opts))
143 return rebase_path();
144 return git_path_seq_dir();
147 static const char *get_todo_path(const struct replay_opts *opts)
149 if (is_rebase_i(opts))
150 return rebase_path_todo();
151 return git_path_todo_file();
155 * Returns 0 for non-conforming footer
156 * Returns 1 for conforming footer
157 * Returns 2 when sob exists within conforming footer
158 * Returns 3 when sob exists within conforming footer as last entry
160 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
161 int ignore_footer)
163 struct trailer_info info;
164 int i;
165 int found_sob = 0, found_sob_last = 0;
167 trailer_info_get(&info, sb->buf);
169 if (info.trailer_start == info.trailer_end)
170 return 0;
172 for (i = 0; i < info.trailer_nr; i++)
173 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
174 found_sob = 1;
175 if (i == info.trailer_nr - 1)
176 found_sob_last = 1;
179 trailer_info_release(&info);
181 if (found_sob_last)
182 return 3;
183 if (found_sob)
184 return 2;
185 return 1;
188 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
190 static struct strbuf buf = STRBUF_INIT;
192 strbuf_reset(&buf);
193 if (opts->gpg_sign)
194 sq_quotef(&buf, "-S%s", opts->gpg_sign);
195 return buf.buf;
198 int sequencer_remove_state(struct replay_opts *opts)
200 struct strbuf dir = STRBUF_INIT;
201 int i;
203 free(opts->gpg_sign);
204 free(opts->strategy);
205 for (i = 0; i < opts->xopts_nr; i++)
206 free(opts->xopts[i]);
207 free(opts->xopts);
209 strbuf_addstr(&dir, get_dir(opts));
210 remove_dir_recursively(&dir, 0);
211 strbuf_release(&dir);
213 return 0;
216 static const char *action_name(const struct replay_opts *opts)
218 switch (opts->action) {
219 case REPLAY_REVERT:
220 return N_("revert");
221 case REPLAY_PICK:
222 return N_("cherry-pick");
223 case REPLAY_INTERACTIVE_REBASE:
224 return N_("rebase -i");
226 die(_("Unknown action: %d"), opts->action);
229 struct commit_message {
230 char *parent_label;
231 char *label;
232 char *subject;
233 const char *message;
236 static const char *short_commit_name(struct commit *commit)
238 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
241 static int get_message(struct commit *commit, struct commit_message *out)
243 const char *abbrev, *subject;
244 int subject_len;
246 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
247 abbrev = short_commit_name(commit);
249 subject_len = find_commit_subject(out->message, &subject);
251 out->subject = xmemdupz(subject, subject_len);
252 out->label = xstrfmt("%s... %s", abbrev, out->subject);
253 out->parent_label = xstrfmt("parent of %s", out->label);
255 return 0;
258 static void free_message(struct commit *commit, struct commit_message *msg)
260 free(msg->parent_label);
261 free(msg->label);
262 free(msg->subject);
263 unuse_commit_buffer(commit, msg->message);
266 static void print_advice(int show_hint, struct replay_opts *opts)
268 char *msg = getenv("GIT_CHERRY_PICK_HELP");
270 if (msg) {
271 fprintf(stderr, "%s\n", msg);
273 * A conflict has occurred but the porcelain
274 * (typically rebase --interactive) wants to take care
275 * of the commit itself so remove CHERRY_PICK_HEAD
277 unlink(git_path_cherry_pick_head());
278 return;
281 if (show_hint) {
282 if (opts->no_commit)
283 advise(_("after resolving the conflicts, mark the corrected paths\n"
284 "with 'git add <paths>' or 'git rm <paths>'"));
285 else
286 advise(_("after resolving the conflicts, mark the corrected paths\n"
287 "with 'git add <paths>' or 'git rm <paths>'\n"
288 "and commit the result with 'git commit'"));
292 static int write_message(const void *buf, size_t len, const char *filename,
293 int append_eol)
295 static struct lock_file msg_file;
297 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
298 if (msg_fd < 0)
299 return error_errno(_("could not lock '%s'"), filename);
300 if (write_in_full(msg_fd, buf, len) < 0) {
301 rollback_lock_file(&msg_file);
302 return error_errno(_("could not write to '%s'"), filename);
304 if (append_eol && write(msg_fd, "\n", 1) < 0) {
305 rollback_lock_file(&msg_file);
306 return error_errno(_("could not write eol to '%s'"), filename);
308 if (commit_lock_file(&msg_file) < 0) {
309 rollback_lock_file(&msg_file);
310 return error(_("failed to finalize '%s'."), filename);
313 return 0;
317 * Reads a file that was presumably written by a shell script, i.e. with an
318 * end-of-line marker that needs to be stripped.
320 * Note that only the last end-of-line marker is stripped, consistent with the
321 * behavior of "$(cat path)" in a shell script.
323 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
325 static int read_oneliner(struct strbuf *buf,
326 const char *path, int skip_if_empty)
328 int orig_len = buf->len;
330 if (!file_exists(path))
331 return 0;
333 if (strbuf_read_file(buf, path, 0) < 0) {
334 warning_errno(_("could not read '%s'"), path);
335 return 0;
338 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
339 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
340 --buf->len;
341 buf->buf[buf->len] = '\0';
344 if (skip_if_empty && buf->len == orig_len)
345 return 0;
347 return 1;
350 static struct tree *empty_tree(void)
352 return lookup_tree(&empty_tree_oid);
355 static int error_dirty_index(struct replay_opts *opts)
357 if (read_cache_unmerged())
358 return error_resolve_conflict(_(action_name(opts)));
360 error(_("your local changes would be overwritten by %s."),
361 _(action_name(opts)));
363 if (advice_commit_before_merge)
364 advise(_("commit your changes or stash them to proceed."));
365 return -1;
368 static void update_abort_safety_file(void)
370 struct object_id head;
372 /* Do nothing on a single-pick */
373 if (!file_exists(git_path_seq_dir()))
374 return;
376 if (!get_oid("HEAD", &head))
377 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
378 else
379 write_file(git_path_abort_safety_file(), "%s", "");
382 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
383 int unborn, struct replay_opts *opts)
385 struct ref_transaction *transaction;
386 struct strbuf sb = STRBUF_INIT;
387 struct strbuf err = STRBUF_INIT;
389 read_cache();
390 if (checkout_fast_forward(from, to, 1))
391 return -1; /* the callee should have complained already */
393 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
395 transaction = ref_transaction_begin(&err);
396 if (!transaction ||
397 ref_transaction_update(transaction, "HEAD",
398 to, unborn ? &null_oid : from,
399 0, sb.buf, &err) ||
400 ref_transaction_commit(transaction, &err)) {
401 ref_transaction_free(transaction);
402 error("%s", err.buf);
403 strbuf_release(&sb);
404 strbuf_release(&err);
405 return -1;
408 strbuf_release(&sb);
409 strbuf_release(&err);
410 ref_transaction_free(transaction);
411 update_abort_safety_file();
412 return 0;
415 void append_conflicts_hint(struct strbuf *msgbuf)
417 int i;
419 strbuf_addch(msgbuf, '\n');
420 strbuf_commented_addf(msgbuf, "Conflicts:\n");
421 for (i = 0; i < active_nr;) {
422 const struct cache_entry *ce = active_cache[i++];
423 if (ce_stage(ce)) {
424 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
425 while (i < active_nr && !strcmp(ce->name,
426 active_cache[i]->name))
427 i++;
432 static int do_recursive_merge(struct commit *base, struct commit *next,
433 const char *base_label, const char *next_label,
434 struct object_id *head, struct strbuf *msgbuf,
435 struct replay_opts *opts)
437 struct merge_options o;
438 struct tree *result, *next_tree, *base_tree, *head_tree;
439 int clean;
440 char **xopt;
441 static struct lock_file index_lock;
443 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
445 read_cache();
447 init_merge_options(&o);
448 o.ancestor = base ? base_label : "(empty tree)";
449 o.branch1 = "HEAD";
450 o.branch2 = next ? next_label : "(empty tree)";
451 if (is_rebase_i(opts))
452 o.buffer_output = 2;
454 head_tree = parse_tree_indirect(head);
455 next_tree = next ? next->tree : empty_tree();
456 base_tree = base ? base->tree : empty_tree();
458 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
459 parse_merge_opt(&o, *xopt);
461 clean = merge_trees(&o,
462 head_tree,
463 next_tree, base_tree, &result);
464 if (is_rebase_i(opts) && clean <= 0)
465 fputs(o.obuf.buf, stdout);
466 strbuf_release(&o.obuf);
467 if (clean < 0)
468 return clean;
470 if (active_cache_changed &&
471 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
473 * TRANSLATORS: %s will be "revert", "cherry-pick" or
474 * "rebase -i".
476 return error(_("%s: Unable to write new index file"),
477 _(action_name(opts)));
478 rollback_lock_file(&index_lock);
480 if (opts->signoff)
481 append_signoff(msgbuf, 0, 0);
483 if (!clean)
484 append_conflicts_hint(msgbuf);
486 return !clean;
489 static int is_index_unchanged(void)
491 struct object_id head_oid;
492 struct commit *head_commit;
494 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
495 return error(_("could not resolve HEAD commit\n"));
497 head_commit = lookup_commit(&head_oid);
500 * If head_commit is NULL, check_commit, called from
501 * lookup_commit, would have indicated that head_commit is not
502 * a commit object already. parse_commit() will return failure
503 * without further complaints in such a case. Otherwise, if
504 * the commit is invalid, parse_commit() will complain. So
505 * there is nothing for us to say here. Just return failure.
507 if (parse_commit(head_commit))
508 return -1;
510 if (!active_cache_tree)
511 active_cache_tree = cache_tree();
513 if (!cache_tree_fully_valid(active_cache_tree))
514 if (cache_tree_update(&the_index, 0))
515 return error(_("unable to update cache tree\n"));
517 return !oidcmp(&active_cache_tree->oid,
518 &head_commit->tree->object.oid);
521 static int write_author_script(const char *message)
523 struct strbuf buf = STRBUF_INIT;
524 const char *eol;
525 int res;
527 for (;;)
528 if (!*message || starts_with(message, "\n")) {
529 missing_author:
530 /* Missing 'author' line? */
531 unlink(rebase_path_author_script());
532 return 0;
533 } else if (skip_prefix(message, "author ", &message))
534 break;
535 else if ((eol = strchr(message, '\n')))
536 message = eol + 1;
537 else
538 goto missing_author;
540 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
541 while (*message && *message != '\n' && *message != '\r')
542 if (skip_prefix(message, " <", &message))
543 break;
544 else if (*message != '\'')
545 strbuf_addch(&buf, *(message++));
546 else
547 strbuf_addf(&buf, "'\\\\%c'", *(message++));
548 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
549 while (*message && *message != '\n' && *message != '\r')
550 if (skip_prefix(message, "> ", &message))
551 break;
552 else if (*message != '\'')
553 strbuf_addch(&buf, *(message++));
554 else
555 strbuf_addf(&buf, "'\\\\%c'", *(message++));
556 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
557 while (*message && *message != '\n' && *message != '\r')
558 if (*message != '\'')
559 strbuf_addch(&buf, *(message++));
560 else
561 strbuf_addf(&buf, "'\\\\%c'", *(message++));
562 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
563 strbuf_release(&buf);
564 return res;
568 * Read a list of environment variable assignments (such as the author-script
569 * file) into an environment block. Returns -1 on error, 0 otherwise.
571 static int read_env_script(struct argv_array *env)
573 struct strbuf script = STRBUF_INIT;
574 int i, count = 0;
575 char *p, *p2;
577 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
578 return -1;
580 for (p = script.buf; *p; p++)
581 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
582 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
583 else if (*p == '\'')
584 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
585 else if (*p == '\n') {
586 *p = '\0';
587 count++;
590 for (i = 0, p = script.buf; i < count; i++) {
591 argv_array_push(env, p);
592 p += strlen(p) + 1;
595 return 0;
598 static const char staged_changes_advice[] =
599 N_("you have staged changes in your working tree\n"
600 "If these changes are meant to be squashed into the previous commit, run:\n"
601 "\n"
602 " git commit --amend %s\n"
603 "\n"
604 "If they are meant to go into a new commit, run:\n"
605 "\n"
606 " git commit %s\n"
607 "\n"
608 "In both cases, once you're done, continue with:\n"
609 "\n"
610 " git rebase --continue\n");
612 #define ALLOW_EMPTY (1<<0)
613 #define EDIT_MSG (1<<1)
614 #define AMEND_MSG (1<<2)
615 #define CLEANUP_MSG (1<<3)
616 #define VERIFY_MSG (1<<4)
619 * If we are cherry-pick, and if the merge did not result in
620 * hand-editing, we will hit this commit and inherit the original
621 * author date and name.
623 * If we are revert, or if our cherry-pick results in a hand merge,
624 * we had better say that the current user is responsible for that.
626 * An exception is when run_git_commit() is called during an
627 * interactive rebase: in that case, we will want to retain the
628 * author metadata.
630 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
631 unsigned int flags)
633 struct child_process cmd = CHILD_PROCESS_INIT;
634 const char *value;
636 cmd.git_cmd = 1;
638 if (is_rebase_i(opts)) {
639 if (!(flags & EDIT_MSG)) {
640 cmd.stdout_to_stderr = 1;
641 cmd.err = -1;
644 if (read_env_script(&cmd.env_array)) {
645 const char *gpg_opt = gpg_sign_opt_quoted(opts);
647 return error(_(staged_changes_advice),
648 gpg_opt, gpg_opt);
652 argv_array_push(&cmd.args, "commit");
654 if (!(flags & VERIFY_MSG))
655 argv_array_push(&cmd.args, "-n");
656 if ((flags & AMEND_MSG))
657 argv_array_push(&cmd.args, "--amend");
658 if (opts->gpg_sign)
659 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
660 if (opts->signoff)
661 argv_array_push(&cmd.args, "-s");
662 if (defmsg)
663 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
664 if ((flags & CLEANUP_MSG))
665 argv_array_push(&cmd.args, "--cleanup=strip");
666 if ((flags & EDIT_MSG))
667 argv_array_push(&cmd.args, "-e");
668 else if (!(flags & CLEANUP_MSG) &&
669 !opts->signoff && !opts->record_origin &&
670 git_config_get_value("commit.cleanup", &value))
671 argv_array_push(&cmd.args, "--cleanup=verbatim");
673 if ((flags & ALLOW_EMPTY))
674 argv_array_push(&cmd.args, "--allow-empty");
676 if (opts->allow_empty_message)
677 argv_array_push(&cmd.args, "--allow-empty-message");
679 if (cmd.err == -1) {
680 /* hide stderr on success */
681 struct strbuf buf = STRBUF_INIT;
682 int rc = pipe_command(&cmd,
683 NULL, 0,
684 /* stdout is already redirected */
685 NULL, 0,
686 &buf, 0);
687 if (rc)
688 fputs(buf.buf, stderr);
689 strbuf_release(&buf);
690 return rc;
693 return run_command(&cmd);
696 static int rest_is_empty(const struct strbuf *sb, int start)
698 int i, eol;
699 const char *nl;
701 /* Check if the rest is just whitespace and Signed-off-by's. */
702 for (i = start; i < sb->len; i++) {
703 nl = memchr(sb->buf + i, '\n', sb->len - i);
704 if (nl)
705 eol = nl - sb->buf;
706 else
707 eol = sb->len;
709 if (strlen(sign_off_header) <= eol - i &&
710 starts_with(sb->buf + i, sign_off_header)) {
711 i = eol;
712 continue;
714 while (i < eol)
715 if (!isspace(sb->buf[i++]))
716 return 0;
719 return 1;
723 * Find out if the message in the strbuf contains only whitespace and
724 * Signed-off-by lines.
726 int message_is_empty(const struct strbuf *sb,
727 enum commit_msg_cleanup_mode cleanup_mode)
729 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
730 return 0;
731 return rest_is_empty(sb, 0);
735 * See if the user edited the message in the editor or left what
736 * was in the template intact
738 int template_untouched(const struct strbuf *sb, const char *template_file,
739 enum commit_msg_cleanup_mode cleanup_mode)
741 struct strbuf tmpl = STRBUF_INIT;
742 const char *start;
744 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
745 return 0;
747 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
748 return 0;
750 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
751 if (!skip_prefix(sb->buf, tmpl.buf, &start))
752 start = sb->buf;
753 strbuf_release(&tmpl);
754 return rest_is_empty(sb, start - sb->buf);
757 int update_head_with_reflog(const struct commit *old_head,
758 const struct object_id *new_head,
759 const char *action, const struct strbuf *msg,
760 struct strbuf *err)
762 struct ref_transaction *transaction;
763 struct strbuf sb = STRBUF_INIT;
764 const char *nl;
765 int ret = 0;
767 if (action) {
768 strbuf_addstr(&sb, action);
769 strbuf_addstr(&sb, ": ");
772 nl = strchr(msg->buf, '\n');
773 if (nl) {
774 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
775 } else {
776 strbuf_addbuf(&sb, msg);
777 strbuf_addch(&sb, '\n');
780 transaction = ref_transaction_begin(err);
781 if (!transaction ||
782 ref_transaction_update(transaction, "HEAD", new_head,
783 old_head ? &old_head->object.oid : &null_oid,
784 0, sb.buf, err) ||
785 ref_transaction_commit(transaction, err)) {
786 ret = -1;
788 ref_transaction_free(transaction);
789 strbuf_release(&sb);
791 return ret;
794 static int run_rewrite_hook(const struct object_id *oldoid,
795 const struct object_id *newoid)
797 struct child_process proc = CHILD_PROCESS_INIT;
798 const char *argv[3];
799 int code;
800 struct strbuf sb = STRBUF_INIT;
802 argv[0] = find_hook("post-rewrite");
803 if (!argv[0])
804 return 0;
806 argv[1] = "amend";
807 argv[2] = NULL;
809 proc.argv = argv;
810 proc.in = -1;
811 proc.stdout_to_stderr = 1;
813 code = start_command(&proc);
814 if (code)
815 return code;
816 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
817 sigchain_push(SIGPIPE, SIG_IGN);
818 write_in_full(proc.in, sb.buf, sb.len);
819 close(proc.in);
820 strbuf_release(&sb);
821 sigchain_pop(SIGPIPE);
822 return finish_command(&proc);
825 void commit_post_rewrite(const struct commit *old_head,
826 const struct object_id *new_head)
828 struct notes_rewrite_cfg *cfg;
830 cfg = init_copy_notes_for_rewrite("amend");
831 if (cfg) {
832 /* we are amending, so old_head is not NULL */
833 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
834 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
836 run_rewrite_hook(&old_head->object.oid, new_head);
839 static int is_original_commit_empty(struct commit *commit)
841 const struct object_id *ptree_oid;
843 if (parse_commit(commit))
844 return error(_("could not parse commit %s\n"),
845 oid_to_hex(&commit->object.oid));
846 if (commit->parents) {
847 struct commit *parent = commit->parents->item;
848 if (parse_commit(parent))
849 return error(_("could not parse parent commit %s\n"),
850 oid_to_hex(&parent->object.oid));
851 ptree_oid = &parent->tree->object.oid;
852 } else {
853 ptree_oid = &empty_tree_oid; /* commit is root */
856 return !oidcmp(ptree_oid, &commit->tree->object.oid);
860 * Do we run "git commit" with "--allow-empty"?
862 static int allow_empty(struct replay_opts *opts, struct commit *commit)
864 int index_unchanged, empty_commit;
867 * Three cases:
869 * (1) we do not allow empty at all and error out.
871 * (2) we allow ones that were initially empty, but
872 * forbid the ones that become empty;
874 * (3) we allow both.
876 if (!opts->allow_empty)
877 return 0; /* let "git commit" barf as necessary */
879 index_unchanged = is_index_unchanged();
880 if (index_unchanged < 0)
881 return index_unchanged;
882 if (!index_unchanged)
883 return 0; /* we do not have to say --allow-empty */
885 if (opts->keep_redundant_commits)
886 return 1;
888 empty_commit = is_original_commit_empty(commit);
889 if (empty_commit < 0)
890 return empty_commit;
891 if (!empty_commit)
892 return 0;
893 else
894 return 1;
898 * Note that ordering matters in this enum. Not only must it match the mapping
899 * below, it is also divided into several sections that matter. When adding
900 * new commands, make sure you add it in the right section.
902 enum todo_command {
903 /* commands that handle commits */
904 TODO_PICK = 0,
905 TODO_REVERT,
906 TODO_EDIT,
907 TODO_REWORD,
908 TODO_FIXUP,
909 TODO_SQUASH,
910 /* commands that do something else than handling a single commit */
911 TODO_EXEC,
912 /* commands that do nothing but are counted for reporting progress */
913 TODO_NOOP,
914 TODO_DROP,
915 /* comments (not counted for reporting progress) */
916 TODO_COMMENT
919 static struct {
920 char c;
921 const char *str;
922 } todo_command_info[] = {
923 { 'p', "pick" },
924 { 0, "revert" },
925 { 'e', "edit" },
926 { 'r', "reword" },
927 { 'f', "fixup" },
928 { 's', "squash" },
929 { 'x', "exec" },
930 { 0, "noop" },
931 { 'd', "drop" },
932 { 0, NULL }
935 static const char *command_to_string(const enum todo_command command)
937 if (command < TODO_COMMENT)
938 return todo_command_info[command].str;
939 die("Unknown command: %d", command);
942 static int is_noop(const enum todo_command command)
944 return TODO_NOOP <= command;
947 static int is_fixup(enum todo_command command)
949 return command == TODO_FIXUP || command == TODO_SQUASH;
952 static int update_squash_messages(enum todo_command command,
953 struct commit *commit, struct replay_opts *opts)
955 struct strbuf buf = STRBUF_INIT;
956 int count, res;
957 const char *message, *body;
959 if (file_exists(rebase_path_squash_msg())) {
960 struct strbuf header = STRBUF_INIT;
961 char *eol, *p;
963 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
964 return error(_("could not read '%s'"),
965 rebase_path_squash_msg());
967 p = buf.buf + 1;
968 eol = strchrnul(buf.buf, '\n');
969 if (buf.buf[0] != comment_line_char ||
970 (p += strcspn(p, "0123456789\n")) == eol)
971 return error(_("unexpected 1st line of squash message:"
972 "\n\n\t%.*s"),
973 (int)(eol - buf.buf), buf.buf);
974 count = strtol(p, NULL, 10);
976 if (count < 1)
977 return error(_("invalid 1st line of squash message:\n"
978 "\n\t%.*s"),
979 (int)(eol - buf.buf), buf.buf);
981 strbuf_addf(&header, "%c ", comment_line_char);
982 strbuf_addf(&header,
983 _("This is a combination of %d commits."), ++count);
984 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
985 strbuf_release(&header);
986 } else {
987 struct object_id head;
988 struct commit *head_commit;
989 const char *head_message, *body;
991 if (get_oid("HEAD", &head))
992 return error(_("need a HEAD to fixup"));
993 if (!(head_commit = lookup_commit_reference(&head)))
994 return error(_("could not read HEAD"));
995 if (!(head_message = get_commit_buffer(head_commit, NULL)))
996 return error(_("could not read HEAD's commit message"));
998 find_commit_subject(head_message, &body);
999 if (write_message(body, strlen(body),
1000 rebase_path_fixup_msg(), 0)) {
1001 unuse_commit_buffer(head_commit, head_message);
1002 return error(_("cannot write '%s'"),
1003 rebase_path_fixup_msg());
1006 count = 2;
1007 strbuf_addf(&buf, "%c ", comment_line_char);
1008 strbuf_addf(&buf, _("This is a combination of %d commits."),
1009 count);
1010 strbuf_addf(&buf, "\n%c ", comment_line_char);
1011 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1012 strbuf_addstr(&buf, "\n\n");
1013 strbuf_addstr(&buf, body);
1015 unuse_commit_buffer(head_commit, head_message);
1018 if (!(message = get_commit_buffer(commit, NULL)))
1019 return error(_("could not read commit message of %s"),
1020 oid_to_hex(&commit->object.oid));
1021 find_commit_subject(message, &body);
1023 if (command == TODO_SQUASH) {
1024 unlink(rebase_path_fixup_msg());
1025 strbuf_addf(&buf, "\n%c ", comment_line_char);
1026 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1027 strbuf_addstr(&buf, "\n\n");
1028 strbuf_addstr(&buf, body);
1029 } else if (command == TODO_FIXUP) {
1030 strbuf_addf(&buf, "\n%c ", comment_line_char);
1031 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1032 count);
1033 strbuf_addstr(&buf, "\n\n");
1034 strbuf_add_commented_lines(&buf, body, strlen(body));
1035 } else
1036 return error(_("unknown command: %d"), command);
1037 unuse_commit_buffer(commit, message);
1039 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1040 strbuf_release(&buf);
1041 return res;
1044 static void flush_rewritten_pending(void) {
1045 struct strbuf buf = STRBUF_INIT;
1046 struct object_id newoid;
1047 FILE *out;
1049 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1050 !get_oid("HEAD", &newoid) &&
1051 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1052 char *bol = buf.buf, *eol;
1054 while (*bol) {
1055 eol = strchrnul(bol, '\n');
1056 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1057 bol, oid_to_hex(&newoid));
1058 if (!*eol)
1059 break;
1060 bol = eol + 1;
1062 fclose(out);
1063 unlink(rebase_path_rewritten_pending());
1065 strbuf_release(&buf);
1068 static void record_in_rewritten(struct object_id *oid,
1069 enum todo_command next_command) {
1070 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1072 if (!out)
1073 return;
1075 fprintf(out, "%s\n", oid_to_hex(oid));
1076 fclose(out);
1078 if (!is_fixup(next_command))
1079 flush_rewritten_pending();
1082 static int do_pick_commit(enum todo_command command, struct commit *commit,
1083 struct replay_opts *opts, int final_fixup)
1085 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1086 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1087 struct object_id head;
1088 struct commit *base, *next, *parent;
1089 const char *base_label, *next_label;
1090 struct commit_message msg = { NULL, NULL, NULL, NULL };
1091 struct strbuf msgbuf = STRBUF_INIT;
1092 int res, unborn = 0, allow;
1094 if (opts->no_commit) {
1096 * We do not intend to commit immediately. We just want to
1097 * merge the differences in, so let's compute the tree
1098 * that represents the "current" state for merge-recursive
1099 * to work on.
1101 if (write_cache_as_tree(head.hash, 0, NULL))
1102 return error(_("your index file is unmerged."));
1103 } else {
1104 unborn = get_oid("HEAD", &head);
1105 if (unborn)
1106 oidcpy(&head, &empty_tree_oid);
1107 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1108 NULL, 0))
1109 return error_dirty_index(opts);
1111 discard_cache();
1113 if (!commit->parents)
1114 parent = NULL;
1115 else if (commit->parents->next) {
1116 /* Reverting or cherry-picking a merge commit */
1117 int cnt;
1118 struct commit_list *p;
1120 if (!opts->mainline)
1121 return error(_("commit %s is a merge but no -m option was given."),
1122 oid_to_hex(&commit->object.oid));
1124 for (cnt = 1, p = commit->parents;
1125 cnt != opts->mainline && p;
1126 cnt++)
1127 p = p->next;
1128 if (cnt != opts->mainline || !p)
1129 return error(_("commit %s does not have parent %d"),
1130 oid_to_hex(&commit->object.oid), opts->mainline);
1131 parent = p->item;
1132 } else if (0 < opts->mainline)
1133 return error(_("mainline was specified but commit %s is not a merge."),
1134 oid_to_hex(&commit->object.oid));
1135 else
1136 parent = commit->parents->item;
1138 if (get_message(commit, &msg) != 0)
1139 return error(_("cannot get commit message for %s"),
1140 oid_to_hex(&commit->object.oid));
1142 if (opts->allow_ff && !is_fixup(command) &&
1143 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1144 (!parent && unborn))) {
1145 if (is_rebase_i(opts))
1146 write_author_script(msg.message);
1147 res = fast_forward_to(&commit->object.oid, &head, unborn,
1148 opts);
1149 if (res || command != TODO_REWORD)
1150 goto leave;
1151 flags |= EDIT_MSG | AMEND_MSG;
1152 if (command == TODO_REWORD)
1153 flags |= VERIFY_MSG;
1154 msg_file = NULL;
1155 goto fast_forward_edit;
1157 if (parent && parse_commit(parent) < 0)
1158 /* TRANSLATORS: The first %s will be a "todo" command like
1159 "revert" or "pick", the second %s a SHA1. */
1160 return error(_("%s: cannot parse parent commit %s"),
1161 command_to_string(command),
1162 oid_to_hex(&parent->object.oid));
1165 * "commit" is an existing commit. We would want to apply
1166 * the difference it introduces since its first parent "prev"
1167 * on top of the current HEAD if we are cherry-pick. Or the
1168 * reverse of it if we are revert.
1171 if (command == TODO_REVERT) {
1172 base = commit;
1173 base_label = msg.label;
1174 next = parent;
1175 next_label = msg.parent_label;
1176 strbuf_addstr(&msgbuf, "Revert \"");
1177 strbuf_addstr(&msgbuf, msg.subject);
1178 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1179 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1181 if (commit->parents && commit->parents->next) {
1182 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1183 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1185 strbuf_addstr(&msgbuf, ".\n");
1186 } else {
1187 const char *p;
1189 base = parent;
1190 base_label = msg.parent_label;
1191 next = commit;
1192 next_label = msg.label;
1194 /* Append the commit log message to msgbuf. */
1195 if (find_commit_subject(msg.message, &p))
1196 strbuf_addstr(&msgbuf, p);
1198 if (opts->record_origin) {
1199 strbuf_complete_line(&msgbuf);
1200 if (!has_conforming_footer(&msgbuf, NULL, 0))
1201 strbuf_addch(&msgbuf, '\n');
1202 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1203 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1204 strbuf_addstr(&msgbuf, ")\n");
1208 if (command == TODO_REWORD)
1209 flags |= EDIT_MSG | VERIFY_MSG;
1210 else if (is_fixup(command)) {
1211 if (update_squash_messages(command, commit, opts))
1212 return -1;
1213 flags |= AMEND_MSG;
1214 if (!final_fixup)
1215 msg_file = rebase_path_squash_msg();
1216 else if (file_exists(rebase_path_fixup_msg())) {
1217 flags |= CLEANUP_MSG;
1218 msg_file = rebase_path_fixup_msg();
1219 } else {
1220 const char *dest = git_path_squash_msg();
1221 unlink(dest);
1222 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1223 return error(_("could not rename '%s' to '%s'"),
1224 rebase_path_squash_msg(), dest);
1225 unlink(git_path_merge_msg());
1226 msg_file = dest;
1227 flags |= EDIT_MSG;
1231 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1232 res = -1;
1233 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1234 res = do_recursive_merge(base, next, base_label, next_label,
1235 &head, &msgbuf, opts);
1236 if (res < 0)
1237 return res;
1238 res |= write_message(msgbuf.buf, msgbuf.len,
1239 git_path_merge_msg(), 0);
1240 } else {
1241 struct commit_list *common = NULL;
1242 struct commit_list *remotes = NULL;
1244 res = write_message(msgbuf.buf, msgbuf.len,
1245 git_path_merge_msg(), 0);
1247 commit_list_insert(base, &common);
1248 commit_list_insert(next, &remotes);
1249 res |= try_merge_command(opts->strategy,
1250 opts->xopts_nr, (const char **)opts->xopts,
1251 common, oid_to_hex(&head), remotes);
1252 free_commit_list(common);
1253 free_commit_list(remotes);
1255 strbuf_release(&msgbuf);
1258 * If the merge was clean or if it failed due to conflict, we write
1259 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1260 * However, if the merge did not even start, then we don't want to
1261 * write it at all.
1263 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1264 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1265 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1266 res = -1;
1267 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1268 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1269 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1270 res = -1;
1272 if (res) {
1273 error(command == TODO_REVERT
1274 ? _("could not revert %s... %s")
1275 : _("could not apply %s... %s"),
1276 short_commit_name(commit), msg.subject);
1277 print_advice(res == 1, opts);
1278 rerere(opts->allow_rerere_auto);
1279 goto leave;
1282 allow = allow_empty(opts, commit);
1283 if (allow < 0) {
1284 res = allow;
1285 goto leave;
1286 } else if (allow)
1287 flags |= ALLOW_EMPTY;
1288 if (!opts->no_commit)
1289 fast_forward_edit:
1290 res = run_git_commit(msg_file, opts, flags);
1292 if (!res && final_fixup) {
1293 unlink(rebase_path_fixup_msg());
1294 unlink(rebase_path_squash_msg());
1297 leave:
1298 free_message(commit, &msg);
1299 update_abort_safety_file();
1301 return res;
1304 static int prepare_revs(struct replay_opts *opts)
1307 * picking (but not reverting) ranges (but not individual revisions)
1308 * should be done in reverse
1310 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1311 opts->revs->reverse ^= 1;
1313 if (prepare_revision_walk(opts->revs))
1314 return error(_("revision walk setup failed"));
1316 if (!opts->revs->commits)
1317 return error(_("empty commit set passed"));
1318 return 0;
1321 static int read_and_refresh_cache(struct replay_opts *opts)
1323 static struct lock_file index_lock;
1324 int index_fd = hold_locked_index(&index_lock, 0);
1325 if (read_index_preload(&the_index, NULL) < 0) {
1326 rollback_lock_file(&index_lock);
1327 return error(_("git %s: failed to read the index"),
1328 _(action_name(opts)));
1330 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1331 if (the_index.cache_changed && index_fd >= 0) {
1332 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1333 return error(_("git %s: failed to refresh the index"),
1334 _(action_name(opts)));
1337 rollback_lock_file(&index_lock);
1338 return 0;
1341 struct todo_item {
1342 enum todo_command command;
1343 struct commit *commit;
1344 const char *arg;
1345 int arg_len;
1346 size_t offset_in_buf;
1349 struct todo_list {
1350 struct strbuf buf;
1351 struct todo_item *items;
1352 int nr, alloc, current;
1353 int done_nr, total_nr;
1354 struct stat_data stat;
1357 #define TODO_LIST_INIT { STRBUF_INIT }
1359 static void todo_list_release(struct todo_list *todo_list)
1361 strbuf_release(&todo_list->buf);
1362 FREE_AND_NULL(todo_list->items);
1363 todo_list->nr = todo_list->alloc = 0;
1366 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1368 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1369 return todo_list->items + todo_list->nr++;
1372 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1374 struct object_id commit_oid;
1375 char *end_of_object_name;
1376 int i, saved, status, padding;
1378 /* left-trim */
1379 bol += strspn(bol, " \t");
1381 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1382 item->command = TODO_COMMENT;
1383 item->commit = NULL;
1384 item->arg = bol;
1385 item->arg_len = eol - bol;
1386 return 0;
1389 for (i = 0; i < TODO_COMMENT; i++)
1390 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1391 item->command = i;
1392 break;
1393 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1394 bol++;
1395 item->command = i;
1396 break;
1398 if (i >= TODO_COMMENT)
1399 return -1;
1401 if (item->command == TODO_NOOP) {
1402 item->commit = NULL;
1403 item->arg = bol;
1404 item->arg_len = eol - bol;
1405 return 0;
1408 /* Eat up extra spaces/ tabs before object name */
1409 padding = strspn(bol, " \t");
1410 if (!padding)
1411 return -1;
1412 bol += padding;
1414 if (item->command == TODO_EXEC) {
1415 item->arg = bol;
1416 item->arg_len = (int)(eol - bol);
1417 return 0;
1420 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1421 saved = *end_of_object_name;
1422 *end_of_object_name = '\0';
1423 status = get_oid(bol, &commit_oid);
1424 *end_of_object_name = saved;
1426 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1427 item->arg_len = (int)(eol - item->arg);
1429 if (status < 0)
1430 return -1;
1432 item->commit = lookup_commit_reference(&commit_oid);
1433 return !item->commit;
1436 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1438 struct todo_item *item;
1439 char *p = buf, *next_p;
1440 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1442 for (i = 1; *p; i++, p = next_p) {
1443 char *eol = strchrnul(p, '\n');
1445 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1447 if (p != eol && eol[-1] == '\r')
1448 eol--; /* strip Carriage Return */
1450 item = append_new_todo(todo_list);
1451 item->offset_in_buf = p - todo_list->buf.buf;
1452 if (parse_insn_line(item, p, eol)) {
1453 res = error(_("invalid line %d: %.*s"),
1454 i, (int)(eol - p), p);
1455 item->command = TODO_NOOP;
1458 if (fixup_okay)
1459 ; /* do nothing */
1460 else if (is_fixup(item->command))
1461 return error(_("cannot '%s' without a previous commit"),
1462 command_to_string(item->command));
1463 else if (!is_noop(item->command))
1464 fixup_okay = 1;
1467 return res;
1470 static int count_commands(struct todo_list *todo_list)
1472 int count = 0, i;
1474 for (i = 0; i < todo_list->nr; i++)
1475 if (todo_list->items[i].command != TODO_COMMENT)
1476 count++;
1478 return count;
1481 static int read_populate_todo(struct todo_list *todo_list,
1482 struct replay_opts *opts)
1484 struct stat st;
1485 const char *todo_file = get_todo_path(opts);
1486 int fd, res;
1488 strbuf_reset(&todo_list->buf);
1489 fd = open(todo_file, O_RDONLY);
1490 if (fd < 0)
1491 return error_errno(_("could not open '%s'"), todo_file);
1492 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1493 close(fd);
1494 return error(_("could not read '%s'."), todo_file);
1496 close(fd);
1498 res = stat(todo_file, &st);
1499 if (res)
1500 return error(_("could not stat '%s'"), todo_file);
1501 fill_stat_data(&todo_list->stat, &st);
1503 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1504 if (res) {
1505 if (is_rebase_i(opts))
1506 return error(_("please fix this using "
1507 "'git rebase --edit-todo'."));
1508 return error(_("unusable instruction sheet: '%s'"), todo_file);
1511 if (!todo_list->nr &&
1512 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1513 return error(_("no commits parsed."));
1515 if (!is_rebase_i(opts)) {
1516 enum todo_command valid =
1517 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1518 int i;
1520 for (i = 0; i < todo_list->nr; i++)
1521 if (valid == todo_list->items[i].command)
1522 continue;
1523 else if (valid == TODO_PICK)
1524 return error(_("cannot cherry-pick during a revert."));
1525 else
1526 return error(_("cannot revert during a cherry-pick."));
1529 if (is_rebase_i(opts)) {
1530 struct todo_list done = TODO_LIST_INIT;
1531 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1533 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1534 !parse_insn_buffer(done.buf.buf, &done))
1535 todo_list->done_nr = count_commands(&done);
1536 else
1537 todo_list->done_nr = 0;
1539 todo_list->total_nr = todo_list->done_nr
1540 + count_commands(todo_list);
1541 todo_list_release(&done);
1543 if (f) {
1544 fprintf(f, "%d\n", todo_list->total_nr);
1545 fclose(f);
1549 return 0;
1552 static int git_config_string_dup(char **dest,
1553 const char *var, const char *value)
1555 if (!value)
1556 return config_error_nonbool(var);
1557 free(*dest);
1558 *dest = xstrdup(value);
1559 return 0;
1562 static int populate_opts_cb(const char *key, const char *value, void *data)
1564 struct replay_opts *opts = data;
1565 int error_flag = 1;
1567 if (!value)
1568 error_flag = 0;
1569 else if (!strcmp(key, "options.no-commit"))
1570 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1571 else if (!strcmp(key, "options.edit"))
1572 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1573 else if (!strcmp(key, "options.signoff"))
1574 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1575 else if (!strcmp(key, "options.record-origin"))
1576 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1577 else if (!strcmp(key, "options.allow-ff"))
1578 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1579 else if (!strcmp(key, "options.mainline"))
1580 opts->mainline = git_config_int(key, value);
1581 else if (!strcmp(key, "options.strategy"))
1582 git_config_string_dup(&opts->strategy, key, value);
1583 else if (!strcmp(key, "options.gpg-sign"))
1584 git_config_string_dup(&opts->gpg_sign, key, value);
1585 else if (!strcmp(key, "options.strategy-option")) {
1586 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1587 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1588 } else if (!strcmp(key, "options.allow-rerere-auto"))
1589 opts->allow_rerere_auto =
1590 git_config_bool_or_int(key, value, &error_flag) ?
1591 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1592 else
1593 return error(_("invalid key: %s"), key);
1595 if (!error_flag)
1596 return error(_("invalid value for %s: %s"), key, value);
1598 return 0;
1601 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1603 int i;
1605 strbuf_reset(buf);
1606 if (!read_oneliner(buf, rebase_path_strategy(), 0))
1607 return;
1608 opts->strategy = strbuf_detach(buf, NULL);
1609 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1610 return;
1612 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1613 for (i = 0; i < opts->xopts_nr; i++) {
1614 const char *arg = opts->xopts[i];
1616 skip_prefix(arg, "--", &arg);
1617 opts->xopts[i] = xstrdup(arg);
1621 static int read_populate_opts(struct replay_opts *opts)
1623 if (is_rebase_i(opts)) {
1624 struct strbuf buf = STRBUF_INIT;
1626 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1627 if (!starts_with(buf.buf, "-S"))
1628 strbuf_reset(&buf);
1629 else {
1630 free(opts->gpg_sign);
1631 opts->gpg_sign = xstrdup(buf.buf + 2);
1633 strbuf_reset(&buf);
1636 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1637 if (!strcmp(buf.buf, "--rerere-autoupdate"))
1638 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1639 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1640 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1641 strbuf_reset(&buf);
1644 if (file_exists(rebase_path_verbose()))
1645 opts->verbose = 1;
1647 read_strategy_opts(opts, &buf);
1648 strbuf_release(&buf);
1650 return 0;
1653 if (!file_exists(git_path_opts_file()))
1654 return 0;
1656 * The function git_parse_source(), called from git_config_from_file(),
1657 * may die() in case of a syntactically incorrect file. We do not care
1658 * about this case, though, because we wrote that file ourselves, so we
1659 * are pretty certain that it is syntactically correct.
1661 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1662 return error(_("malformed options sheet: '%s'"),
1663 git_path_opts_file());
1664 return 0;
1667 static int walk_revs_populate_todo(struct todo_list *todo_list,
1668 struct replay_opts *opts)
1670 enum todo_command command = opts->action == REPLAY_PICK ?
1671 TODO_PICK : TODO_REVERT;
1672 const char *command_string = todo_command_info[command].str;
1673 struct commit *commit;
1675 if (prepare_revs(opts))
1676 return -1;
1678 while ((commit = get_revision(opts->revs))) {
1679 struct todo_item *item = append_new_todo(todo_list);
1680 const char *commit_buffer = get_commit_buffer(commit, NULL);
1681 const char *subject;
1682 int subject_len;
1684 item->command = command;
1685 item->commit = commit;
1686 item->arg = NULL;
1687 item->arg_len = 0;
1688 item->offset_in_buf = todo_list->buf.len;
1689 subject_len = find_commit_subject(commit_buffer, &subject);
1690 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1691 short_commit_name(commit), subject_len, subject);
1692 unuse_commit_buffer(commit, commit_buffer);
1694 return 0;
1697 static int create_seq_dir(void)
1699 if (file_exists(git_path_seq_dir())) {
1700 error(_("a cherry-pick or revert is already in progress"));
1701 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1702 return -1;
1703 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1704 return error_errno(_("could not create sequencer directory '%s'"),
1705 git_path_seq_dir());
1706 return 0;
1709 static int save_head(const char *head)
1711 static struct lock_file head_lock;
1712 struct strbuf buf = STRBUF_INIT;
1713 int fd;
1714 ssize_t written;
1716 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1717 if (fd < 0) {
1718 rollback_lock_file(&head_lock);
1719 return error_errno(_("could not lock HEAD"));
1721 strbuf_addf(&buf, "%s\n", head);
1722 written = write_in_full(fd, buf.buf, buf.len);
1723 strbuf_release(&buf);
1724 if (written < 0) {
1725 rollback_lock_file(&head_lock);
1726 return error_errno(_("could not write to '%s'"),
1727 git_path_head_file());
1729 if (commit_lock_file(&head_lock) < 0) {
1730 rollback_lock_file(&head_lock);
1731 return error(_("failed to finalize '%s'."), git_path_head_file());
1733 return 0;
1736 static int rollback_is_safe(void)
1738 struct strbuf sb = STRBUF_INIT;
1739 struct object_id expected_head, actual_head;
1741 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1742 strbuf_trim(&sb);
1743 if (get_oid_hex(sb.buf, &expected_head)) {
1744 strbuf_release(&sb);
1745 die(_("could not parse %s"), git_path_abort_safety_file());
1747 strbuf_release(&sb);
1749 else if (errno == ENOENT)
1750 oidclr(&expected_head);
1751 else
1752 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1754 if (get_oid("HEAD", &actual_head))
1755 oidclr(&actual_head);
1757 return !oidcmp(&actual_head, &expected_head);
1760 static int reset_for_rollback(const struct object_id *oid)
1762 const char *argv[4]; /* reset --merge <arg> + NULL */
1764 argv[0] = "reset";
1765 argv[1] = "--merge";
1766 argv[2] = oid_to_hex(oid);
1767 argv[3] = NULL;
1768 return run_command_v_opt(argv, RUN_GIT_CMD);
1771 static int rollback_single_pick(void)
1773 struct object_id head_oid;
1775 if (!file_exists(git_path_cherry_pick_head()) &&
1776 !file_exists(git_path_revert_head()))
1777 return error(_("no cherry-pick or revert in progress"));
1778 if (read_ref_full("HEAD", 0, &head_oid, NULL))
1779 return error(_("cannot resolve HEAD"));
1780 if (is_null_oid(&head_oid))
1781 return error(_("cannot abort from a branch yet to be born"));
1782 return reset_for_rollback(&head_oid);
1785 int sequencer_rollback(struct replay_opts *opts)
1787 FILE *f;
1788 struct object_id oid;
1789 struct strbuf buf = STRBUF_INIT;
1790 const char *p;
1792 f = fopen(git_path_head_file(), "r");
1793 if (!f && errno == ENOENT) {
1795 * There is no multiple-cherry-pick in progress.
1796 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1797 * a single-cherry-pick in progress, abort that.
1799 return rollback_single_pick();
1801 if (!f)
1802 return error_errno(_("cannot open '%s'"), git_path_head_file());
1803 if (strbuf_getline_lf(&buf, f)) {
1804 error(_("cannot read '%s': %s"), git_path_head_file(),
1805 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1806 fclose(f);
1807 goto fail;
1809 fclose(f);
1810 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
1811 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1812 git_path_head_file());
1813 goto fail;
1815 if (is_null_oid(&oid)) {
1816 error(_("cannot abort from a branch yet to be born"));
1817 goto fail;
1820 if (!rollback_is_safe()) {
1821 /* Do not error, just do not rollback */
1822 warning(_("You seem to have moved HEAD. "
1823 "Not rewinding, check your HEAD!"));
1824 } else
1825 if (reset_for_rollback(&oid))
1826 goto fail;
1827 strbuf_release(&buf);
1828 return sequencer_remove_state(opts);
1829 fail:
1830 strbuf_release(&buf);
1831 return -1;
1834 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1836 static struct lock_file todo_lock;
1837 const char *todo_path = get_todo_path(opts);
1838 int next = todo_list->current, offset, fd;
1841 * rebase -i writes "git-rebase-todo" without the currently executing
1842 * command, appending it to "done" instead.
1844 if (is_rebase_i(opts))
1845 next++;
1847 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1848 if (fd < 0)
1849 return error_errno(_("could not lock '%s'"), todo_path);
1850 offset = next < todo_list->nr ?
1851 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1852 if (write_in_full(fd, todo_list->buf.buf + offset,
1853 todo_list->buf.len - offset) < 0)
1854 return error_errno(_("could not write to '%s'"), todo_path);
1855 if (commit_lock_file(&todo_lock) < 0)
1856 return error(_("failed to finalize '%s'."), todo_path);
1858 if (is_rebase_i(opts)) {
1859 const char *done_path = rebase_path_done();
1860 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1861 int prev_offset = !next ? 0 :
1862 todo_list->items[next - 1].offset_in_buf;
1864 if (fd >= 0 && offset > prev_offset &&
1865 write_in_full(fd, todo_list->buf.buf + prev_offset,
1866 offset - prev_offset) < 0) {
1867 close(fd);
1868 return error_errno(_("could not write to '%s'"),
1869 done_path);
1871 if (fd >= 0)
1872 close(fd);
1874 return 0;
1877 static int save_opts(struct replay_opts *opts)
1879 const char *opts_file = git_path_opts_file();
1880 int res = 0;
1882 if (opts->no_commit)
1883 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1884 if (opts->edit)
1885 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1886 if (opts->signoff)
1887 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1888 if (opts->record_origin)
1889 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1890 if (opts->allow_ff)
1891 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1892 if (opts->mainline) {
1893 struct strbuf buf = STRBUF_INIT;
1894 strbuf_addf(&buf, "%d", opts->mainline);
1895 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1896 strbuf_release(&buf);
1898 if (opts->strategy)
1899 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1900 if (opts->gpg_sign)
1901 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1902 if (opts->xopts) {
1903 int i;
1904 for (i = 0; i < opts->xopts_nr; i++)
1905 res |= git_config_set_multivar_in_file_gently(opts_file,
1906 "options.strategy-option",
1907 opts->xopts[i], "^$", 0);
1909 if (opts->allow_rerere_auto)
1910 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
1911 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
1912 "true" : "false");
1913 return res;
1916 static int make_patch(struct commit *commit, struct replay_opts *opts)
1918 struct strbuf buf = STRBUF_INIT;
1919 struct rev_info log_tree_opt;
1920 const char *subject, *p;
1921 int res = 0;
1923 p = short_commit_name(commit);
1924 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1925 return -1;
1927 strbuf_addf(&buf, "%s/patch", get_dir(opts));
1928 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1929 init_revisions(&log_tree_opt, NULL);
1930 log_tree_opt.abbrev = 0;
1931 log_tree_opt.diff = 1;
1932 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1933 log_tree_opt.disable_stdin = 1;
1934 log_tree_opt.no_commit_id = 1;
1935 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1936 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1937 if (!log_tree_opt.diffopt.file)
1938 res |= error_errno(_("could not open '%s'"), buf.buf);
1939 else {
1940 res |= log_tree_commit(&log_tree_opt, commit);
1941 fclose(log_tree_opt.diffopt.file);
1943 strbuf_reset(&buf);
1945 strbuf_addf(&buf, "%s/message", get_dir(opts));
1946 if (!file_exists(buf.buf)) {
1947 const char *commit_buffer = get_commit_buffer(commit, NULL);
1948 find_commit_subject(commit_buffer, &subject);
1949 res |= write_message(subject, strlen(subject), buf.buf, 1);
1950 unuse_commit_buffer(commit, commit_buffer);
1952 strbuf_release(&buf);
1954 return res;
1957 static int intend_to_amend(void)
1959 struct object_id head;
1960 char *p;
1962 if (get_oid("HEAD", &head))
1963 return error(_("cannot read HEAD"));
1965 p = oid_to_hex(&head);
1966 return write_message(p, strlen(p), rebase_path_amend(), 1);
1969 static int error_with_patch(struct commit *commit,
1970 const char *subject, int subject_len,
1971 struct replay_opts *opts, int exit_code, int to_amend)
1973 if (make_patch(commit, opts))
1974 return -1;
1976 if (to_amend) {
1977 if (intend_to_amend())
1978 return -1;
1980 fprintf(stderr, "You can amend the commit now, with\n"
1981 "\n"
1982 " git commit --amend %s\n"
1983 "\n"
1984 "Once you are satisfied with your changes, run\n"
1985 "\n"
1986 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
1987 } else if (exit_code)
1988 fprintf(stderr, "Could not apply %s... %.*s\n",
1989 short_commit_name(commit), subject_len, subject);
1991 return exit_code;
1994 static int error_failed_squash(struct commit *commit,
1995 struct replay_opts *opts, int subject_len, const char *subject)
1997 if (rename(rebase_path_squash_msg(), rebase_path_message()))
1998 return error(_("could not rename '%s' to '%s'"),
1999 rebase_path_squash_msg(), rebase_path_message());
2000 unlink(rebase_path_fixup_msg());
2001 unlink(git_path_merge_msg());
2002 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2003 return error(_("could not copy '%s' to '%s'"),
2004 rebase_path_message(), git_path_merge_msg());
2005 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2008 static int do_exec(const char *command_line)
2010 struct argv_array child_env = ARGV_ARRAY_INIT;
2011 const char *child_argv[] = { NULL, NULL };
2012 int dirty, status;
2014 fprintf(stderr, "Executing: %s\n", command_line);
2015 child_argv[0] = command_line;
2016 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2017 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2018 child_env.argv);
2020 /* force re-reading of the cache */
2021 if (discard_cache() < 0 || read_cache() < 0)
2022 return error(_("could not read index"));
2024 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2026 if (status) {
2027 warning(_("execution failed: %s\n%s"
2028 "You can fix the problem, and then run\n"
2029 "\n"
2030 " git rebase --continue\n"
2031 "\n"),
2032 command_line,
2033 dirty ? N_("and made changes to the index and/or the "
2034 "working tree\n") : "");
2035 if (status == 127)
2036 /* command not found */
2037 status = 1;
2038 } else if (dirty) {
2039 warning(_("execution succeeded: %s\nbut "
2040 "left changes to the index and/or the working tree\n"
2041 "Commit or stash your changes, and then run\n"
2042 "\n"
2043 " git rebase --continue\n"
2044 "\n"), command_line);
2045 status = 1;
2048 argv_array_clear(&child_env);
2050 return status;
2053 static int is_final_fixup(struct todo_list *todo_list)
2055 int i = todo_list->current;
2057 if (!is_fixup(todo_list->items[i].command))
2058 return 0;
2060 while (++i < todo_list->nr)
2061 if (is_fixup(todo_list->items[i].command))
2062 return 0;
2063 else if (!is_noop(todo_list->items[i].command))
2064 break;
2065 return 1;
2068 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2070 int i;
2072 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2073 if (!is_noop(todo_list->items[i].command))
2074 return todo_list->items[i].command;
2076 return -1;
2079 static int apply_autostash(struct replay_opts *opts)
2081 struct strbuf stash_sha1 = STRBUF_INIT;
2082 struct child_process child = CHILD_PROCESS_INIT;
2083 int ret = 0;
2085 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2086 strbuf_release(&stash_sha1);
2087 return 0;
2089 strbuf_trim(&stash_sha1);
2091 child.git_cmd = 1;
2092 child.no_stdout = 1;
2093 child.no_stderr = 1;
2094 argv_array_push(&child.args, "stash");
2095 argv_array_push(&child.args, "apply");
2096 argv_array_push(&child.args, stash_sha1.buf);
2097 if (!run_command(&child))
2098 fprintf(stderr, _("Applied autostash.\n"));
2099 else {
2100 struct child_process store = CHILD_PROCESS_INIT;
2102 store.git_cmd = 1;
2103 argv_array_push(&store.args, "stash");
2104 argv_array_push(&store.args, "store");
2105 argv_array_push(&store.args, "-m");
2106 argv_array_push(&store.args, "autostash");
2107 argv_array_push(&store.args, "-q");
2108 argv_array_push(&store.args, stash_sha1.buf);
2109 if (run_command(&store))
2110 ret = error(_("cannot store %s"), stash_sha1.buf);
2111 else
2112 fprintf(stderr,
2113 _("Applying autostash resulted in conflicts.\n"
2114 "Your changes are safe in the stash.\n"
2115 "You can run \"git stash pop\" or"
2116 " \"git stash drop\" at any time.\n"));
2119 strbuf_release(&stash_sha1);
2120 return ret;
2123 static const char *reflog_message(struct replay_opts *opts,
2124 const char *sub_action, const char *fmt, ...)
2126 va_list ap;
2127 static struct strbuf buf = STRBUF_INIT;
2129 va_start(ap, fmt);
2130 strbuf_reset(&buf);
2131 strbuf_addstr(&buf, action_name(opts));
2132 if (sub_action)
2133 strbuf_addf(&buf, " (%s)", sub_action);
2134 if (fmt) {
2135 strbuf_addstr(&buf, ": ");
2136 strbuf_vaddf(&buf, fmt, ap);
2138 va_end(ap);
2140 return buf.buf;
2143 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2145 int res = 0;
2147 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2148 if (opts->allow_ff)
2149 assert(!(opts->signoff || opts->no_commit ||
2150 opts->record_origin || opts->edit));
2151 if (read_and_refresh_cache(opts))
2152 return -1;
2154 while (todo_list->current < todo_list->nr) {
2155 struct todo_item *item = todo_list->items + todo_list->current;
2156 if (save_todo(todo_list, opts))
2157 return -1;
2158 if (is_rebase_i(opts)) {
2159 if (item->command != TODO_COMMENT) {
2160 FILE *f = fopen(rebase_path_msgnum(), "w");
2162 todo_list->done_nr++;
2164 if (f) {
2165 fprintf(f, "%d\n", todo_list->done_nr);
2166 fclose(f);
2168 fprintf(stderr, "Rebasing (%d/%d)%s",
2169 todo_list->done_nr,
2170 todo_list->total_nr,
2171 opts->verbose ? "\n" : "\r");
2173 unlink(rebase_path_message());
2174 unlink(rebase_path_author_script());
2175 unlink(rebase_path_stopped_sha());
2176 unlink(rebase_path_amend());
2178 if (item->command <= TODO_SQUASH) {
2179 if (is_rebase_i(opts))
2180 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2181 command_to_string(item->command), NULL),
2183 res = do_pick_commit(item->command, item->commit,
2184 opts, is_final_fixup(todo_list));
2185 if (is_rebase_i(opts) && res < 0) {
2186 /* Reschedule */
2187 todo_list->current--;
2188 if (save_todo(todo_list, opts))
2189 return -1;
2191 if (item->command == TODO_EDIT) {
2192 struct commit *commit = item->commit;
2193 if (!res)
2194 fprintf(stderr,
2195 _("Stopped at %s... %.*s\n"),
2196 short_commit_name(commit),
2197 item->arg_len, item->arg);
2198 return error_with_patch(commit,
2199 item->arg, item->arg_len, opts, res,
2200 !res);
2202 if (is_rebase_i(opts) && !res)
2203 record_in_rewritten(&item->commit->object.oid,
2204 peek_command(todo_list, 1));
2205 if (res && is_fixup(item->command)) {
2206 if (res == 1)
2207 intend_to_amend();
2208 return error_failed_squash(item->commit, opts,
2209 item->arg_len, item->arg);
2210 } else if (res && is_rebase_i(opts))
2211 return res | error_with_patch(item->commit,
2212 item->arg, item->arg_len, opts, res,
2213 item->command == TODO_REWORD);
2214 } else if (item->command == TODO_EXEC) {
2215 char *end_of_arg = (char *)(item->arg + item->arg_len);
2216 int saved = *end_of_arg;
2217 struct stat st;
2219 *end_of_arg = '\0';
2220 res = do_exec(item->arg);
2221 *end_of_arg = saved;
2223 /* Reread the todo file if it has changed. */
2224 if (res)
2225 ; /* fall through */
2226 else if (stat(get_todo_path(opts), &st))
2227 res = error_errno(_("could not stat '%s'"),
2228 get_todo_path(opts));
2229 else if (match_stat_data(&todo_list->stat, &st)) {
2230 todo_list_release(todo_list);
2231 if (read_populate_todo(todo_list, opts))
2232 res = -1; /* message was printed */
2233 /* `current` will be incremented below */
2234 todo_list->current = -1;
2236 } else if (!is_noop(item->command))
2237 return error(_("unknown command %d"), item->command);
2239 todo_list->current++;
2240 if (res)
2241 return res;
2244 if (is_rebase_i(opts)) {
2245 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2246 struct stat st;
2248 /* Stopped in the middle, as planned? */
2249 if (todo_list->current < todo_list->nr)
2250 return 0;
2252 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2253 starts_with(head_ref.buf, "refs/")) {
2254 const char *msg;
2255 struct object_id head, orig;
2256 int res;
2258 if (get_oid("HEAD", &head)) {
2259 res = error(_("cannot read HEAD"));
2260 cleanup_head_ref:
2261 strbuf_release(&head_ref);
2262 strbuf_release(&buf);
2263 return res;
2265 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2266 get_oid_hex(buf.buf, &orig)) {
2267 res = error(_("could not read orig-head"));
2268 goto cleanup_head_ref;
2270 strbuf_reset(&buf);
2271 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2272 res = error(_("could not read 'onto'"));
2273 goto cleanup_head_ref;
2275 msg = reflog_message(opts, "finish", "%s onto %s",
2276 head_ref.buf, buf.buf);
2277 if (update_ref(msg, head_ref.buf, &head, &orig,
2278 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2279 res = error(_("could not update %s"),
2280 head_ref.buf);
2281 goto cleanup_head_ref;
2283 msg = reflog_message(opts, "finish", "returning to %s",
2284 head_ref.buf);
2285 if (create_symref("HEAD", head_ref.buf, msg)) {
2286 res = error(_("could not update HEAD to %s"),
2287 head_ref.buf);
2288 goto cleanup_head_ref;
2290 strbuf_reset(&buf);
2293 if (opts->verbose) {
2294 struct rev_info log_tree_opt;
2295 struct object_id orig, head;
2297 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2298 init_revisions(&log_tree_opt, NULL);
2299 log_tree_opt.diff = 1;
2300 log_tree_opt.diffopt.output_format =
2301 DIFF_FORMAT_DIFFSTAT;
2302 log_tree_opt.disable_stdin = 1;
2304 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2305 !get_oid(buf.buf, &orig) &&
2306 !get_oid("HEAD", &head)) {
2307 diff_tree_oid(&orig, &head, "",
2308 &log_tree_opt.diffopt);
2309 log_tree_diff_flush(&log_tree_opt);
2312 flush_rewritten_pending();
2313 if (!stat(rebase_path_rewritten_list(), &st) &&
2314 st.st_size > 0) {
2315 struct child_process child = CHILD_PROCESS_INIT;
2316 const char *post_rewrite_hook =
2317 find_hook("post-rewrite");
2319 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2320 child.git_cmd = 1;
2321 argv_array_push(&child.args, "notes");
2322 argv_array_push(&child.args, "copy");
2323 argv_array_push(&child.args, "--for-rewrite=rebase");
2324 /* we don't care if this copying failed */
2325 run_command(&child);
2327 if (post_rewrite_hook) {
2328 struct child_process hook = CHILD_PROCESS_INIT;
2330 hook.in = open(rebase_path_rewritten_list(),
2331 O_RDONLY);
2332 hook.stdout_to_stderr = 1;
2333 argv_array_push(&hook.args, post_rewrite_hook);
2334 argv_array_push(&hook.args, "rebase");
2335 /* we don't care if this hook failed */
2336 run_command(&hook);
2339 apply_autostash(opts);
2341 fprintf(stderr, "Successfully rebased and updated %s.\n",
2342 head_ref.buf);
2344 strbuf_release(&buf);
2345 strbuf_release(&head_ref);
2349 * Sequence of picks finished successfully; cleanup by
2350 * removing the .git/sequencer directory
2352 return sequencer_remove_state(opts);
2355 static int continue_single_pick(void)
2357 const char *argv[] = { "commit", NULL };
2359 if (!file_exists(git_path_cherry_pick_head()) &&
2360 !file_exists(git_path_revert_head()))
2361 return error(_("no cherry-pick or revert in progress"));
2362 return run_command_v_opt(argv, RUN_GIT_CMD);
2365 static int commit_staged_changes(struct replay_opts *opts)
2367 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2369 if (has_unstaged_changes(1))
2370 return error(_("cannot rebase: You have unstaged changes."));
2371 if (!has_uncommitted_changes(0)) {
2372 const char *cherry_pick_head = git_path_cherry_pick_head();
2374 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2375 return error(_("could not remove CHERRY_PICK_HEAD"));
2376 return 0;
2379 if (file_exists(rebase_path_amend())) {
2380 struct strbuf rev = STRBUF_INIT;
2381 struct object_id head, to_amend;
2383 if (get_oid("HEAD", &head))
2384 return error(_("cannot amend non-existing commit"));
2385 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2386 return error(_("invalid file: '%s'"), rebase_path_amend());
2387 if (get_oid_hex(rev.buf, &to_amend))
2388 return error(_("invalid contents: '%s'"),
2389 rebase_path_amend());
2390 if (oidcmp(&head, &to_amend))
2391 return error(_("\nYou have uncommitted changes in your "
2392 "working tree. Please, commit them\n"
2393 "first and then run 'git rebase "
2394 "--continue' again."));
2396 strbuf_release(&rev);
2397 flags |= AMEND_MSG;
2400 if (run_git_commit(rebase_path_message(), opts, flags))
2401 return error(_("could not commit staged changes."));
2402 unlink(rebase_path_amend());
2403 return 0;
2406 int sequencer_continue(struct replay_opts *opts)
2408 struct todo_list todo_list = TODO_LIST_INIT;
2409 int res;
2411 if (read_and_refresh_cache(opts))
2412 return -1;
2414 if (is_rebase_i(opts)) {
2415 if (commit_staged_changes(opts))
2416 return -1;
2417 } else if (!file_exists(get_todo_path(opts)))
2418 return continue_single_pick();
2419 if (read_populate_opts(opts))
2420 return -1;
2421 if ((res = read_populate_todo(&todo_list, opts)))
2422 goto release_todo_list;
2424 if (!is_rebase_i(opts)) {
2425 /* Verify that the conflict has been resolved */
2426 if (file_exists(git_path_cherry_pick_head()) ||
2427 file_exists(git_path_revert_head())) {
2428 res = continue_single_pick();
2429 if (res)
2430 goto release_todo_list;
2432 if (index_differs_from("HEAD", NULL, 0)) {
2433 res = error_dirty_index(opts);
2434 goto release_todo_list;
2436 todo_list.current++;
2437 } else if (file_exists(rebase_path_stopped_sha())) {
2438 struct strbuf buf = STRBUF_INIT;
2439 struct object_id oid;
2441 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2442 !get_oid_committish(buf.buf, &oid))
2443 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2444 strbuf_release(&buf);
2447 res = pick_commits(&todo_list, opts);
2448 release_todo_list:
2449 todo_list_release(&todo_list);
2450 return res;
2453 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2455 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2456 return do_pick_commit(opts->action == REPLAY_PICK ?
2457 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2460 int sequencer_pick_revisions(struct replay_opts *opts)
2462 struct todo_list todo_list = TODO_LIST_INIT;
2463 struct object_id oid;
2464 int i, res;
2466 assert(opts->revs);
2467 if (read_and_refresh_cache(opts))
2468 return -1;
2470 for (i = 0; i < opts->revs->pending.nr; i++) {
2471 struct object_id oid;
2472 const char *name = opts->revs->pending.objects[i].name;
2474 /* This happens when using --stdin. */
2475 if (!strlen(name))
2476 continue;
2478 if (!get_oid(name, &oid)) {
2479 if (!lookup_commit_reference_gently(&oid, 1)) {
2480 enum object_type type = sha1_object_info(oid.hash, NULL);
2481 return error(_("%s: can't cherry-pick a %s"),
2482 name, typename(type));
2484 } else
2485 return error(_("%s: bad revision"), name);
2489 * If we were called as "git cherry-pick <commit>", just
2490 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2491 * REVERT_HEAD, and don't touch the sequencer state.
2492 * This means it is possible to cherry-pick in the middle
2493 * of a cherry-pick sequence.
2495 if (opts->revs->cmdline.nr == 1 &&
2496 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2497 opts->revs->no_walk &&
2498 !opts->revs->cmdline.rev->flags) {
2499 struct commit *cmit;
2500 if (prepare_revision_walk(opts->revs))
2501 return error(_("revision walk setup failed"));
2502 cmit = get_revision(opts->revs);
2503 if (!cmit || get_revision(opts->revs))
2504 return error("BUG: expected exactly one commit from walk");
2505 return single_pick(cmit, opts);
2509 * Start a new cherry-pick/ revert sequence; but
2510 * first, make sure that an existing one isn't in
2511 * progress
2514 if (walk_revs_populate_todo(&todo_list, opts) ||
2515 create_seq_dir() < 0)
2516 return -1;
2517 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2518 return error(_("can't revert as initial commit"));
2519 if (save_head(oid_to_hex(&oid)))
2520 return -1;
2521 if (save_opts(opts))
2522 return -1;
2523 update_abort_safety_file();
2524 res = pick_commits(&todo_list, opts);
2525 todo_list_release(&todo_list);
2526 return res;
2529 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2531 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2532 struct strbuf sob = STRBUF_INIT;
2533 int has_footer;
2535 strbuf_addstr(&sob, sign_off_header);
2536 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2537 getenv("GIT_COMMITTER_EMAIL")));
2538 strbuf_addch(&sob, '\n');
2540 if (!ignore_footer)
2541 strbuf_complete_line(msgbuf);
2544 * If the whole message buffer is equal to the sob, pretend that we
2545 * found a conforming footer with a matching sob
2547 if (msgbuf->len - ignore_footer == sob.len &&
2548 !strncmp(msgbuf->buf, sob.buf, sob.len))
2549 has_footer = 3;
2550 else
2551 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2553 if (!has_footer) {
2554 const char *append_newlines = NULL;
2555 size_t len = msgbuf->len - ignore_footer;
2557 if (!len) {
2559 * The buffer is completely empty. Leave foom for
2560 * the title and body to be filled in by the user.
2562 append_newlines = "\n\n";
2563 } else if (len == 1) {
2565 * Buffer contains a single newline. Add another
2566 * so that we leave room for the title and body.
2568 append_newlines = "\n";
2569 } else if (msgbuf->buf[len - 2] != '\n') {
2571 * Buffer ends with a single newline. Add another
2572 * so that there is an empty line between the message
2573 * body and the sob.
2575 append_newlines = "\n";
2576 } /* else, the buffer already ends with two newlines. */
2578 if (append_newlines)
2579 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2580 append_newlines, strlen(append_newlines));
2583 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2584 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2585 sob.buf, sob.len);
2587 strbuf_release(&sob);
2590 int sequencer_make_script(int keep_empty, FILE *out,
2591 int argc, const char **argv)
2593 char *format = NULL;
2594 struct pretty_print_context pp = {0};
2595 struct strbuf buf = STRBUF_INIT;
2596 struct rev_info revs;
2597 struct commit *commit;
2599 init_revisions(&revs, NULL);
2600 revs.verbose_header = 1;
2601 revs.max_parents = 1;
2602 revs.cherry_pick = 1;
2603 revs.limited = 1;
2604 revs.reverse = 1;
2605 revs.right_only = 1;
2606 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2607 revs.topo_order = 1;
2609 revs.pretty_given = 1;
2610 git_config_get_string("rebase.instructionFormat", &format);
2611 if (!format || !*format) {
2612 free(format);
2613 format = xstrdup("%s");
2615 get_commit_format(format, &revs);
2616 free(format);
2617 pp.fmt = revs.commit_format;
2618 pp.output_encoding = get_log_output_encoding();
2620 if (setup_revisions(argc, argv, &revs, NULL) > 1)
2621 return error(_("make_script: unhandled options"));
2623 if (prepare_revision_walk(&revs) < 0)
2624 return error(_("make_script: error preparing revisions"));
2626 while ((commit = get_revision(&revs))) {
2627 strbuf_reset(&buf);
2628 if (!keep_empty && is_original_commit_empty(commit))
2629 strbuf_addf(&buf, "%c ", comment_line_char);
2630 strbuf_addf(&buf, "pick %s ", oid_to_hex(&commit->object.oid));
2631 pretty_print_commit(&pp, commit, &buf);
2632 strbuf_addch(&buf, '\n');
2633 fputs(buf.buf, out);
2635 strbuf_release(&buf);
2636 return 0;
2640 int transform_todo_ids(int shorten_ids)
2642 const char *todo_file = rebase_path_todo();
2643 struct todo_list todo_list = TODO_LIST_INIT;
2644 int fd, res, i;
2645 FILE *out;
2647 strbuf_reset(&todo_list.buf);
2648 fd = open(todo_file, O_RDONLY);
2649 if (fd < 0)
2650 return error_errno(_("could not open '%s'"), todo_file);
2651 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2652 close(fd);
2653 return error(_("could not read '%s'."), todo_file);
2655 close(fd);
2657 res = parse_insn_buffer(todo_list.buf.buf, &todo_list);
2658 if (res) {
2659 todo_list_release(&todo_list);
2660 return error(_("unusable todo list: '%s'"), todo_file);
2663 out = fopen(todo_file, "w");
2664 if (!out) {
2665 todo_list_release(&todo_list);
2666 return error(_("unable to open '%s' for writing"), todo_file);
2668 for (i = 0; i < todo_list.nr; i++) {
2669 struct todo_item *item = todo_list.items + i;
2670 int bol = item->offset_in_buf;
2671 const char *p = todo_list.buf.buf + bol;
2672 int eol = i + 1 < todo_list.nr ?
2673 todo_list.items[i + 1].offset_in_buf :
2674 todo_list.buf.len;
2676 if (item->command >= TODO_EXEC && item->command != TODO_DROP)
2677 fwrite(p, eol - bol, 1, out);
2678 else {
2679 const char *id = shorten_ids ?
2680 short_commit_name(item->commit) :
2681 oid_to_hex(&item->commit->object.oid);
2682 int len;
2684 p += strspn(p, " \t"); /* left-trim command */
2685 len = strcspn(p, " \t"); /* length of command */
2687 fprintf(out, "%.*s %s %.*s\n",
2688 len, p, id, item->arg_len, item->arg);
2691 fclose(out);
2692 todo_list_release(&todo_list);
2693 return 0;
2696 enum check_level {
2697 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
2700 static enum check_level get_missing_commit_check_level(void)
2702 const char *value;
2704 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
2705 !strcasecmp("ignore", value))
2706 return CHECK_IGNORE;
2707 if (!strcasecmp("warn", value))
2708 return CHECK_WARN;
2709 if (!strcasecmp("error", value))
2710 return CHECK_ERROR;
2711 warning(_("unrecognized setting %s for option "
2712 "rebase.missingCommitsCheck. Ignoring."), value);
2713 return CHECK_IGNORE;
2717 * Check if the user dropped some commits by mistake
2718 * Behaviour determined by rebase.missingCommitsCheck.
2719 * Check if there is an unrecognized command or a
2720 * bad SHA-1 in a command.
2722 int check_todo_list(void)
2724 enum check_level check_level = get_missing_commit_check_level();
2725 struct strbuf todo_file = STRBUF_INIT;
2726 struct todo_list todo_list = TODO_LIST_INIT;
2727 struct strbuf missing = STRBUF_INIT;
2728 int advise_to_edit_todo = 0, res = 0, fd, i;
2730 strbuf_addstr(&todo_file, rebase_path_todo());
2731 fd = open(todo_file.buf, O_RDONLY);
2732 if (fd < 0) {
2733 res = error_errno(_("could not open '%s'"), todo_file.buf);
2734 goto leave_check;
2736 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2737 close(fd);
2738 res = error(_("could not read '%s'."), todo_file.buf);
2739 goto leave_check;
2741 close(fd);
2742 advise_to_edit_todo = res =
2743 parse_insn_buffer(todo_list.buf.buf, &todo_list);
2745 if (res || check_level == CHECK_IGNORE)
2746 goto leave_check;
2748 /* Mark the commits in git-rebase-todo as seen */
2749 for (i = 0; i < todo_list.nr; i++) {
2750 struct commit *commit = todo_list.items[i].commit;
2751 if (commit)
2752 commit->util = (void *)1;
2755 todo_list_release(&todo_list);
2756 strbuf_addstr(&todo_file, ".backup");
2757 fd = open(todo_file.buf, O_RDONLY);
2758 if (fd < 0) {
2759 res = error_errno(_("could not open '%s'"), todo_file.buf);
2760 goto leave_check;
2762 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2763 close(fd);
2764 res = error(_("could not read '%s'."), todo_file.buf);
2765 goto leave_check;
2767 close(fd);
2768 strbuf_release(&todo_file);
2769 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
2771 /* Find commits in git-rebase-todo.backup yet unseen */
2772 for (i = todo_list.nr - 1; i >= 0; i--) {
2773 struct todo_item *item = todo_list.items + i;
2774 struct commit *commit = item->commit;
2775 if (commit && !commit->util) {
2776 strbuf_addf(&missing, " - %s %.*s\n",
2777 short_commit_name(commit),
2778 item->arg_len, item->arg);
2779 commit->util = (void *)1;
2783 /* Warn about missing commits */
2784 if (!missing.len)
2785 goto leave_check;
2787 if (check_level == CHECK_ERROR)
2788 advise_to_edit_todo = res = 1;
2790 fprintf(stderr,
2791 _("Warning: some commits may have been dropped accidentally.\n"
2792 "Dropped commits (newer to older):\n"));
2794 /* Make the list user-friendly and display */
2795 fputs(missing.buf, stderr);
2796 strbuf_release(&missing);
2798 fprintf(stderr, _("To avoid this message, use \"drop\" to "
2799 "explicitly remove a commit.\n\n"
2800 "Use 'git config rebase.missingCommitsCheck' to change "
2801 "the level of warnings.\n"
2802 "The possible behaviours are: ignore, warn, error.\n\n"));
2804 leave_check:
2805 strbuf_release(&todo_file);
2806 todo_list_release(&todo_list);
2808 if (advise_to_edit_todo)
2809 fprintf(stderr,
2810 _("You can fix this with 'git rebase --edit-todo' "
2811 "and then run 'git rebase --continue'.\n"
2812 "Or you can abort the rebase with 'git rebase"
2813 " --abort'.\n"));
2815 return res;
2818 /* skip picking commits whose parents are unchanged */
2819 int skip_unnecessary_picks(void)
2821 const char *todo_file = rebase_path_todo();
2822 struct strbuf buf = STRBUF_INIT;
2823 struct todo_list todo_list = TODO_LIST_INIT;
2824 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
2825 int fd, i;
2827 if (!read_oneliner(&buf, rebase_path_onto(), 0))
2828 return error(_("could not read 'onto'"));
2829 if (get_oid(buf.buf, &onto_oid)) {
2830 strbuf_release(&buf);
2831 return error(_("need a HEAD to fixup"));
2833 strbuf_release(&buf);
2835 fd = open(todo_file, O_RDONLY);
2836 if (fd < 0) {
2837 return error_errno(_("could not open '%s'"), todo_file);
2839 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2840 close(fd);
2841 return error(_("could not read '%s'."), todo_file);
2843 close(fd);
2844 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2845 todo_list_release(&todo_list);
2846 return -1;
2849 for (i = 0; i < todo_list.nr; i++) {
2850 struct todo_item *item = todo_list.items + i;
2852 if (item->command >= TODO_NOOP)
2853 continue;
2854 if (item->command != TODO_PICK)
2855 break;
2856 if (parse_commit(item->commit)) {
2857 todo_list_release(&todo_list);
2858 return error(_("could not parse commit '%s'"),
2859 oid_to_hex(&item->commit->object.oid));
2861 if (!item->commit->parents)
2862 break; /* root commit */
2863 if (item->commit->parents->next)
2864 break; /* merge commit */
2865 parent_oid = &item->commit->parents->item->object.oid;
2866 if (hashcmp(parent_oid->hash, oid->hash))
2867 break;
2868 oid = &item->commit->object.oid;
2870 if (i > 0) {
2871 int offset = i < todo_list.nr ?
2872 todo_list.items[i].offset_in_buf : todo_list.buf.len;
2873 const char *done_path = rebase_path_done();
2875 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2876 if (fd < 0) {
2877 error_errno(_("could not open '%s' for writing"),
2878 done_path);
2879 todo_list_release(&todo_list);
2880 return -1;
2882 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
2883 error_errno(_("could not write to '%s'"), done_path);
2884 todo_list_release(&todo_list);
2885 close(fd);
2886 return -1;
2888 close(fd);
2890 fd = open(rebase_path_todo(), O_WRONLY, 0666);
2891 if (fd < 0) {
2892 error_errno(_("could not open '%s' for writing"),
2893 rebase_path_todo());
2894 todo_list_release(&todo_list);
2895 return -1;
2897 if (write_in_full(fd, todo_list.buf.buf + offset,
2898 todo_list.buf.len - offset) < 0) {
2899 error_errno(_("could not write to '%s'"),
2900 rebase_path_todo());
2901 close(fd);
2902 todo_list_release(&todo_list);
2903 return -1;
2905 if (ftruncate(fd, todo_list.buf.len - offset) < 0) {
2906 error_errno(_("could not truncate '%s'"),
2907 rebase_path_todo());
2908 todo_list_release(&todo_list);
2909 close(fd);
2910 return -1;
2912 close(fd);
2914 todo_list.current = i;
2915 if (is_fixup(peek_command(&todo_list, 0)))
2916 record_in_rewritten(oid, peek_command(&todo_list, 0));
2919 todo_list_release(&todo_list);
2920 printf("%s\n", oid_to_hex(oid));
2922 return 0;
2925 struct subject2item_entry {
2926 struct hashmap_entry entry;
2927 int i;
2928 char subject[FLEX_ARRAY];
2931 static int subject2item_cmp(const void *fndata,
2932 const struct subject2item_entry *a,
2933 const struct subject2item_entry *b, const void *key)
2935 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
2939 * Rearrange the todo list that has both "pick commit-id msg" and "pick
2940 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
2941 * after the former, and change "pick" to "fixup"/"squash".
2943 * Note that if the config has specified a custom instruction format, each log
2944 * message will have to be retrieved from the commit (as the oneline in the
2945 * script cannot be trusted) in order to normalize the autosquash arrangement.
2947 int rearrange_squash(void)
2949 const char *todo_file = rebase_path_todo();
2950 struct todo_list todo_list = TODO_LIST_INIT;
2951 struct hashmap subject2item;
2952 int res = 0, rearranged = 0, *next, *tail, fd, i;
2953 char **subjects;
2955 fd = open(todo_file, O_RDONLY);
2956 if (fd < 0)
2957 return error_errno(_("could not open '%s'"), todo_file);
2958 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2959 close(fd);
2960 return error(_("could not read '%s'."), todo_file);
2962 close(fd);
2963 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2964 todo_list_release(&todo_list);
2965 return -1;
2969 * The hashmap maps onelines to the respective todo list index.
2971 * If any items need to be rearranged, the next[i] value will indicate
2972 * which item was moved directly after the i'th.
2974 * In that case, last[i] will indicate the index of the latest item to
2975 * be moved to appear after the i'th.
2977 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
2978 NULL, todo_list.nr);
2979 ALLOC_ARRAY(next, todo_list.nr);
2980 ALLOC_ARRAY(tail, todo_list.nr);
2981 ALLOC_ARRAY(subjects, todo_list.nr);
2982 for (i = 0; i < todo_list.nr; i++) {
2983 struct strbuf buf = STRBUF_INIT;
2984 struct todo_item *item = todo_list.items + i;
2985 const char *commit_buffer, *subject, *p;
2986 size_t subject_len;
2987 int i2 = -1;
2988 struct subject2item_entry *entry;
2990 next[i] = tail[i] = -1;
2991 if (item->command >= TODO_EXEC) {
2992 subjects[i] = NULL;
2993 continue;
2996 if (is_fixup(item->command)) {
2997 todo_list_release(&todo_list);
2998 return error(_("the script was already rearranged."));
3001 item->commit->util = item;
3003 parse_commit(item->commit);
3004 commit_buffer = get_commit_buffer(item->commit, NULL);
3005 find_commit_subject(commit_buffer, &subject);
3006 format_subject(&buf, subject, " ");
3007 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3008 unuse_commit_buffer(item->commit, commit_buffer);
3009 if ((skip_prefix(subject, "fixup! ", &p) ||
3010 skip_prefix(subject, "squash! ", &p))) {
3011 struct commit *commit2;
3013 for (;;) {
3014 while (isspace(*p))
3015 p++;
3016 if (!skip_prefix(p, "fixup! ", &p) &&
3017 !skip_prefix(p, "squash! ", &p))
3018 break;
3021 if ((entry = hashmap_get_from_hash(&subject2item,
3022 strhash(p), p)))
3023 /* found by title */
3024 i2 = entry->i;
3025 else if (!strchr(p, ' ') &&
3026 (commit2 =
3027 lookup_commit_reference_by_name(p)) &&
3028 commit2->util)
3029 /* found by commit name */
3030 i2 = (struct todo_item *)commit2->util
3031 - todo_list.items;
3032 else {
3033 /* copy can be a prefix of the commit subject */
3034 for (i2 = 0; i2 < i; i2++)
3035 if (subjects[i2] &&
3036 starts_with(subjects[i2], p))
3037 break;
3038 if (i2 == i)
3039 i2 = -1;
3042 if (i2 >= 0) {
3043 rearranged = 1;
3044 todo_list.items[i].command =
3045 starts_with(subject, "fixup!") ?
3046 TODO_FIXUP : TODO_SQUASH;
3047 if (next[i2] < 0)
3048 next[i2] = i;
3049 else
3050 next[tail[i2]] = i;
3051 tail[i2] = i;
3052 } else if (!hashmap_get_from_hash(&subject2item,
3053 strhash(subject), subject)) {
3054 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3055 entry->i = i;
3056 hashmap_entry_init(entry, strhash(entry->subject));
3057 hashmap_put(&subject2item, entry);
3061 if (rearranged) {
3062 struct strbuf buf = STRBUF_INIT;
3064 for (i = 0; i < todo_list.nr; i++) {
3065 enum todo_command command = todo_list.items[i].command;
3066 int cur = i;
3069 * Initially, all commands are 'pick's. If it is a
3070 * fixup or a squash now, we have rearranged it.
3072 if (is_fixup(command))
3073 continue;
3075 while (cur >= 0) {
3076 int offset = todo_list.items[cur].offset_in_buf;
3077 int end_offset = cur + 1 < todo_list.nr ?
3078 todo_list.items[cur + 1].offset_in_buf :
3079 todo_list.buf.len;
3080 char *bol = todo_list.buf.buf + offset;
3081 char *eol = todo_list.buf.buf + end_offset;
3083 /* replace 'pick', by 'fixup' or 'squash' */
3084 command = todo_list.items[cur].command;
3085 if (is_fixup(command)) {
3086 strbuf_addstr(&buf,
3087 todo_command_info[command].str);
3088 bol += strcspn(bol, " \t");
3091 strbuf_add(&buf, bol, eol - bol);
3093 cur = next[cur];
3097 fd = open(todo_file, O_WRONLY);
3098 if (fd < 0)
3099 res = error_errno(_("could not open '%s'"), todo_file);
3100 else if (write(fd, buf.buf, buf.len) < 0)
3101 res = error_errno(_("could not write to '%s'"), todo_file);
3102 else if (ftruncate(fd, buf.len) < 0)
3103 res = error_errno(_("could not truncate '%s'"),
3104 todo_file);
3105 close(fd);
3106 strbuf_release(&buf);
3109 free(next);
3110 free(tail);
3111 for (i = 0; i < todo_list.nr; i++)
3112 free(subjects[i]);
3113 free(subjects);
3114 hashmap_free(&subject2item, 1);
3115 todo_list_release(&todo_list);
3117 return res;