Merge branch 'ma/t0091-fixup'
[alt-git.git] / sequencer.c
blob7e6c556e0a684d6e9724f90a1be6e34f4ffe2c5f
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "alloc.h"
5 #include "config.h"
6 #include "copy.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "lockfile.h"
11 #include "dir.h"
12 #include "object-file.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
15 #include "object.h"
16 #include "pager.h"
17 #include "commit.h"
18 #include "sequencer.h"
19 #include "tag.h"
20 #include "run-command.h"
21 #include "hook.h"
22 #include "exec-cmd.h"
23 #include "utf8.h"
24 #include "cache-tree.h"
25 #include "diff.h"
26 #include "path.h"
27 #include "revision.h"
28 #include "rerere.h"
29 #include "merge.h"
30 #include "merge-ort.h"
31 #include "merge-ort-wrappers.h"
32 #include "refs.h"
33 #include "sparse-index.h"
34 #include "strvec.h"
35 #include "quote.h"
36 #include "trailer.h"
37 #include "log-tree.h"
38 #include "wt-status.h"
39 #include "hashmap.h"
40 #include "notes-utils.h"
41 #include "sigchain.h"
42 #include "unpack-trees.h"
43 #include "worktree.h"
44 #include "oidmap.h"
45 #include "oidset.h"
46 #include "commit-slab.h"
47 #include "alias.h"
48 #include "commit-reach.h"
49 #include "rebase-interactive.h"
50 #include "reset.h"
51 #include "branch.h"
52 #include "wrapper.h"
54 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
56 static const char sign_off_header[] = "Signed-off-by: ";
57 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
59 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
61 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
63 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
64 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
65 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
66 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
68 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
70 * The file containing rebase commands, comments, and empty lines.
71 * This file is created by "git rebase -i" then edited by the user. As
72 * the lines are processed, they are removed from the front of this
73 * file and written to the tail of 'done'.
75 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
76 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
78 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
81 * The rebase command lines that have already been processed. A line
82 * is moved here when it is first handled, before any associated user
83 * actions.
85 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
87 * The file to keep track of how many commands were already processed (e.g.
88 * for the prompt).
90 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
92 * The file to keep track of how many commands are to be processed in total
93 * (e.g. for the prompt).
95 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
97 * The commit message that is planned to be used for any changes that
98 * need to be committed following a user interaction.
100 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
102 * The file into which is accumulated the suggested commit message for
103 * squash/fixup commands. When the first of a series of squash/fixups
104 * is seen, the file is created and the commit message from the
105 * previous commit and from the first squash/fixup commit are written
106 * to it. The commit message for each subsequent squash/fixup commit
107 * is appended to the file as it is processed.
109 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
111 * If the current series of squash/fixups has not yet included a squash
112 * command, then this file exists and holds the commit message of the
113 * original "pick" commit. (If the series ends without a "squash"
114 * command, then this can be used as the commit message of the combined
115 * commit without opening the editor.)
117 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
119 * This file contains the list fixup/squash commands that have been
120 * accumulated into message-fixup or message-squash so far.
122 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
124 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
125 * GIT_AUTHOR_DATE that will be used for the commit that is currently
126 * being rebased.
128 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
130 * When an "edit" rebase command is being processed, the SHA1 of the
131 * commit to be edited is recorded in this file. When "git rebase
132 * --continue" is executed, if there are any staged changes then they
133 * will be amended to the HEAD commit, but only provided the HEAD
134 * commit is still the commit to be edited. When any other rebase
135 * command is processed, this file is deleted.
137 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
139 * When we stop at a given patch via the "edit" command, this file contains
140 * the commit object name of the corresponding patch.
142 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
144 * For the post-rewrite hook, we make a list of rewritten commits and
145 * their new sha1s. The rewritten-pending list keeps the sha1s of
146 * commits that have been processed, but not committed yet,
147 * e.g. because they are waiting for a 'squash' command.
149 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
150 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
151 "rebase-merge/rewritten-pending")
154 * The path of the file containing the OID of the "squash onto" commit, i.e.
155 * the dummy commit used for `reset [new root]`.
157 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
160 * The path of the file listing refs that need to be deleted after the rebase
161 * finishes. This is used by the `label` command to record the need for cleanup.
163 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
166 * The update-refs file stores a list of refs that will be updated at the end
167 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
168 * update the OIDs for the refs in this file, but the refs are not updated
169 * until the end of the rebase sequence.
171 * rebase_path_update_refs() returns the path to this file for a given
172 * worktree directory. For the current worktree, pass the_repository->gitdir.
174 static char *rebase_path_update_refs(const char *wt_git_dir)
176 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
180 * The following files are written by git-rebase just after parsing the
181 * command-line.
183 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
184 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
185 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
186 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
187 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
188 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
189 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
190 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
191 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
192 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
193 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
194 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
195 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
196 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
197 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
198 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
199 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
202 * A 'struct update_refs_record' represents a value in the update-refs
203 * list. We use a string_list to map refs to these (before, after) pairs.
205 struct update_ref_record {
206 struct object_id before;
207 struct object_id after;
210 static struct update_ref_record *init_update_ref_record(const char *ref)
212 struct update_ref_record *rec;
214 CALLOC_ARRAY(rec, 1);
216 oidcpy(&rec->before, null_oid());
217 oidcpy(&rec->after, null_oid());
219 /* This may fail, but that's fine, we will keep the null OID. */
220 read_ref(ref, &rec->before);
222 return rec;
225 static int git_sequencer_config(const char *k, const char *v,
226 const struct config_context *ctx, void *cb)
228 struct replay_opts *opts = cb;
229 int status;
231 if (!strcmp(k, "commit.cleanup")) {
232 const char *s;
234 status = git_config_string(&s, k, v);
235 if (status)
236 return status;
238 if (!strcmp(s, "verbatim")) {
239 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
240 opts->explicit_cleanup = 1;
241 } else if (!strcmp(s, "whitespace")) {
242 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
243 opts->explicit_cleanup = 1;
244 } else if (!strcmp(s, "strip")) {
245 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
246 opts->explicit_cleanup = 1;
247 } else if (!strcmp(s, "scissors")) {
248 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
249 opts->explicit_cleanup = 1;
250 } else {
251 warning(_("invalid commit message cleanup mode '%s'"),
255 free((char *)s);
256 return status;
259 if (!strcmp(k, "commit.gpgsign")) {
260 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
261 return 0;
264 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
265 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
266 if (ret == 0) {
268 * pull.twohead is allowed to be multi-valued; we only
269 * care about the first value.
271 char *tmp = strchr(opts->default_strategy, ' ');
272 if (tmp)
273 *tmp = '\0';
275 return ret;
278 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
279 opts->commit_use_reference = git_config_bool(k, v);
281 return git_diff_basic_config(k, v, ctx, NULL);
284 void sequencer_init_config(struct replay_opts *opts)
286 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
287 git_config(git_sequencer_config, opts);
290 static inline int is_rebase_i(const struct replay_opts *opts)
292 return opts->action == REPLAY_INTERACTIVE_REBASE;
295 static const char *get_dir(const struct replay_opts *opts)
297 if (is_rebase_i(opts))
298 return rebase_path();
299 return git_path_seq_dir();
302 static const char *get_todo_path(const struct replay_opts *opts)
304 if (is_rebase_i(opts))
305 return rebase_path_todo();
306 return git_path_todo_file();
310 * Returns 0 for non-conforming footer
311 * Returns 1 for conforming footer
312 * Returns 2 when sob exists within conforming footer
313 * Returns 3 when sob exists within conforming footer as last entry
315 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
316 size_t ignore_footer)
318 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
319 struct trailer_info info;
320 size_t i;
321 int found_sob = 0, found_sob_last = 0;
322 char saved_char;
324 opts.no_divider = 1;
326 if (ignore_footer) {
327 saved_char = sb->buf[sb->len - ignore_footer];
328 sb->buf[sb->len - ignore_footer] = '\0';
331 trailer_info_get(&info, sb->buf, &opts);
333 if (ignore_footer)
334 sb->buf[sb->len - ignore_footer] = saved_char;
336 if (info.trailer_start == info.trailer_end)
337 return 0;
339 for (i = 0; i < info.trailer_nr; i++)
340 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
341 found_sob = 1;
342 if (i == info.trailer_nr - 1)
343 found_sob_last = 1;
346 trailer_info_release(&info);
348 if (found_sob_last)
349 return 3;
350 if (found_sob)
351 return 2;
352 return 1;
355 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
357 static struct strbuf buf = STRBUF_INIT;
359 strbuf_reset(&buf);
360 if (opts->gpg_sign)
361 sq_quotef(&buf, "-S%s", opts->gpg_sign);
362 return buf.buf;
365 void replay_opts_release(struct replay_opts *opts)
367 free(opts->gpg_sign);
368 free(opts->reflog_action);
369 free(opts->default_strategy);
370 free(opts->strategy);
371 strvec_clear (&opts->xopts);
372 strbuf_release(&opts->current_fixups);
373 if (opts->revs)
374 release_revisions(opts->revs);
375 free(opts->revs);
378 int sequencer_remove_state(struct replay_opts *opts)
380 struct strbuf buf = STRBUF_INIT;
381 int ret = 0;
383 if (is_rebase_i(opts) &&
384 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
385 char *p = buf.buf;
386 while (*p) {
387 char *eol = strchr(p, '\n');
388 if (eol)
389 *eol = '\0';
390 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
391 warning(_("could not delete '%s'"), p);
392 ret = -1;
394 if (!eol)
395 break;
396 p = eol + 1;
400 strbuf_reset(&buf);
401 strbuf_addstr(&buf, get_dir(opts));
402 if (remove_dir_recursively(&buf, 0))
403 ret = error(_("could not remove '%s'"), buf.buf);
404 strbuf_release(&buf);
406 return ret;
409 static const char *action_name(const struct replay_opts *opts)
411 switch (opts->action) {
412 case REPLAY_REVERT:
413 return N_("revert");
414 case REPLAY_PICK:
415 return N_("cherry-pick");
416 case REPLAY_INTERACTIVE_REBASE:
417 return N_("rebase");
419 die(_("unknown action: %d"), opts->action);
422 struct commit_message {
423 char *parent_label;
424 char *label;
425 char *subject;
426 const char *message;
429 static const char *short_commit_name(struct commit *commit)
431 return repo_find_unique_abbrev(the_repository, &commit->object.oid,
432 DEFAULT_ABBREV);
435 static int get_message(struct commit *commit, struct commit_message *out)
437 const char *abbrev, *subject;
438 int subject_len;
440 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
441 get_commit_output_encoding());
442 abbrev = short_commit_name(commit);
444 subject_len = find_commit_subject(out->message, &subject);
446 out->subject = xmemdupz(subject, subject_len);
447 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
448 out->parent_label = xstrfmt("parent of %s", out->label);
450 return 0;
453 static void free_message(struct commit *commit, struct commit_message *msg)
455 free(msg->parent_label);
456 free(msg->label);
457 free(msg->subject);
458 repo_unuse_commit_buffer(the_repository, commit, msg->message);
461 static void print_advice(struct repository *r, int show_hint,
462 struct replay_opts *opts)
464 char *msg = getenv("GIT_CHERRY_PICK_HELP");
466 if (msg) {
467 advise("%s\n", msg);
469 * A conflict has occurred but the porcelain
470 * (typically rebase --interactive) wants to take care
471 * of the commit itself so remove CHERRY_PICK_HEAD
473 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
474 NULL, 0);
475 return;
478 if (show_hint) {
479 if (opts->no_commit)
480 advise(_("after resolving the conflicts, mark the corrected paths\n"
481 "with 'git add <paths>' or 'git rm <paths>'"));
482 else if (opts->action == REPLAY_PICK)
483 advise(_("After resolving the conflicts, mark them with\n"
484 "\"git add/rm <pathspec>\", then run\n"
485 "\"git cherry-pick --continue\".\n"
486 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
487 "To abort and get back to the state before \"git cherry-pick\",\n"
488 "run \"git cherry-pick --abort\"."));
489 else if (opts->action == REPLAY_REVERT)
490 advise(_("After resolving the conflicts, mark them with\n"
491 "\"git add/rm <pathspec>\", then run\n"
492 "\"git revert --continue\".\n"
493 "You can instead skip this commit with \"git revert --skip\".\n"
494 "To abort and get back to the state before \"git revert\",\n"
495 "run \"git revert --abort\"."));
496 else
497 BUG("unexpected pick action in print_advice()");
501 static int write_message(const void *buf, size_t len, const char *filename,
502 int append_eol)
504 struct lock_file msg_file = LOCK_INIT;
506 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
507 if (msg_fd < 0)
508 return error_errno(_("could not lock '%s'"), filename);
509 if (write_in_full(msg_fd, buf, len) < 0) {
510 error_errno(_("could not write to '%s'"), filename);
511 rollback_lock_file(&msg_file);
512 return -1;
514 if (append_eol && write(msg_fd, "\n", 1) < 0) {
515 error_errno(_("could not write eol to '%s'"), filename);
516 rollback_lock_file(&msg_file);
517 return -1;
519 if (commit_lock_file(&msg_file) < 0)
520 return error(_("failed to finalize '%s'"), filename);
522 return 0;
525 int read_oneliner(struct strbuf *buf,
526 const char *path, unsigned flags)
528 int orig_len = buf->len;
530 if (strbuf_read_file(buf, path, 0) < 0) {
531 if ((flags & READ_ONELINER_WARN_MISSING) ||
532 (errno != ENOENT && errno != ENOTDIR))
533 warning_errno(_("could not read '%s'"), path);
534 return 0;
537 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
538 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
539 --buf->len;
540 buf->buf[buf->len] = '\0';
543 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
544 return 0;
546 return 1;
549 static struct tree *empty_tree(struct repository *r)
551 return lookup_tree(r, the_hash_algo->empty_tree);
554 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
556 if (repo_read_index_unmerged(repo))
557 return error_resolve_conflict(action_name(opts));
559 error(_("your local changes would be overwritten by %s."),
560 _(action_name(opts)));
562 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
563 advise(_("commit your changes or stash them to proceed."));
564 return -1;
567 static void update_abort_safety_file(void)
569 struct object_id head;
571 /* Do nothing on a single-pick */
572 if (!file_exists(git_path_seq_dir()))
573 return;
575 if (!repo_get_oid(the_repository, "HEAD", &head))
576 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
577 else
578 write_file(git_path_abort_safety_file(), "%s", "");
581 static int fast_forward_to(struct repository *r,
582 const struct object_id *to,
583 const struct object_id *from,
584 int unborn,
585 struct replay_opts *opts)
587 struct ref_transaction *transaction;
588 struct strbuf sb = STRBUF_INIT;
589 struct strbuf err = STRBUF_INIT;
591 repo_read_index(r);
592 if (checkout_fast_forward(r, from, to, 1))
593 return -1; /* the callee should have complained already */
595 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
597 transaction = ref_transaction_begin(&err);
598 if (!transaction ||
599 ref_transaction_update(transaction, "HEAD",
600 to, unborn && !is_rebase_i(opts) ?
601 null_oid() : from,
602 0, sb.buf, &err) ||
603 ref_transaction_commit(transaction, &err)) {
604 ref_transaction_free(transaction);
605 error("%s", err.buf);
606 strbuf_release(&sb);
607 strbuf_release(&err);
608 return -1;
611 strbuf_release(&sb);
612 strbuf_release(&err);
613 ref_transaction_free(transaction);
614 update_abort_safety_file();
615 return 0;
618 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
619 int use_editor)
621 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
622 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
623 COMMIT_MSG_CLEANUP_SPACE;
624 else if (!strcmp(cleanup_arg, "verbatim"))
625 return COMMIT_MSG_CLEANUP_NONE;
626 else if (!strcmp(cleanup_arg, "whitespace"))
627 return COMMIT_MSG_CLEANUP_SPACE;
628 else if (!strcmp(cleanup_arg, "strip"))
629 return COMMIT_MSG_CLEANUP_ALL;
630 else if (!strcmp(cleanup_arg, "scissors"))
631 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
632 COMMIT_MSG_CLEANUP_SPACE;
633 else
634 die(_("Invalid cleanup mode %s"), cleanup_arg);
638 * NB using int rather than enum cleanup_mode to stop clang's
639 * -Wtautological-constant-out-of-range-compare complaining that the comparison
640 * is always true.
642 static const char *describe_cleanup_mode(int cleanup_mode)
644 static const char *modes[] = { "whitespace",
645 "verbatim",
646 "scissors",
647 "strip" };
649 if (cleanup_mode < ARRAY_SIZE(modes))
650 return modes[cleanup_mode];
652 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
655 void append_conflicts_hint(struct index_state *istate,
656 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
658 int i;
660 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
661 strbuf_addch(msgbuf, '\n');
662 wt_status_append_cut_line(msgbuf);
663 strbuf_addch(msgbuf, comment_line_char);
666 strbuf_addch(msgbuf, '\n');
667 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
668 for (i = 0; i < istate->cache_nr;) {
669 const struct cache_entry *ce = istate->cache[i++];
670 if (ce_stage(ce)) {
671 strbuf_commented_addf(msgbuf, comment_line_char,
672 "\t%s\n", ce->name);
673 while (i < istate->cache_nr &&
674 !strcmp(ce->name, istate->cache[i]->name))
675 i++;
680 static int do_recursive_merge(struct repository *r,
681 struct commit *base, struct commit *next,
682 const char *base_label, const char *next_label,
683 struct object_id *head, struct strbuf *msgbuf,
684 struct replay_opts *opts)
686 struct merge_options o;
687 struct merge_result result;
688 struct tree *next_tree, *base_tree, *head_tree;
689 int clean, show_output;
690 int i;
691 struct lock_file index_lock = LOCK_INIT;
693 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
694 return -1;
696 repo_read_index(r);
698 init_merge_options(&o, r);
699 o.ancestor = base ? base_label : "(empty tree)";
700 o.branch1 = "HEAD";
701 o.branch2 = next ? next_label : "(empty tree)";
702 if (is_rebase_i(opts))
703 o.buffer_output = 2;
704 o.show_rename_progress = 1;
706 head_tree = parse_tree_indirect(head);
707 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
708 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
710 for (i = 0; i < opts->xopts.nr; i++)
711 parse_merge_opt(&o, opts->xopts.v[i]);
713 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
714 memset(&result, 0, sizeof(result));
715 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
716 &result);
717 show_output = !is_rebase_i(opts) || !result.clean;
719 * TODO: merge_switch_to_result will update index/working tree;
720 * we only really want to do that if !result.clean || this is
721 * the final patch to be picked. But determining this is the
722 * final patch would take some work, and "head_tree" would need
723 * to be replace with the tree the index matched before we
724 * started doing any picks.
726 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
727 clean = result.clean;
728 } else {
729 ensure_full_index(r->index);
730 clean = merge_trees(&o, head_tree, next_tree, base_tree);
731 if (is_rebase_i(opts) && clean <= 0)
732 fputs(o.obuf.buf, stdout);
733 strbuf_release(&o.obuf);
735 if (clean < 0) {
736 rollback_lock_file(&index_lock);
737 return clean;
740 if (write_locked_index(r->index, &index_lock,
741 COMMIT_LOCK | SKIP_IF_UNCHANGED))
743 * TRANSLATORS: %s will be "revert", "cherry-pick" or
744 * "rebase".
746 return error(_("%s: Unable to write new index file"),
747 _(action_name(opts)));
749 if (!clean)
750 append_conflicts_hint(r->index, msgbuf,
751 opts->default_msg_cleanup);
753 return !clean;
756 static struct object_id *get_cache_tree_oid(struct index_state *istate)
758 if (!cache_tree_fully_valid(istate->cache_tree))
759 if (cache_tree_update(istate, 0)) {
760 error(_("unable to update cache tree"));
761 return NULL;
764 return &istate->cache_tree->oid;
767 static int is_index_unchanged(struct repository *r)
769 struct object_id head_oid, *cache_tree_oid;
770 struct commit *head_commit;
771 struct index_state *istate = r->index;
773 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
774 return error(_("could not resolve HEAD commit"));
776 head_commit = lookup_commit(r, &head_oid);
779 * If head_commit is NULL, check_commit, called from
780 * lookup_commit, would have indicated that head_commit is not
781 * a commit object already. repo_parse_commit() will return failure
782 * without further complaints in such a case. Otherwise, if
783 * the commit is invalid, repo_parse_commit() will complain. So
784 * there is nothing for us to say here. Just return failure.
786 if (repo_parse_commit(r, head_commit))
787 return -1;
789 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
790 return -1;
792 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
795 static int write_author_script(const char *message)
797 struct strbuf buf = STRBUF_INIT;
798 const char *eol;
799 int res;
801 for (;;)
802 if (!*message || starts_with(message, "\n")) {
803 missing_author:
804 /* Missing 'author' line? */
805 unlink(rebase_path_author_script());
806 return 0;
807 } else if (skip_prefix(message, "author ", &message))
808 break;
809 else if ((eol = strchr(message, '\n')))
810 message = eol + 1;
811 else
812 goto missing_author;
814 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
815 while (*message && *message != '\n' && *message != '\r')
816 if (skip_prefix(message, " <", &message))
817 break;
818 else if (*message != '\'')
819 strbuf_addch(&buf, *(message++));
820 else
821 strbuf_addf(&buf, "'\\%c'", *(message++));
822 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
823 while (*message && *message != '\n' && *message != '\r')
824 if (skip_prefix(message, "> ", &message))
825 break;
826 else if (*message != '\'')
827 strbuf_addch(&buf, *(message++));
828 else
829 strbuf_addf(&buf, "'\\%c'", *(message++));
830 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
831 while (*message && *message != '\n' && *message != '\r')
832 if (*message != '\'')
833 strbuf_addch(&buf, *(message++));
834 else
835 strbuf_addf(&buf, "'\\%c'", *(message++));
836 strbuf_addch(&buf, '\'');
837 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
838 strbuf_release(&buf);
839 return res;
843 * Take a series of KEY='VALUE' lines where VALUE part is
844 * sq-quoted, and append <KEY, VALUE> at the end of the string list
846 static int parse_key_value_squoted(char *buf, struct string_list *list)
848 while (*buf) {
849 struct string_list_item *item;
850 char *np;
851 char *cp = strchr(buf, '=');
852 if (!cp) {
853 np = strchrnul(buf, '\n');
854 return error(_("no key present in '%.*s'"),
855 (int) (np - buf), buf);
857 np = strchrnul(cp, '\n');
858 *cp++ = '\0';
859 item = string_list_append(list, buf);
861 buf = np + (*np == '\n');
862 *np = '\0';
863 cp = sq_dequote(cp);
864 if (!cp)
865 return error(_("unable to dequote value of '%s'"),
866 item->string);
867 item->util = xstrdup(cp);
869 return 0;
873 * Reads and parses the state directory's "author-script" file, and sets name,
874 * email and date accordingly.
875 * Returns 0 on success, -1 if the file could not be parsed.
877 * The author script is of the format:
879 * GIT_AUTHOR_NAME='$author_name'
880 * GIT_AUTHOR_EMAIL='$author_email'
881 * GIT_AUTHOR_DATE='$author_date'
883 * where $author_name, $author_email and $author_date are quoted. We are strict
884 * with our parsing, as the file was meant to be eval'd in the now-removed
885 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
886 * from what this function expects, it is better to bail out than to do
887 * something that the user does not expect.
889 int read_author_script(const char *path, char **name, char **email, char **date,
890 int allow_missing)
892 struct strbuf buf = STRBUF_INIT;
893 struct string_list kv = STRING_LIST_INIT_DUP;
894 int retval = -1; /* assume failure */
895 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
897 if (strbuf_read_file(&buf, path, 256) <= 0) {
898 strbuf_release(&buf);
899 if (errno == ENOENT && allow_missing)
900 return 0;
901 else
902 return error_errno(_("could not open '%s' for reading"),
903 path);
906 if (parse_key_value_squoted(buf.buf, &kv))
907 goto finish;
909 for (i = 0; i < kv.nr; i++) {
910 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
911 if (name_i != -2)
912 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
913 else
914 name_i = i;
915 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
916 if (email_i != -2)
917 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
918 else
919 email_i = i;
920 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
921 if (date_i != -2)
922 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
923 else
924 date_i = i;
925 } else {
926 err = error(_("unknown variable '%s'"),
927 kv.items[i].string);
930 if (name_i == -2)
931 error(_("missing 'GIT_AUTHOR_NAME'"));
932 if (email_i == -2)
933 error(_("missing 'GIT_AUTHOR_EMAIL'"));
934 if (date_i == -2)
935 error(_("missing 'GIT_AUTHOR_DATE'"));
936 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
937 goto finish;
938 *name = kv.items[name_i].util;
939 *email = kv.items[email_i].util;
940 *date = kv.items[date_i].util;
941 retval = 0;
942 finish:
943 string_list_clear(&kv, !!retval);
944 strbuf_release(&buf);
945 return retval;
949 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
950 * file with shell quoting into struct strvec. Returns -1 on
951 * error, 0 otherwise.
953 static int read_env_script(struct strvec *env)
955 char *name, *email, *date;
957 if (read_author_script(rebase_path_author_script(),
958 &name, &email, &date, 0))
959 return -1;
961 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
962 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
963 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
964 free(name);
965 free(email);
966 free(date);
968 return 0;
971 static char *get_author(const char *message)
973 size_t len;
974 const char *a;
976 a = find_commit_header(message, "author", &len);
977 if (a)
978 return xmemdupz(a, len);
980 return NULL;
983 static const char *author_date_from_env(const struct strvec *env)
985 int i;
986 const char *date;
988 for (i = 0; i < env->nr; i++)
989 if (skip_prefix(env->v[i],
990 "GIT_AUTHOR_DATE=", &date))
991 return date;
993 * If GIT_AUTHOR_DATE is missing we should have already errored out when
994 * reading the script
996 BUG("GIT_AUTHOR_DATE missing from author script");
999 static const char staged_changes_advice[] =
1000 N_("you have staged changes in your working tree\n"
1001 "If these changes are meant to be squashed into the previous commit, run:\n"
1002 "\n"
1003 " git commit --amend %s\n"
1004 "\n"
1005 "If they are meant to go into a new commit, run:\n"
1006 "\n"
1007 " git commit %s\n"
1008 "\n"
1009 "In both cases, once you're done, continue with:\n"
1010 "\n"
1011 " git rebase --continue\n");
1013 #define ALLOW_EMPTY (1<<0)
1014 #define EDIT_MSG (1<<1)
1015 #define AMEND_MSG (1<<2)
1016 #define CLEANUP_MSG (1<<3)
1017 #define VERIFY_MSG (1<<4)
1018 #define CREATE_ROOT_COMMIT (1<<5)
1019 #define VERBATIM_MSG (1<<6)
1021 static int run_command_silent_on_success(struct child_process *cmd)
1023 struct strbuf buf = STRBUF_INIT;
1024 int rc;
1026 cmd->stdout_to_stderr = 1;
1027 rc = pipe_command(cmd,
1028 NULL, 0,
1029 NULL, 0,
1030 &buf, 0);
1032 if (rc)
1033 fputs(buf.buf, stderr);
1034 strbuf_release(&buf);
1035 return rc;
1039 * If we are cherry-pick, and if the merge did not result in
1040 * hand-editing, we will hit this commit and inherit the original
1041 * author date and name.
1043 * If we are revert, or if our cherry-pick results in a hand merge,
1044 * we had better say that the current user is responsible for that.
1046 * An exception is when run_git_commit() is called during an
1047 * interactive rebase: in that case, we will want to retain the
1048 * author metadata.
1050 static int run_git_commit(const char *defmsg,
1051 struct replay_opts *opts,
1052 unsigned int flags)
1054 struct child_process cmd = CHILD_PROCESS_INIT;
1056 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1057 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1059 cmd.git_cmd = 1;
1061 if (is_rebase_i(opts) &&
1062 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1063 !(!defmsg && (flags & AMEND_MSG))) &&
1064 read_env_script(&cmd.env)) {
1065 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1067 return error(_(staged_changes_advice),
1068 gpg_opt, gpg_opt);
1071 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1073 if (opts->committer_date_is_author_date)
1074 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1075 opts->ignore_date ?
1076 "" :
1077 author_date_from_env(&cmd.env));
1078 if (opts->ignore_date)
1079 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1081 strvec_push(&cmd.args, "commit");
1083 if (!(flags & VERIFY_MSG))
1084 strvec_push(&cmd.args, "-n");
1085 if ((flags & AMEND_MSG))
1086 strvec_push(&cmd.args, "--amend");
1087 if (opts->gpg_sign)
1088 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1089 else
1090 strvec_push(&cmd.args, "--no-gpg-sign");
1091 if (defmsg)
1092 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1093 else if (!(flags & EDIT_MSG))
1094 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1095 if ((flags & CLEANUP_MSG))
1096 strvec_push(&cmd.args, "--cleanup=strip");
1097 if ((flags & VERBATIM_MSG))
1098 strvec_push(&cmd.args, "--cleanup=verbatim");
1099 if ((flags & EDIT_MSG))
1100 strvec_push(&cmd.args, "-e");
1101 else if (!(flags & CLEANUP_MSG) &&
1102 !opts->signoff && !opts->record_origin &&
1103 !opts->explicit_cleanup)
1104 strvec_push(&cmd.args, "--cleanup=verbatim");
1106 if ((flags & ALLOW_EMPTY))
1107 strvec_push(&cmd.args, "--allow-empty");
1109 if (!(flags & EDIT_MSG))
1110 strvec_push(&cmd.args, "--allow-empty-message");
1112 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1113 return run_command_silent_on_success(&cmd);
1114 else
1115 return run_command(&cmd);
1118 static int rest_is_empty(const struct strbuf *sb, int start)
1120 int i, eol;
1121 const char *nl;
1123 /* Check if the rest is just whitespace and Signed-off-by's. */
1124 for (i = start; i < sb->len; i++) {
1125 nl = memchr(sb->buf + i, '\n', sb->len - i);
1126 if (nl)
1127 eol = nl - sb->buf;
1128 else
1129 eol = sb->len;
1131 if (strlen(sign_off_header) <= eol - i &&
1132 starts_with(sb->buf + i, sign_off_header)) {
1133 i = eol;
1134 continue;
1136 while (i < eol)
1137 if (!isspace(sb->buf[i++]))
1138 return 0;
1141 return 1;
1144 void cleanup_message(struct strbuf *msgbuf,
1145 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1147 if (verbose || /* Truncate the message just before the diff, if any. */
1148 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1149 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1150 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1151 strbuf_stripspace(msgbuf,
1152 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1156 * Find out if the message in the strbuf contains only whitespace and
1157 * Signed-off-by lines.
1159 int message_is_empty(const struct strbuf *sb,
1160 enum commit_msg_cleanup_mode cleanup_mode)
1162 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1163 return 0;
1164 return rest_is_empty(sb, 0);
1168 * See if the user edited the message in the editor or left what
1169 * was in the template intact
1171 int template_untouched(const struct strbuf *sb, const char *template_file,
1172 enum commit_msg_cleanup_mode cleanup_mode)
1174 struct strbuf tmpl = STRBUF_INIT;
1175 const char *start;
1177 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1178 return 0;
1180 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1181 return 0;
1183 strbuf_stripspace(&tmpl,
1184 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1185 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1186 start = sb->buf;
1187 strbuf_release(&tmpl);
1188 return rest_is_empty(sb, start - sb->buf);
1191 int update_head_with_reflog(const struct commit *old_head,
1192 const struct object_id *new_head,
1193 const char *action, const struct strbuf *msg,
1194 struct strbuf *err)
1196 struct ref_transaction *transaction;
1197 struct strbuf sb = STRBUF_INIT;
1198 const char *nl;
1199 int ret = 0;
1201 if (action) {
1202 strbuf_addstr(&sb, action);
1203 strbuf_addstr(&sb, ": ");
1206 nl = strchr(msg->buf, '\n');
1207 if (nl) {
1208 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1209 } else {
1210 strbuf_addbuf(&sb, msg);
1211 strbuf_addch(&sb, '\n');
1214 transaction = ref_transaction_begin(err);
1215 if (!transaction ||
1216 ref_transaction_update(transaction, "HEAD", new_head,
1217 old_head ? &old_head->object.oid : null_oid(),
1218 0, sb.buf, err) ||
1219 ref_transaction_commit(transaction, err)) {
1220 ret = -1;
1222 ref_transaction_free(transaction);
1223 strbuf_release(&sb);
1225 return ret;
1228 static int run_rewrite_hook(const struct object_id *oldoid,
1229 const struct object_id *newoid)
1231 struct child_process proc = CHILD_PROCESS_INIT;
1232 int code;
1233 struct strbuf sb = STRBUF_INIT;
1234 const char *hook_path = find_hook("post-rewrite");
1236 if (!hook_path)
1237 return 0;
1239 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1240 proc.in = -1;
1241 proc.stdout_to_stderr = 1;
1242 proc.trace2_hook_name = "post-rewrite";
1244 code = start_command(&proc);
1245 if (code)
1246 return code;
1247 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1248 sigchain_push(SIGPIPE, SIG_IGN);
1249 write_in_full(proc.in, sb.buf, sb.len);
1250 close(proc.in);
1251 strbuf_release(&sb);
1252 sigchain_pop(SIGPIPE);
1253 return finish_command(&proc);
1256 void commit_post_rewrite(struct repository *r,
1257 const struct commit *old_head,
1258 const struct object_id *new_head)
1260 struct notes_rewrite_cfg *cfg;
1262 cfg = init_copy_notes_for_rewrite("amend");
1263 if (cfg) {
1264 /* we are amending, so old_head is not NULL */
1265 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1266 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1268 run_rewrite_hook(&old_head->object.oid, new_head);
1271 static int run_prepare_commit_msg_hook(struct repository *r,
1272 struct strbuf *msg,
1273 const char *commit)
1275 int ret = 0;
1276 const char *name, *arg1 = NULL, *arg2 = NULL;
1278 name = git_path_commit_editmsg();
1279 if (write_message(msg->buf, msg->len, name, 0))
1280 return -1;
1282 if (commit) {
1283 arg1 = "commit";
1284 arg2 = commit;
1285 } else {
1286 arg1 = "message";
1288 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1289 arg1, arg2, NULL))
1290 ret = error(_("'prepare-commit-msg' hook failed"));
1292 return ret;
1295 static const char implicit_ident_advice_noconfig[] =
1296 N_("Your name and email address were configured automatically based\n"
1297 "on your username and hostname. Please check that they are accurate.\n"
1298 "You can suppress this message by setting them explicitly. Run the\n"
1299 "following command and follow the instructions in your editor to edit\n"
1300 "your configuration file:\n"
1301 "\n"
1302 " git config --global --edit\n"
1303 "\n"
1304 "After doing this, you may fix the identity used for this commit with:\n"
1305 "\n"
1306 " git commit --amend --reset-author\n");
1308 static const char implicit_ident_advice_config[] =
1309 N_("Your name and email address were configured automatically based\n"
1310 "on your username and hostname. Please check that they are accurate.\n"
1311 "You can suppress this message by setting them explicitly:\n"
1312 "\n"
1313 " git config --global user.name \"Your Name\"\n"
1314 " git config --global user.email you@example.com\n"
1315 "\n"
1316 "After doing this, you may fix the identity used for this commit with:\n"
1317 "\n"
1318 " git commit --amend --reset-author\n");
1320 static const char *implicit_ident_advice(void)
1322 char *user_config = interpolate_path("~/.gitconfig", 0);
1323 char *xdg_config = xdg_config_home("config");
1324 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1326 free(user_config);
1327 free(xdg_config);
1329 if (config_exists)
1330 return _(implicit_ident_advice_config);
1331 else
1332 return _(implicit_ident_advice_noconfig);
1336 void print_commit_summary(struct repository *r,
1337 const char *prefix,
1338 const struct object_id *oid,
1339 unsigned int flags)
1341 struct rev_info rev;
1342 struct commit *commit;
1343 struct strbuf format = STRBUF_INIT;
1344 const char *head;
1345 struct pretty_print_context pctx = {0};
1346 struct strbuf author_ident = STRBUF_INIT;
1347 struct strbuf committer_ident = STRBUF_INIT;
1348 struct ref_store *refs;
1350 commit = lookup_commit(r, oid);
1351 if (!commit)
1352 die(_("couldn't look up newly created commit"));
1353 if (repo_parse_commit(r, commit))
1354 die(_("could not parse newly created commit"));
1356 strbuf_addstr(&format, "format:%h] %s");
1358 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1359 &pctx);
1360 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1361 &pctx);
1362 if (strbuf_cmp(&author_ident, &committer_ident)) {
1363 strbuf_addstr(&format, "\n Author: ");
1364 strbuf_addbuf_percentquote(&format, &author_ident);
1366 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1367 struct strbuf date = STRBUF_INIT;
1369 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1370 strbuf_addstr(&format, "\n Date: ");
1371 strbuf_addbuf_percentquote(&format, &date);
1372 strbuf_release(&date);
1374 if (!committer_ident_sufficiently_given()) {
1375 strbuf_addstr(&format, "\n Committer: ");
1376 strbuf_addbuf_percentquote(&format, &committer_ident);
1377 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1378 strbuf_addch(&format, '\n');
1379 strbuf_addstr(&format, implicit_ident_advice());
1382 strbuf_release(&author_ident);
1383 strbuf_release(&committer_ident);
1385 repo_init_revisions(r, &rev, prefix);
1386 setup_revisions(0, NULL, &rev, NULL);
1388 rev.diff = 1;
1389 rev.diffopt.output_format =
1390 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1392 rev.verbose_header = 1;
1393 rev.show_root_diff = 1;
1394 get_commit_format(format.buf, &rev);
1395 rev.always_show_header = 0;
1396 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1397 diff_setup_done(&rev.diffopt);
1399 refs = get_main_ref_store(r);
1400 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1401 if (!head)
1402 die(_("unable to resolve HEAD after creating commit"));
1403 if (!strcmp(head, "HEAD"))
1404 head = _("detached HEAD");
1405 else
1406 skip_prefix(head, "refs/heads/", &head);
1407 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1408 _(" (root-commit)") : "");
1410 if (!log_tree_commit(&rev, commit)) {
1411 rev.always_show_header = 1;
1412 rev.use_terminator = 1;
1413 log_tree_commit(&rev, commit);
1416 release_revisions(&rev);
1417 strbuf_release(&format);
1420 static int parse_head(struct repository *r, struct commit **head)
1422 struct commit *current_head;
1423 struct object_id oid;
1425 if (repo_get_oid(r, "HEAD", &oid)) {
1426 current_head = NULL;
1427 } else {
1428 current_head = lookup_commit_reference(r, &oid);
1429 if (!current_head)
1430 return error(_("could not parse HEAD"));
1431 if (!oideq(&oid, &current_head->object.oid)) {
1432 warning(_("HEAD %s is not a commit!"),
1433 oid_to_hex(&oid));
1435 if (repo_parse_commit(r, current_head))
1436 return error(_("could not parse HEAD commit"));
1438 *head = current_head;
1440 return 0;
1444 * Try to commit without forking 'git commit'. In some cases we need
1445 * to run 'git commit' to display an error message
1447 * Returns:
1448 * -1 - error unable to commit
1449 * 0 - success
1450 * 1 - run 'git commit'
1452 static int try_to_commit(struct repository *r,
1453 struct strbuf *msg, const char *author,
1454 struct replay_opts *opts, unsigned int flags,
1455 struct object_id *oid)
1457 struct object_id tree;
1458 struct commit *current_head = NULL;
1459 struct commit_list *parents = NULL;
1460 struct commit_extra_header *extra = NULL;
1461 struct strbuf err = STRBUF_INIT;
1462 struct strbuf commit_msg = STRBUF_INIT;
1463 char *amend_author = NULL;
1464 const char *committer = NULL;
1465 const char *hook_commit = NULL;
1466 enum commit_msg_cleanup_mode cleanup;
1467 int res = 0;
1469 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1470 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1472 if (parse_head(r, &current_head))
1473 return -1;
1475 if (flags & AMEND_MSG) {
1476 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1477 const char *out_enc = get_commit_output_encoding();
1478 const char *message = repo_logmsg_reencode(r, current_head,
1479 NULL, out_enc);
1481 if (!msg) {
1482 const char *orig_message = NULL;
1484 find_commit_subject(message, &orig_message);
1485 msg = &commit_msg;
1486 strbuf_addstr(msg, orig_message);
1487 hook_commit = "HEAD";
1489 author = amend_author = get_author(message);
1490 repo_unuse_commit_buffer(r, current_head,
1491 message);
1492 if (!author) {
1493 res = error(_("unable to parse commit author"));
1494 goto out;
1496 parents = copy_commit_list(current_head->parents);
1497 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1498 } else if (current_head &&
1499 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1500 commit_list_insert(current_head, &parents);
1503 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1504 res = error(_("git write-tree failed to write a tree"));
1505 goto out;
1508 if (!(flags & ALLOW_EMPTY)) {
1509 struct commit *first_parent = current_head;
1511 if (flags & AMEND_MSG) {
1512 if (current_head->parents) {
1513 first_parent = current_head->parents->item;
1514 if (repo_parse_commit(r, first_parent)) {
1515 res = error(_("could not parse HEAD commit"));
1516 goto out;
1518 } else {
1519 first_parent = NULL;
1522 if (oideq(first_parent
1523 ? get_commit_tree_oid(first_parent)
1524 : the_hash_algo->empty_tree,
1525 &tree)) {
1526 res = 1; /* run 'git commit' to display error message */
1527 goto out;
1531 if (hook_exists("prepare-commit-msg")) {
1532 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1533 if (res)
1534 goto out;
1535 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1536 2048) < 0) {
1537 res = error_errno(_("unable to read commit message "
1538 "from '%s'"),
1539 git_path_commit_editmsg());
1540 goto out;
1542 msg = &commit_msg;
1545 if (flags & CLEANUP_MSG)
1546 cleanup = COMMIT_MSG_CLEANUP_ALL;
1547 else if (flags & VERBATIM_MSG)
1548 cleanup = COMMIT_MSG_CLEANUP_NONE;
1549 else if ((opts->signoff || opts->record_origin) &&
1550 !opts->explicit_cleanup)
1551 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1552 else
1553 cleanup = opts->default_msg_cleanup;
1555 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1556 strbuf_stripspace(msg,
1557 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1558 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1559 res = 1; /* run 'git commit' to display error message */
1560 goto out;
1563 if (opts->committer_date_is_author_date) {
1564 struct ident_split id;
1565 struct strbuf date = STRBUF_INIT;
1567 if (!opts->ignore_date) {
1568 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1569 res = error(_("invalid author identity '%s'"),
1570 author);
1571 goto out;
1573 if (!id.date_begin) {
1574 res = error(_(
1575 "corrupt author: missing date information"));
1576 goto out;
1578 strbuf_addf(&date, "@%.*s %.*s",
1579 (int)(id.date_end - id.date_begin),
1580 id.date_begin,
1581 (int)(id.tz_end - id.tz_begin),
1582 id.tz_begin);
1583 } else {
1584 reset_ident_date();
1586 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1587 getenv("GIT_COMMITTER_EMAIL"),
1588 WANT_COMMITTER_IDENT,
1589 opts->ignore_date ? NULL : date.buf,
1590 IDENT_STRICT);
1591 strbuf_release(&date);
1592 } else {
1593 reset_ident_date();
1596 if (opts->ignore_date) {
1597 struct ident_split id;
1598 char *name, *email;
1600 if (split_ident_line(&id, author, strlen(author)) < 0) {
1601 error(_("invalid author identity '%s'"), author);
1602 goto out;
1604 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1605 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1606 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1607 IDENT_STRICT);
1608 free(name);
1609 free(email);
1612 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1613 author, committer, opts->gpg_sign, extra)) {
1614 res = error(_("failed to write commit object"));
1615 goto out;
1618 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1619 msg, &err)) {
1620 res = error("%s", err.buf);
1621 goto out;
1624 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1625 if (flags & AMEND_MSG)
1626 commit_post_rewrite(r, current_head, oid);
1628 out:
1629 free_commit_extra_headers(extra);
1630 strbuf_release(&err);
1631 strbuf_release(&commit_msg);
1632 free(amend_author);
1634 return res;
1637 static int write_rebase_head(struct object_id *oid)
1639 if (update_ref("rebase", "REBASE_HEAD", oid,
1640 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1641 return error(_("could not update %s"), "REBASE_HEAD");
1643 return 0;
1646 static int do_commit(struct repository *r,
1647 const char *msg_file, const char *author,
1648 struct replay_opts *opts, unsigned int flags,
1649 struct object_id *oid)
1651 int res = 1;
1653 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1654 struct object_id oid;
1655 struct strbuf sb = STRBUF_INIT;
1657 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1658 return error_errno(_("unable to read commit message "
1659 "from '%s'"),
1660 msg_file);
1662 res = try_to_commit(r, msg_file ? &sb : NULL,
1663 author, opts, flags, &oid);
1664 strbuf_release(&sb);
1665 if (!res) {
1666 refs_delete_ref(get_main_ref_store(r), "",
1667 "CHERRY_PICK_HEAD", NULL, 0);
1668 unlink(git_path_merge_msg(r));
1669 if (!is_rebase_i(opts))
1670 print_commit_summary(r, NULL, &oid,
1671 SUMMARY_SHOW_AUTHOR_DATE);
1672 return res;
1675 if (res == 1) {
1676 if (is_rebase_i(opts) && oid)
1677 if (write_rebase_head(oid))
1678 return -1;
1679 return run_git_commit(msg_file, opts, flags);
1682 return res;
1685 static int is_original_commit_empty(struct commit *commit)
1687 const struct object_id *ptree_oid;
1689 if (repo_parse_commit(the_repository, commit))
1690 return error(_("could not parse commit %s"),
1691 oid_to_hex(&commit->object.oid));
1692 if (commit->parents) {
1693 struct commit *parent = commit->parents->item;
1694 if (repo_parse_commit(the_repository, parent))
1695 return error(_("could not parse parent commit %s"),
1696 oid_to_hex(&parent->object.oid));
1697 ptree_oid = get_commit_tree_oid(parent);
1698 } else {
1699 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1702 return oideq(ptree_oid, get_commit_tree_oid(commit));
1706 * Should empty commits be allowed? Return status:
1707 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1708 * 0: Halt on empty commit
1709 * 1: Allow empty commit
1710 * 2: Drop empty commit
1712 static int allow_empty(struct repository *r,
1713 struct replay_opts *opts,
1714 struct commit *commit)
1716 int index_unchanged, originally_empty;
1719 * Four cases:
1721 * (1) we do not allow empty at all and error out.
1723 * (2) we allow ones that were initially empty, and
1724 * just drop the ones that become empty
1726 * (3) we allow ones that were initially empty, but
1727 * halt for the ones that become empty;
1729 * (4) we allow both.
1731 if (!opts->allow_empty)
1732 return 0; /* let "git commit" barf as necessary */
1734 index_unchanged = is_index_unchanged(r);
1735 if (index_unchanged < 0)
1736 return index_unchanged;
1737 if (!index_unchanged)
1738 return 0; /* we do not have to say --allow-empty */
1740 if (opts->keep_redundant_commits)
1741 return 1;
1743 originally_empty = is_original_commit_empty(commit);
1744 if (originally_empty < 0)
1745 return originally_empty;
1746 if (originally_empty)
1747 return 1;
1748 else if (opts->drop_redundant_commits)
1749 return 2;
1750 else
1751 return 0;
1754 static struct {
1755 char c;
1756 const char *str;
1757 } todo_command_info[] = {
1758 [TODO_PICK] = { 'p', "pick" },
1759 [TODO_REVERT] = { 0, "revert" },
1760 [TODO_EDIT] = { 'e', "edit" },
1761 [TODO_REWORD] = { 'r', "reword" },
1762 [TODO_FIXUP] = { 'f', "fixup" },
1763 [TODO_SQUASH] = { 's', "squash" },
1764 [TODO_EXEC] = { 'x', "exec" },
1765 [TODO_BREAK] = { 'b', "break" },
1766 [TODO_LABEL] = { 'l', "label" },
1767 [TODO_RESET] = { 't', "reset" },
1768 [TODO_MERGE] = { 'm', "merge" },
1769 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1770 [TODO_NOOP] = { 0, "noop" },
1771 [TODO_DROP] = { 'd', "drop" },
1772 [TODO_COMMENT] = { 0, NULL },
1775 static const char *command_to_string(const enum todo_command command)
1777 if (command < TODO_COMMENT)
1778 return todo_command_info[command].str;
1779 die(_("unknown command: %d"), command);
1782 static char command_to_char(const enum todo_command command)
1784 if (command < TODO_COMMENT)
1785 return todo_command_info[command].c;
1786 return comment_line_char;
1789 static int is_noop(const enum todo_command command)
1791 return TODO_NOOP <= command;
1794 static int is_fixup(enum todo_command command)
1796 return command == TODO_FIXUP || command == TODO_SQUASH;
1799 /* Does this command create a (non-merge) commit? */
1800 static int is_pick_or_similar(enum todo_command command)
1802 switch (command) {
1803 case TODO_PICK:
1804 case TODO_REVERT:
1805 case TODO_EDIT:
1806 case TODO_REWORD:
1807 case TODO_FIXUP:
1808 case TODO_SQUASH:
1809 return 1;
1810 default:
1811 return 0;
1815 enum todo_item_flags {
1816 TODO_EDIT_MERGE_MSG = (1 << 0),
1817 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1818 TODO_EDIT_FIXUP_MSG = (1 << 2),
1821 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1822 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1823 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1824 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1825 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1827 static int is_fixup_flag(enum todo_command command, unsigned flag)
1829 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1830 (flag & TODO_EDIT_FIXUP_MSG));
1834 * Wrapper around strbuf_add_commented_lines() which avoids double
1835 * commenting commit subjects.
1837 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1839 const char *s = str;
1840 while (len > 0 && s[0] == comment_line_char) {
1841 size_t count;
1842 const char *n = memchr(s, '\n', len);
1843 if (!n)
1844 count = len;
1845 else
1846 count = n - s + 1;
1847 strbuf_add(buf, s, count);
1848 s += count;
1849 len -= count;
1851 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1854 /* Does the current fixup chain contain a squash command? */
1855 static int seen_squash(struct replay_opts *opts)
1857 return starts_with(opts->current_fixups.buf, "squash") ||
1858 strstr(opts->current_fixups.buf, "\nsquash");
1861 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1863 strbuf_setlen(buf1, 2);
1864 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1865 strbuf_addch(buf1, '\n');
1866 strbuf_setlen(buf2, 2);
1867 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1868 strbuf_addch(buf2, '\n');
1872 * Comment out any un-commented commit messages, updating the message comments
1873 * to say they will be skipped but do not comment out the empty lines that
1874 * surround commit messages and their comments.
1876 static void update_squash_message_for_fixup(struct strbuf *msg)
1878 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1879 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1880 const char *s, *start;
1881 char *orig_msg;
1882 size_t orig_msg_len;
1883 int i = 1;
1885 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1886 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1887 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1888 while (s) {
1889 const char *next;
1890 size_t off;
1891 if (skip_prefix(s, buf1.buf, &next)) {
1893 * Copy the last message, preserving the blank line
1894 * preceding the current line
1896 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1897 copy_lines(msg, start, s - start - off);
1898 if (off)
1899 strbuf_addch(msg, '\n');
1901 * The next message needs to be commented out but the
1902 * message header is already commented out so just copy
1903 * it and the blank line that follows it.
1905 strbuf_addbuf(msg, &buf2);
1906 if (*next == '\n')
1907 strbuf_addch(msg, *next++);
1908 start = s = next;
1909 copy_lines = add_commented_lines;
1910 update_comment_bufs(&buf1, &buf2, ++i);
1911 } else if (skip_prefix(s, buf2.buf, &next)) {
1912 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1913 copy_lines(msg, start, s - start - off);
1914 start = s - off;
1915 s = next;
1916 copy_lines = strbuf_add;
1917 update_comment_bufs(&buf1, &buf2, ++i);
1918 } else {
1919 s = strchr(s, '\n');
1920 if (s)
1921 s++;
1924 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1925 free(orig_msg);
1926 strbuf_release(&buf1);
1927 strbuf_release(&buf2);
1930 static int append_squash_message(struct strbuf *buf, const char *body,
1931 enum todo_command command, struct replay_opts *opts,
1932 unsigned flag)
1934 const char *fixup_msg;
1935 size_t commented_len = 0, fixup_off;
1937 * amend is non-interactive and not normally used with fixup!
1938 * or squash! commits, so only comment out those subjects when
1939 * squashing commit messages.
1941 if (starts_with(body, "amend!") ||
1942 ((command == TODO_SQUASH || seen_squash(opts)) &&
1943 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1944 commented_len = commit_subject_length(body);
1946 strbuf_addf(buf, "\n%c ", comment_line_char);
1947 strbuf_addf(buf, _(nth_commit_msg_fmt),
1948 ++opts->current_fixup_count + 1);
1949 strbuf_addstr(buf, "\n\n");
1950 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1951 /* buf->buf may be reallocated so store an offset into the buffer */
1952 fixup_off = buf->len;
1953 strbuf_addstr(buf, body + commented_len);
1955 /* fixup -C after squash behaves like squash */
1956 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1958 * We're replacing the commit message so we need to
1959 * append the Signed-off-by: trailer if the user
1960 * requested '--signoff'.
1962 if (opts->signoff)
1963 append_signoff(buf, 0, 0);
1965 if ((command == TODO_FIXUP) &&
1966 (flag & TODO_REPLACE_FIXUP_MSG) &&
1967 (file_exists(rebase_path_fixup_msg()) ||
1968 !file_exists(rebase_path_squash_msg()))) {
1969 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1970 if (write_message(fixup_msg, strlen(fixup_msg),
1971 rebase_path_fixup_msg(), 0) < 0)
1972 return error(_("cannot write '%s'"),
1973 rebase_path_fixup_msg());
1974 } else {
1975 unlink(rebase_path_fixup_msg());
1977 } else {
1978 unlink(rebase_path_fixup_msg());
1981 return 0;
1984 static int update_squash_messages(struct repository *r,
1985 enum todo_command command,
1986 struct commit *commit,
1987 struct replay_opts *opts,
1988 unsigned flag)
1990 struct strbuf buf = STRBUF_INIT;
1991 int res = 0;
1992 const char *message, *body;
1993 const char *encoding = get_commit_output_encoding();
1995 if (opts->current_fixup_count > 0) {
1996 struct strbuf header = STRBUF_INIT;
1997 char *eol;
1999 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2000 return error(_("could not read '%s'"),
2001 rebase_path_squash_msg());
2003 eol = buf.buf[0] != comment_line_char ?
2004 buf.buf : strchrnul(buf.buf, '\n');
2006 strbuf_addf(&header, "%c ", comment_line_char);
2007 strbuf_addf(&header, _(combined_commit_msg_fmt),
2008 opts->current_fixup_count + 2);
2009 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2010 strbuf_release(&header);
2011 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2012 update_squash_message_for_fixup(&buf);
2013 } else {
2014 struct object_id head;
2015 struct commit *head_commit;
2016 const char *head_message, *body;
2018 if (repo_get_oid(r, "HEAD", &head))
2019 return error(_("need a HEAD to fixup"));
2020 if (!(head_commit = lookup_commit_reference(r, &head)))
2021 return error(_("could not read HEAD"));
2022 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2023 encoding)))
2024 return error(_("could not read HEAD's commit message"));
2026 find_commit_subject(head_message, &body);
2027 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2028 rebase_path_fixup_msg(), 0) < 0) {
2029 repo_unuse_commit_buffer(r, head_commit, head_message);
2030 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2032 strbuf_addf(&buf, "%c ", comment_line_char);
2033 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2034 strbuf_addf(&buf, "\n%c ", comment_line_char);
2035 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2036 _(skip_first_commit_msg_str) :
2037 _(first_commit_msg_str));
2038 strbuf_addstr(&buf, "\n\n");
2039 if (is_fixup_flag(command, flag))
2040 strbuf_add_commented_lines(&buf, body, strlen(body),
2041 comment_line_char);
2042 else
2043 strbuf_addstr(&buf, body);
2045 repo_unuse_commit_buffer(r, head_commit, head_message);
2048 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2049 return error(_("could not read commit message of %s"),
2050 oid_to_hex(&commit->object.oid));
2051 find_commit_subject(message, &body);
2053 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2054 res = append_squash_message(&buf, body, command, opts, flag);
2055 } else if (command == TODO_FIXUP) {
2056 strbuf_addf(&buf, "\n%c ", comment_line_char);
2057 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2058 ++opts->current_fixup_count + 1);
2059 strbuf_addstr(&buf, "\n\n");
2060 strbuf_add_commented_lines(&buf, body, strlen(body),
2061 comment_line_char);
2062 } else
2063 return error(_("unknown command: %d"), command);
2064 repo_unuse_commit_buffer(r, commit, message);
2066 if (!res)
2067 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2069 strbuf_release(&buf);
2071 if (!res) {
2072 strbuf_addf(&opts->current_fixups, "%s%s %s",
2073 opts->current_fixups.len ? "\n" : "",
2074 command_to_string(command),
2075 oid_to_hex(&commit->object.oid));
2076 res = write_message(opts->current_fixups.buf,
2077 opts->current_fixups.len,
2078 rebase_path_current_fixups(), 0);
2081 return res;
2084 static void flush_rewritten_pending(void)
2086 struct strbuf buf = STRBUF_INIT;
2087 struct object_id newoid;
2088 FILE *out;
2090 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2091 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2092 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2093 char *bol = buf.buf, *eol;
2095 while (*bol) {
2096 eol = strchrnul(bol, '\n');
2097 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2098 bol, oid_to_hex(&newoid));
2099 if (!*eol)
2100 break;
2101 bol = eol + 1;
2103 fclose(out);
2104 unlink(rebase_path_rewritten_pending());
2106 strbuf_release(&buf);
2109 static void record_in_rewritten(struct object_id *oid,
2110 enum todo_command next_command)
2112 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2114 if (!out)
2115 return;
2117 fprintf(out, "%s\n", oid_to_hex(oid));
2118 fclose(out);
2120 if (!is_fixup(next_command))
2121 flush_rewritten_pending();
2124 static int should_edit(struct replay_opts *opts) {
2125 if (opts->edit < 0)
2127 * Note that we only handle the case of non-conflicted
2128 * commits; continue_single_pick() handles the conflicted
2129 * commits itself instead of calling this function.
2131 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2132 return opts->edit;
2135 static void refer_to_commit(struct replay_opts *opts,
2136 struct strbuf *msgbuf, struct commit *commit)
2138 if (opts->commit_use_reference) {
2139 struct pretty_print_context ctx = {
2140 .abbrev = DEFAULT_ABBREV,
2141 .date_mode.type = DATE_SHORT,
2143 repo_format_commit_message(the_repository, commit,
2144 "%h (%s, %ad)", msgbuf, &ctx);
2145 } else {
2146 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2150 static int do_pick_commit(struct repository *r,
2151 struct todo_item *item,
2152 struct replay_opts *opts,
2153 int final_fixup, int *check_todo)
2155 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2156 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2157 struct object_id head;
2158 struct commit *base, *next, *parent;
2159 const char *base_label, *next_label;
2160 char *author = NULL;
2161 struct commit_message msg = { NULL, NULL, NULL, NULL };
2162 struct strbuf msgbuf = STRBUF_INIT;
2163 int res, unborn = 0, reword = 0, allow, drop_commit;
2164 enum todo_command command = item->command;
2165 struct commit *commit = item->commit;
2167 if (opts->no_commit) {
2169 * We do not intend to commit immediately. We just want to
2170 * merge the differences in, so let's compute the tree
2171 * that represents the "current" state for the merge machinery
2172 * to work on.
2174 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2175 return error(_("your index file is unmerged."));
2176 } else {
2177 unborn = repo_get_oid(r, "HEAD", &head);
2178 /* Do we want to generate a root commit? */
2179 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2180 oideq(&head, &opts->squash_onto)) {
2181 if (is_fixup(command))
2182 return error(_("cannot fixup root commit"));
2183 flags |= CREATE_ROOT_COMMIT;
2184 unborn = 1;
2185 } else if (unborn)
2186 oidcpy(&head, the_hash_algo->empty_tree);
2187 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2188 NULL, 0))
2189 return error_dirty_index(r, opts);
2191 discard_index(r->index);
2193 if (!commit->parents)
2194 parent = NULL;
2195 else if (commit->parents->next) {
2196 /* Reverting or cherry-picking a merge commit */
2197 int cnt;
2198 struct commit_list *p;
2200 if (!opts->mainline)
2201 return error(_("commit %s is a merge but no -m option was given."),
2202 oid_to_hex(&commit->object.oid));
2204 for (cnt = 1, p = commit->parents;
2205 cnt != opts->mainline && p;
2206 cnt++)
2207 p = p->next;
2208 if (cnt != opts->mainline || !p)
2209 return error(_("commit %s does not have parent %d"),
2210 oid_to_hex(&commit->object.oid), opts->mainline);
2211 parent = p->item;
2212 } else if (1 < opts->mainline)
2214 * Non-first parent explicitly specified as mainline for
2215 * non-merge commit
2217 return error(_("commit %s does not have parent %d"),
2218 oid_to_hex(&commit->object.oid), opts->mainline);
2219 else
2220 parent = commit->parents->item;
2222 if (get_message(commit, &msg) != 0)
2223 return error(_("cannot get commit message for %s"),
2224 oid_to_hex(&commit->object.oid));
2226 if (opts->allow_ff && !is_fixup(command) &&
2227 ((parent && oideq(&parent->object.oid, &head)) ||
2228 (!parent && unborn))) {
2229 if (is_rebase_i(opts))
2230 write_author_script(msg.message);
2231 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2232 opts);
2233 if (res || command != TODO_REWORD)
2234 goto leave;
2235 reword = 1;
2236 msg_file = NULL;
2237 goto fast_forward_edit;
2239 if (parent && repo_parse_commit(r, parent) < 0)
2240 /* TRANSLATORS: The first %s will be a "todo" command like
2241 "revert" or "pick", the second %s a SHA1. */
2242 return error(_("%s: cannot parse parent commit %s"),
2243 command_to_string(command),
2244 oid_to_hex(&parent->object.oid));
2247 * "commit" is an existing commit. We would want to apply
2248 * the difference it introduces since its first parent "prev"
2249 * on top of the current HEAD if we are cherry-pick. Or the
2250 * reverse of it if we are revert.
2253 if (command == TODO_REVERT) {
2254 base = commit;
2255 base_label = msg.label;
2256 next = parent;
2257 next_label = msg.parent_label;
2258 if (opts->commit_use_reference) {
2259 strbuf_addstr(&msgbuf,
2260 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2261 } else {
2262 strbuf_addstr(&msgbuf, "Revert \"");
2263 strbuf_addstr(&msgbuf, msg.subject);
2264 strbuf_addstr(&msgbuf, "\"");
2266 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2267 refer_to_commit(opts, &msgbuf, commit);
2269 if (commit->parents && commit->parents->next) {
2270 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2271 refer_to_commit(opts, &msgbuf, parent);
2273 strbuf_addstr(&msgbuf, ".\n");
2274 } else {
2275 const char *p;
2277 base = parent;
2278 base_label = msg.parent_label;
2279 next = commit;
2280 next_label = msg.label;
2282 /* Append the commit log message to msgbuf. */
2283 if (find_commit_subject(msg.message, &p))
2284 strbuf_addstr(&msgbuf, p);
2286 if (opts->record_origin) {
2287 strbuf_complete_line(&msgbuf);
2288 if (!has_conforming_footer(&msgbuf, NULL, 0))
2289 strbuf_addch(&msgbuf, '\n');
2290 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2291 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2292 strbuf_addstr(&msgbuf, ")\n");
2294 if (!is_fixup(command))
2295 author = get_author(msg.message);
2298 if (command == TODO_REWORD)
2299 reword = 1;
2300 else if (is_fixup(command)) {
2301 if (update_squash_messages(r, command, commit,
2302 opts, item->flags)) {
2303 res = -1;
2304 goto leave;
2306 flags |= AMEND_MSG;
2307 if (!final_fixup)
2308 msg_file = rebase_path_squash_msg();
2309 else if (file_exists(rebase_path_fixup_msg())) {
2310 flags |= VERBATIM_MSG;
2311 msg_file = rebase_path_fixup_msg();
2312 } else {
2313 const char *dest = git_path_squash_msg(r);
2314 unlink(dest);
2315 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2316 res = error(_("could not rename '%s' to '%s'"),
2317 rebase_path_squash_msg(), dest);
2318 goto leave;
2320 unlink(git_path_merge_msg(r));
2321 msg_file = dest;
2322 flags |= EDIT_MSG;
2326 if (opts->signoff && !is_fixup(command))
2327 append_signoff(&msgbuf, 0, 0);
2329 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2330 res = -1;
2331 else if (!opts->strategy ||
2332 !strcmp(opts->strategy, "recursive") ||
2333 !strcmp(opts->strategy, "ort") ||
2334 command == TODO_REVERT) {
2335 res = do_recursive_merge(r, base, next, base_label, next_label,
2336 &head, &msgbuf, opts);
2337 if (res < 0)
2338 goto leave;
2340 res |= write_message(msgbuf.buf, msgbuf.len,
2341 git_path_merge_msg(r), 0);
2342 } else {
2343 struct commit_list *common = NULL;
2344 struct commit_list *remotes = NULL;
2346 res = write_message(msgbuf.buf, msgbuf.len,
2347 git_path_merge_msg(r), 0);
2349 commit_list_insert(base, &common);
2350 commit_list_insert(next, &remotes);
2351 res |= try_merge_command(r, opts->strategy,
2352 opts->xopts.nr, opts->xopts.v,
2353 common, oid_to_hex(&head), remotes);
2354 free_commit_list(common);
2355 free_commit_list(remotes);
2359 * If the merge was clean or if it failed due to conflict, we write
2360 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2361 * However, if the merge did not even start, then we don't want to
2362 * write it at all.
2364 if ((command == TODO_PICK || command == TODO_REWORD ||
2365 command == TODO_EDIT) && !opts->no_commit &&
2366 (res == 0 || res == 1) &&
2367 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2368 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2369 res = -1;
2370 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2371 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2372 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2373 res = -1;
2375 if (res) {
2376 error(command == TODO_REVERT
2377 ? _("could not revert %s... %s")
2378 : _("could not apply %s... %s"),
2379 short_commit_name(commit), msg.subject);
2380 print_advice(r, res == 1, opts);
2381 repo_rerere(r, opts->allow_rerere_auto);
2382 goto leave;
2385 drop_commit = 0;
2386 allow = allow_empty(r, opts, commit);
2387 if (allow < 0) {
2388 res = allow;
2389 goto leave;
2390 } else if (allow == 1) {
2391 flags |= ALLOW_EMPTY;
2392 } else if (allow == 2) {
2393 drop_commit = 1;
2394 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2395 NULL, 0);
2396 unlink(git_path_merge_msg(r));
2397 unlink(git_path_auto_merge(r));
2398 fprintf(stderr,
2399 _("dropping %s %s -- patch contents already upstream\n"),
2400 oid_to_hex(&commit->object.oid), msg.subject);
2401 } /* else allow == 0 and there's nothing special to do */
2402 if (!opts->no_commit && !drop_commit) {
2403 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2404 res = do_commit(r, msg_file, author, opts, flags,
2405 commit? &commit->object.oid : NULL);
2406 else
2407 res = error(_("unable to parse commit author"));
2408 *check_todo = !!(flags & EDIT_MSG);
2409 if (!res && reword) {
2410 fast_forward_edit:
2411 res = run_git_commit(NULL, opts, EDIT_MSG |
2412 VERIFY_MSG | AMEND_MSG |
2413 (flags & ALLOW_EMPTY));
2414 *check_todo = 1;
2419 if (!res && final_fixup) {
2420 unlink(rebase_path_fixup_msg());
2421 unlink(rebase_path_squash_msg());
2422 unlink(rebase_path_current_fixups());
2423 strbuf_reset(&opts->current_fixups);
2424 opts->current_fixup_count = 0;
2427 leave:
2428 free_message(commit, &msg);
2429 free(author);
2430 strbuf_release(&msgbuf);
2431 update_abort_safety_file();
2433 return res;
2436 static int prepare_revs(struct replay_opts *opts)
2439 * picking (but not reverting) ranges (but not individual revisions)
2440 * should be done in reverse
2442 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2443 opts->revs->reverse ^= 1;
2445 if (prepare_revision_walk(opts->revs))
2446 return error(_("revision walk setup failed"));
2448 return 0;
2451 static int read_and_refresh_cache(struct repository *r,
2452 struct replay_opts *opts)
2454 struct lock_file index_lock = LOCK_INIT;
2455 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2456 if (repo_read_index(r) < 0) {
2457 rollback_lock_file(&index_lock);
2458 return error(_("git %s: failed to read the index"),
2459 action_name(opts));
2461 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2463 if (index_fd >= 0) {
2464 if (write_locked_index(r->index, &index_lock,
2465 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2466 return error(_("git %s: failed to refresh the index"),
2467 action_name(opts));
2472 * If we are resolving merges in any way other than "ort", then
2473 * expand the sparse index.
2475 if (opts->strategy && strcmp(opts->strategy, "ort"))
2476 ensure_full_index(r->index);
2477 return 0;
2480 void todo_list_release(struct todo_list *todo_list)
2482 strbuf_release(&todo_list->buf);
2483 FREE_AND_NULL(todo_list->items);
2484 todo_list->nr = todo_list->alloc = 0;
2487 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2489 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2490 return todo_list->items + todo_list->nr++;
2493 const char *todo_item_get_arg(struct todo_list *todo_list,
2494 struct todo_item *item)
2496 return todo_list->buf.buf + item->arg_offset;
2499 static int is_command(enum todo_command command, const char **bol)
2501 const char *str = todo_command_info[command].str;
2502 const char nick = todo_command_info[command].c;
2503 const char *p = *bol;
2505 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2506 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2507 (*bol = p);
2510 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2512 switch (command) {
2513 case TODO_LABEL:
2515 * '#' is not a valid label as the merge command uses it to
2516 * separate merge parents from the commit subject.
2518 if (!strcmp(arg, "#") ||
2519 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2520 return error(_("'%s' is not a valid label"), arg);
2521 break;
2523 case TODO_UPDATE_REF:
2524 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2525 return error(_("'%s' is not a valid refname"), arg);
2526 if (check_refname_format(arg, 0))
2527 return error(_("update-ref requires a fully qualified "
2528 "refname e.g. refs/heads/%s"), arg);
2529 break;
2531 default:
2532 BUG("unexpected todo_command");
2535 return 0;
2538 static int parse_insn_line(struct repository *r, struct todo_item *item,
2539 const char *buf, const char *bol, char *eol)
2541 struct object_id commit_oid;
2542 char *end_of_object_name;
2543 int i, saved, status, padding;
2545 item->flags = 0;
2547 /* left-trim */
2548 bol += strspn(bol, " \t");
2550 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2551 item->command = TODO_COMMENT;
2552 item->commit = NULL;
2553 item->arg_offset = bol - buf;
2554 item->arg_len = eol - bol;
2555 return 0;
2558 for (i = 0; i < TODO_COMMENT; i++)
2559 if (is_command(i, &bol)) {
2560 item->command = i;
2561 break;
2563 if (i >= TODO_COMMENT)
2564 return error(_("invalid command '%.*s'"),
2565 (int)strcspn(bol, " \t\r\n"), bol);
2567 /* Eat up extra spaces/ tabs before object name */
2568 padding = strspn(bol, " \t");
2569 bol += padding;
2571 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2572 if (bol != eol)
2573 return error(_("%s does not accept arguments: '%s'"),
2574 command_to_string(item->command), bol);
2575 item->commit = NULL;
2576 item->arg_offset = bol - buf;
2577 item->arg_len = eol - bol;
2578 return 0;
2581 if (!padding)
2582 return error(_("missing arguments for %s"),
2583 command_to_string(item->command));
2585 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2586 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2587 int ret = 0;
2589 item->commit = NULL;
2590 item->arg_offset = bol - buf;
2591 item->arg_len = (int)(eol - bol);
2592 if (item->command == TODO_LABEL ||
2593 item->command == TODO_UPDATE_REF) {
2594 saved = *eol;
2595 *eol = '\0';
2596 ret = check_label_or_ref_arg(item->command, bol);
2597 *eol = saved;
2599 return ret;
2602 if (item->command == TODO_FIXUP) {
2603 if (skip_prefix(bol, "-C", &bol)) {
2604 bol += strspn(bol, " \t");
2605 item->flags |= TODO_REPLACE_FIXUP_MSG;
2606 } else if (skip_prefix(bol, "-c", &bol)) {
2607 bol += strspn(bol, " \t");
2608 item->flags |= TODO_EDIT_FIXUP_MSG;
2612 if (item->command == TODO_MERGE) {
2613 if (skip_prefix(bol, "-C", &bol))
2614 bol += strspn(bol, " \t");
2615 else if (skip_prefix(bol, "-c", &bol)) {
2616 bol += strspn(bol, " \t");
2617 item->flags |= TODO_EDIT_MERGE_MSG;
2618 } else {
2619 item->flags |= TODO_EDIT_MERGE_MSG;
2620 item->commit = NULL;
2621 item->arg_offset = bol - buf;
2622 item->arg_len = (int)(eol - bol);
2623 return 0;
2627 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2628 saved = *end_of_object_name;
2629 *end_of_object_name = '\0';
2630 status = repo_get_oid(r, bol, &commit_oid);
2631 if (status < 0)
2632 error(_("could not parse '%s'"), bol); /* return later */
2633 *end_of_object_name = saved;
2635 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2636 item->arg_offset = bol - buf;
2637 item->arg_len = (int)(eol - bol);
2639 if (status < 0)
2640 return status;
2642 item->commit = lookup_commit_reference(r, &commit_oid);
2643 return item->commit ? 0 : -1;
2646 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2648 const char *todo_file, *bol;
2649 struct strbuf buf = STRBUF_INIT;
2650 int ret = 0;
2652 todo_file = git_path_todo_file();
2653 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2654 if (errno == ENOENT || errno == ENOTDIR)
2655 return -1;
2656 else
2657 return error_errno("unable to open '%s'", todo_file);
2659 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2660 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2661 *action = REPLAY_PICK;
2662 else if (is_command(TODO_REVERT, &bol) &&
2663 (*bol == ' ' || *bol == '\t'))
2664 *action = REPLAY_REVERT;
2665 else
2666 ret = -1;
2668 strbuf_release(&buf);
2670 return ret;
2673 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2674 struct todo_list *todo_list)
2676 struct todo_item *item;
2677 char *p = buf, *next_p;
2678 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2680 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2682 for (i = 1; *p; i++, p = next_p) {
2683 char *eol = strchrnul(p, '\n');
2685 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2687 if (p != eol && eol[-1] == '\r')
2688 eol--; /* strip Carriage Return */
2690 item = append_new_todo(todo_list);
2691 item->offset_in_buf = p - todo_list->buf.buf;
2692 if (parse_insn_line(r, item, buf, p, eol)) {
2693 res = error(_("invalid line %d: %.*s"),
2694 i, (int)(eol - p), p);
2695 item->command = TODO_COMMENT + 1;
2696 item->arg_offset = p - buf;
2697 item->arg_len = (int)(eol - p);
2698 item->commit = NULL;
2701 if (item->command != TODO_COMMENT)
2702 todo_list->total_nr++;
2704 if (fixup_okay)
2705 ; /* do nothing */
2706 else if (is_fixup(item->command))
2707 return error(_("cannot '%s' without a previous commit"),
2708 command_to_string(item->command));
2709 else if (!is_noop(item->command))
2710 fixup_okay = 1;
2713 return res;
2716 static int count_commands(struct todo_list *todo_list)
2718 int count = 0, i;
2720 for (i = 0; i < todo_list->nr; i++)
2721 if (todo_list->items[i].command != TODO_COMMENT)
2722 count++;
2724 return count;
2727 static int get_item_line_offset(struct todo_list *todo_list, int index)
2729 return index < todo_list->nr ?
2730 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2733 static const char *get_item_line(struct todo_list *todo_list, int index)
2735 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2738 static int get_item_line_length(struct todo_list *todo_list, int index)
2740 return get_item_line_offset(todo_list, index + 1)
2741 - get_item_line_offset(todo_list, index);
2744 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2746 int fd;
2747 ssize_t len;
2749 fd = open(path, O_RDONLY);
2750 if (fd < 0)
2751 return error_errno(_("could not open '%s'"), path);
2752 len = strbuf_read(sb, fd, 0);
2753 close(fd);
2754 if (len < 0)
2755 return error(_("could not read '%s'."), path);
2756 return len;
2759 static int have_finished_the_last_pick(void)
2761 struct strbuf buf = STRBUF_INIT;
2762 const char *eol;
2763 const char *todo_path = git_path_todo_file();
2764 int ret = 0;
2766 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2767 if (errno == ENOENT) {
2768 return 0;
2769 } else {
2770 error_errno("unable to open '%s'", todo_path);
2771 return 0;
2774 /* If there is only one line then we are done */
2775 eol = strchr(buf.buf, '\n');
2776 if (!eol || !eol[1])
2777 ret = 1;
2779 strbuf_release(&buf);
2781 return ret;
2784 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2786 struct replay_opts opts = REPLAY_OPTS_INIT;
2787 int need_cleanup = 0;
2789 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2790 if (!refs_delete_ref(get_main_ref_store(r), "",
2791 "CHERRY_PICK_HEAD", NULL, 0) &&
2792 verbose)
2793 warning(_("cancelling a cherry picking in progress"));
2794 opts.action = REPLAY_PICK;
2795 need_cleanup = 1;
2798 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2799 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2800 NULL, 0) &&
2801 verbose)
2802 warning(_("cancelling a revert in progress"));
2803 opts.action = REPLAY_REVERT;
2804 need_cleanup = 1;
2807 unlink(git_path_auto_merge(r));
2809 if (!need_cleanup)
2810 return;
2812 if (!have_finished_the_last_pick())
2813 return;
2815 sequencer_remove_state(&opts);
2818 static void todo_list_write_total_nr(struct todo_list *todo_list)
2820 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2822 if (f) {
2823 fprintf(f, "%d\n", todo_list->total_nr);
2824 fclose(f);
2828 static int read_populate_todo(struct repository *r,
2829 struct todo_list *todo_list,
2830 struct replay_opts *opts)
2832 const char *todo_file = get_todo_path(opts);
2833 int res;
2835 strbuf_reset(&todo_list->buf);
2836 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2837 return -1;
2839 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2840 if (res) {
2841 if (is_rebase_i(opts))
2842 return error(_("please fix this using "
2843 "'git rebase --edit-todo'."));
2844 return error(_("unusable instruction sheet: '%s'"), todo_file);
2847 if (!todo_list->nr &&
2848 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2849 return error(_("no commits parsed."));
2851 if (!is_rebase_i(opts)) {
2852 enum todo_command valid =
2853 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2854 int i;
2856 for (i = 0; i < todo_list->nr; i++)
2857 if (valid == todo_list->items[i].command)
2858 continue;
2859 else if (valid == TODO_PICK)
2860 return error(_("cannot cherry-pick during a revert."));
2861 else
2862 return error(_("cannot revert during a cherry-pick."));
2865 if (is_rebase_i(opts)) {
2866 struct todo_list done = TODO_LIST_INIT;
2868 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2869 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2870 todo_list->done_nr = count_commands(&done);
2871 else
2872 todo_list->done_nr = 0;
2874 todo_list->total_nr = todo_list->done_nr
2875 + count_commands(todo_list);
2876 todo_list_release(&done);
2878 todo_list_write_total_nr(todo_list);
2881 return 0;
2884 static int git_config_string_dup(char **dest,
2885 const char *var, const char *value)
2887 if (!value)
2888 return config_error_nonbool(var);
2889 free(*dest);
2890 *dest = xstrdup(value);
2891 return 0;
2894 static int populate_opts_cb(const char *key, const char *value,
2895 const struct config_context *ctx,
2896 void *data)
2898 struct replay_opts *opts = data;
2899 int error_flag = 1;
2901 if (!value)
2902 error_flag = 0;
2903 else if (!strcmp(key, "options.no-commit"))
2904 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2905 else if (!strcmp(key, "options.edit"))
2906 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2907 else if (!strcmp(key, "options.allow-empty"))
2908 opts->allow_empty =
2909 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2910 else if (!strcmp(key, "options.allow-empty-message"))
2911 opts->allow_empty_message =
2912 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2913 else if (!strcmp(key, "options.keep-redundant-commits"))
2914 opts->keep_redundant_commits =
2915 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2916 else if (!strcmp(key, "options.signoff"))
2917 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2918 else if (!strcmp(key, "options.record-origin"))
2919 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2920 else if (!strcmp(key, "options.allow-ff"))
2921 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2922 else if (!strcmp(key, "options.mainline"))
2923 opts->mainline = git_config_int(key, value, ctx->kvi);
2924 else if (!strcmp(key, "options.strategy"))
2925 git_config_string_dup(&opts->strategy, key, value);
2926 else if (!strcmp(key, "options.gpg-sign"))
2927 git_config_string_dup(&opts->gpg_sign, key, value);
2928 else if (!strcmp(key, "options.strategy-option")) {
2929 strvec_push(&opts->xopts, value);
2930 } else if (!strcmp(key, "options.allow-rerere-auto"))
2931 opts->allow_rerere_auto =
2932 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
2933 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2934 else if (!strcmp(key, "options.default-msg-cleanup")) {
2935 opts->explicit_cleanup = 1;
2936 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2937 } else
2938 return error(_("invalid key: %s"), key);
2940 if (!error_flag)
2941 return error(_("invalid value for '%s': '%s'"), key, value);
2943 return 0;
2946 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2948 int i;
2949 int count;
2950 const char **argv;
2951 char *strategy_opts_string = raw_opts;
2953 if (*strategy_opts_string == ' ')
2954 strategy_opts_string++;
2956 count = split_cmdline(strategy_opts_string, &argv);
2957 if (count < 0)
2958 BUG("could not split '%s': %s", strategy_opts_string,
2959 split_cmdline_strerror(count));
2960 for (i = 0; i < count; i++) {
2961 const char *arg = argv[i];
2963 skip_prefix(arg, "--", &arg);
2964 strvec_push(&opts->xopts, arg);
2966 free(argv);
2969 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2971 strbuf_reset(buf);
2972 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2973 return;
2974 opts->strategy = strbuf_detach(buf, NULL);
2975 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2976 return;
2978 parse_strategy_opts(opts, buf->buf);
2981 static int read_populate_opts(struct replay_opts *opts)
2983 if (is_rebase_i(opts)) {
2984 struct strbuf buf = STRBUF_INIT;
2985 int ret = 0;
2987 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2988 READ_ONELINER_SKIP_IF_EMPTY)) {
2989 if (!starts_with(buf.buf, "-S"))
2990 strbuf_reset(&buf);
2991 else {
2992 free(opts->gpg_sign);
2993 opts->gpg_sign = xstrdup(buf.buf + 2);
2995 strbuf_reset(&buf);
2998 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2999 READ_ONELINER_SKIP_IF_EMPTY)) {
3000 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3001 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3002 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3003 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3004 strbuf_reset(&buf);
3007 if (file_exists(rebase_path_verbose()))
3008 opts->verbose = 1;
3010 if (file_exists(rebase_path_quiet()))
3011 opts->quiet = 1;
3013 if (file_exists(rebase_path_signoff())) {
3014 opts->allow_ff = 0;
3015 opts->signoff = 1;
3018 if (file_exists(rebase_path_cdate_is_adate())) {
3019 opts->allow_ff = 0;
3020 opts->committer_date_is_author_date = 1;
3023 if (file_exists(rebase_path_ignore_date())) {
3024 opts->allow_ff = 0;
3025 opts->ignore_date = 1;
3028 if (file_exists(rebase_path_reschedule_failed_exec()))
3029 opts->reschedule_failed_exec = 1;
3030 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3031 opts->reschedule_failed_exec = 0;
3033 if (file_exists(rebase_path_drop_redundant_commits()))
3034 opts->drop_redundant_commits = 1;
3036 if (file_exists(rebase_path_keep_redundant_commits()))
3037 opts->keep_redundant_commits = 1;
3039 read_strategy_opts(opts, &buf);
3040 strbuf_reset(&buf);
3042 if (read_oneliner(&opts->current_fixups,
3043 rebase_path_current_fixups(),
3044 READ_ONELINER_SKIP_IF_EMPTY)) {
3045 const char *p = opts->current_fixups.buf;
3046 opts->current_fixup_count = 1;
3047 while ((p = strchr(p, '\n'))) {
3048 opts->current_fixup_count++;
3049 p++;
3053 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3054 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3055 ret = error(_("unusable squash-onto"));
3056 goto done_rebase_i;
3058 opts->have_squash_onto = 1;
3061 done_rebase_i:
3062 strbuf_release(&buf);
3063 return ret;
3066 if (!file_exists(git_path_opts_file()))
3067 return 0;
3069 * The function git_parse_source(), called from git_config_from_file(),
3070 * may die() in case of a syntactically incorrect file. We do not care
3071 * about this case, though, because we wrote that file ourselves, so we
3072 * are pretty certain that it is syntactically correct.
3074 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3075 return error(_("malformed options sheet: '%s'"),
3076 git_path_opts_file());
3077 return 0;
3080 static void write_strategy_opts(struct replay_opts *opts)
3082 struct strbuf buf = STRBUF_INIT;
3085 * Quote strategy options so that they can be read correctly
3086 * by split_cmdline().
3088 quote_cmdline(&buf, opts->xopts.v);
3089 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3090 strbuf_release(&buf);
3093 int write_basic_state(struct replay_opts *opts, const char *head_name,
3094 struct commit *onto, const struct object_id *orig_head)
3096 if (head_name)
3097 write_file(rebase_path_head_name(), "%s\n", head_name);
3098 if (onto)
3099 write_file(rebase_path_onto(), "%s\n",
3100 oid_to_hex(&onto->object.oid));
3101 if (orig_head)
3102 write_file(rebase_path_orig_head(), "%s\n",
3103 oid_to_hex(orig_head));
3105 if (opts->quiet)
3106 write_file(rebase_path_quiet(), "%s", "");
3107 if (opts->verbose)
3108 write_file(rebase_path_verbose(), "%s", "");
3109 if (opts->strategy)
3110 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3111 if (opts->xopts.nr > 0)
3112 write_strategy_opts(opts);
3114 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3115 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3116 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3117 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3119 if (opts->gpg_sign)
3120 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3121 if (opts->signoff)
3122 write_file(rebase_path_signoff(), "--signoff\n");
3123 if (opts->drop_redundant_commits)
3124 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3125 if (opts->keep_redundant_commits)
3126 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3127 if (opts->committer_date_is_author_date)
3128 write_file(rebase_path_cdate_is_adate(), "%s", "");
3129 if (opts->ignore_date)
3130 write_file(rebase_path_ignore_date(), "%s", "");
3131 if (opts->reschedule_failed_exec)
3132 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3133 else
3134 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3136 return 0;
3139 static int walk_revs_populate_todo(struct todo_list *todo_list,
3140 struct replay_opts *opts)
3142 enum todo_command command = opts->action == REPLAY_PICK ?
3143 TODO_PICK : TODO_REVERT;
3144 const char *command_string = todo_command_info[command].str;
3145 const char *encoding;
3146 struct commit *commit;
3148 if (prepare_revs(opts))
3149 return -1;
3151 encoding = get_log_output_encoding();
3153 while ((commit = get_revision(opts->revs))) {
3154 struct todo_item *item = append_new_todo(todo_list);
3155 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3156 commit, NULL,
3157 encoding);
3158 const char *subject;
3159 int subject_len;
3161 item->command = command;
3162 item->commit = commit;
3163 item->arg_offset = 0;
3164 item->arg_len = 0;
3165 item->offset_in_buf = todo_list->buf.len;
3166 subject_len = find_commit_subject(commit_buffer, &subject);
3167 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3168 short_commit_name(commit), subject_len, subject);
3169 repo_unuse_commit_buffer(the_repository, commit,
3170 commit_buffer);
3173 if (!todo_list->nr)
3174 return error(_("empty commit set passed"));
3176 return 0;
3179 static int create_seq_dir(struct repository *r)
3181 enum replay_action action;
3182 const char *in_progress_error = NULL;
3183 const char *in_progress_advice = NULL;
3184 unsigned int advise_skip =
3185 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3186 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3188 if (!sequencer_get_last_command(r, &action)) {
3189 switch (action) {
3190 case REPLAY_REVERT:
3191 in_progress_error = _("revert is already in progress");
3192 in_progress_advice =
3193 _("try \"git revert (--continue | %s--abort | --quit)\"");
3194 break;
3195 case REPLAY_PICK:
3196 in_progress_error = _("cherry-pick is already in progress");
3197 in_progress_advice =
3198 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3199 break;
3200 default:
3201 BUG("unexpected action in create_seq_dir");
3204 if (in_progress_error) {
3205 error("%s", in_progress_error);
3206 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3207 advise(in_progress_advice,
3208 advise_skip ? "--skip | " : "");
3209 return -1;
3211 if (mkdir(git_path_seq_dir(), 0777) < 0)
3212 return error_errno(_("could not create sequencer directory '%s'"),
3213 git_path_seq_dir());
3215 return 0;
3218 static int save_head(const char *head)
3220 return write_message(head, strlen(head), git_path_head_file(), 1);
3223 static int rollback_is_safe(void)
3225 struct strbuf sb = STRBUF_INIT;
3226 struct object_id expected_head, actual_head;
3228 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3229 strbuf_trim(&sb);
3230 if (get_oid_hex(sb.buf, &expected_head)) {
3231 strbuf_release(&sb);
3232 die(_("could not parse %s"), git_path_abort_safety_file());
3234 strbuf_release(&sb);
3236 else if (errno == ENOENT)
3237 oidclr(&expected_head);
3238 else
3239 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3241 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3242 oidclr(&actual_head);
3244 return oideq(&actual_head, &expected_head);
3247 static int reset_merge(const struct object_id *oid)
3249 struct child_process cmd = CHILD_PROCESS_INIT;
3251 cmd.git_cmd = 1;
3252 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3254 if (!is_null_oid(oid))
3255 strvec_push(&cmd.args, oid_to_hex(oid));
3257 return run_command(&cmd);
3260 static int rollback_single_pick(struct repository *r)
3262 struct object_id head_oid;
3264 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3265 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3266 return error(_("no cherry-pick or revert in progress"));
3267 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3268 return error(_("cannot resolve HEAD"));
3269 if (is_null_oid(&head_oid))
3270 return error(_("cannot abort from a branch yet to be born"));
3271 return reset_merge(&head_oid);
3274 static int skip_single_pick(void)
3276 struct object_id head;
3278 if (read_ref_full("HEAD", 0, &head, NULL))
3279 return error(_("cannot resolve HEAD"));
3280 return reset_merge(&head);
3283 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3285 FILE *f;
3286 struct object_id oid;
3287 struct strbuf buf = STRBUF_INIT;
3288 const char *p;
3290 f = fopen(git_path_head_file(), "r");
3291 if (!f && errno == ENOENT) {
3293 * There is no multiple-cherry-pick in progress.
3294 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3295 * a single-cherry-pick in progress, abort that.
3297 return rollback_single_pick(r);
3299 if (!f)
3300 return error_errno(_("cannot open '%s'"), git_path_head_file());
3301 if (strbuf_getline_lf(&buf, f)) {
3302 error(_("cannot read '%s': %s"), git_path_head_file(),
3303 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3304 fclose(f);
3305 goto fail;
3307 fclose(f);
3308 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3309 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3310 git_path_head_file());
3311 goto fail;
3313 if (is_null_oid(&oid)) {
3314 error(_("cannot abort from a branch yet to be born"));
3315 goto fail;
3318 if (!rollback_is_safe()) {
3319 /* Do not error, just do not rollback */
3320 warning(_("You seem to have moved HEAD. "
3321 "Not rewinding, check your HEAD!"));
3322 } else
3323 if (reset_merge(&oid))
3324 goto fail;
3325 strbuf_release(&buf);
3326 return sequencer_remove_state(opts);
3327 fail:
3328 strbuf_release(&buf);
3329 return -1;
3332 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3334 enum replay_action action = -1;
3335 sequencer_get_last_command(r, &action);
3338 * Check whether the subcommand requested to skip the commit is actually
3339 * in progress and that it's safe to skip the commit.
3341 * opts->action tells us which subcommand requested to skip the commit.
3342 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3343 * action is in progress and we can skip the commit.
3345 * Otherwise we check that the last instruction was related to the
3346 * particular subcommand we're trying to execute and barf if that's not
3347 * the case.
3349 * Finally we check that the rollback is "safe", i.e., has the HEAD
3350 * moved? In this case, it doesn't make sense to "reset the merge" and
3351 * "skip the commit" as the user already handled this by committing. But
3352 * we'd not want to barf here, instead give advice on how to proceed. We
3353 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3354 * it gets removed when the user commits, so if it still exists we're
3355 * sure the user can't have committed before.
3357 switch (opts->action) {
3358 case REPLAY_REVERT:
3359 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3360 if (action != REPLAY_REVERT)
3361 return error(_("no revert in progress"));
3362 if (!rollback_is_safe())
3363 goto give_advice;
3365 break;
3366 case REPLAY_PICK:
3367 if (!refs_ref_exists(get_main_ref_store(r),
3368 "CHERRY_PICK_HEAD")) {
3369 if (action != REPLAY_PICK)
3370 return error(_("no cherry-pick in progress"));
3371 if (!rollback_is_safe())
3372 goto give_advice;
3374 break;
3375 default:
3376 BUG("unexpected action in sequencer_skip");
3379 if (skip_single_pick())
3380 return error(_("failed to skip the commit"));
3381 if (!is_directory(git_path_seq_dir()))
3382 return 0;
3384 return sequencer_continue(r, opts);
3386 give_advice:
3387 error(_("there is nothing to skip"));
3389 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3390 advise(_("have you committed already?\n"
3391 "try \"git %s --continue\""),
3392 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3394 return -1;
3397 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3399 struct lock_file todo_lock = LOCK_INIT;
3400 const char *todo_path = get_todo_path(opts);
3401 int next = todo_list->current, offset, fd;
3404 * rebase -i writes "git-rebase-todo" without the currently executing
3405 * command, appending it to "done" instead.
3407 if (is_rebase_i(opts))
3408 next++;
3410 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3411 if (fd < 0)
3412 return error_errno(_("could not lock '%s'"), todo_path);
3413 offset = get_item_line_offset(todo_list, next);
3414 if (write_in_full(fd, todo_list->buf.buf + offset,
3415 todo_list->buf.len - offset) < 0)
3416 return error_errno(_("could not write to '%s'"), todo_path);
3417 if (commit_lock_file(&todo_lock) < 0)
3418 return error(_("failed to finalize '%s'"), todo_path);
3420 if (is_rebase_i(opts) && next > 0) {
3421 const char *done = rebase_path_done();
3422 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3423 int ret = 0;
3425 if (fd < 0)
3426 return 0;
3427 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3428 get_item_line_length(todo_list, next - 1))
3429 < 0)
3430 ret = error_errno(_("could not write to '%s'"), done);
3431 if (close(fd) < 0)
3432 ret = error_errno(_("failed to finalize '%s'"), done);
3433 return ret;
3435 return 0;
3438 static int save_opts(struct replay_opts *opts)
3440 const char *opts_file = git_path_opts_file();
3441 int res = 0;
3443 if (opts->no_commit)
3444 res |= git_config_set_in_file_gently(opts_file,
3445 "options.no-commit", "true");
3446 if (opts->edit >= 0)
3447 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3448 opts->edit ? "true" : "false");
3449 if (opts->allow_empty)
3450 res |= git_config_set_in_file_gently(opts_file,
3451 "options.allow-empty", "true");
3452 if (opts->allow_empty_message)
3453 res |= git_config_set_in_file_gently(opts_file,
3454 "options.allow-empty-message", "true");
3455 if (opts->keep_redundant_commits)
3456 res |= git_config_set_in_file_gently(opts_file,
3457 "options.keep-redundant-commits", "true");
3458 if (opts->signoff)
3459 res |= git_config_set_in_file_gently(opts_file,
3460 "options.signoff", "true");
3461 if (opts->record_origin)
3462 res |= git_config_set_in_file_gently(opts_file,
3463 "options.record-origin", "true");
3464 if (opts->allow_ff)
3465 res |= git_config_set_in_file_gently(opts_file,
3466 "options.allow-ff", "true");
3467 if (opts->mainline) {
3468 struct strbuf buf = STRBUF_INIT;
3469 strbuf_addf(&buf, "%d", opts->mainline);
3470 res |= git_config_set_in_file_gently(opts_file,
3471 "options.mainline", buf.buf);
3472 strbuf_release(&buf);
3474 if (opts->strategy)
3475 res |= git_config_set_in_file_gently(opts_file,
3476 "options.strategy", opts->strategy);
3477 if (opts->gpg_sign)
3478 res |= git_config_set_in_file_gently(opts_file,
3479 "options.gpg-sign", opts->gpg_sign);
3480 for (size_t i = 0; i < opts->xopts.nr; i++)
3481 res |= git_config_set_multivar_in_file_gently(opts_file,
3482 "options.strategy-option",
3483 opts->xopts.v[i], "^$", 0);
3484 if (opts->allow_rerere_auto)
3485 res |= git_config_set_in_file_gently(opts_file,
3486 "options.allow-rerere-auto",
3487 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3488 "true" : "false");
3490 if (opts->explicit_cleanup)
3491 res |= git_config_set_in_file_gently(opts_file,
3492 "options.default-msg-cleanup",
3493 describe_cleanup_mode(opts->default_msg_cleanup));
3494 return res;
3497 static int make_patch(struct repository *r,
3498 struct commit *commit,
3499 struct replay_opts *opts)
3501 struct strbuf buf = STRBUF_INIT;
3502 struct rev_info log_tree_opt;
3503 const char *subject;
3504 char hex[GIT_MAX_HEXSZ + 1];
3505 int res = 0;
3507 oid_to_hex_r(hex, &commit->object.oid);
3508 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3509 return -1;
3510 res |= write_rebase_head(&commit->object.oid);
3512 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3513 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3514 repo_init_revisions(r, &log_tree_opt, NULL);
3515 log_tree_opt.abbrev = 0;
3516 log_tree_opt.diff = 1;
3517 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3518 log_tree_opt.disable_stdin = 1;
3519 log_tree_opt.no_commit_id = 1;
3520 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3521 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3522 if (!log_tree_opt.diffopt.file)
3523 res |= error_errno(_("could not open '%s'"), buf.buf);
3524 else {
3525 res |= log_tree_commit(&log_tree_opt, commit);
3526 fclose(log_tree_opt.diffopt.file);
3528 strbuf_reset(&buf);
3530 strbuf_addf(&buf, "%s/message", get_dir(opts));
3531 if (!file_exists(buf.buf)) {
3532 const char *encoding = get_commit_output_encoding();
3533 const char *commit_buffer = repo_logmsg_reencode(r,
3534 commit, NULL,
3535 encoding);
3536 find_commit_subject(commit_buffer, &subject);
3537 res |= write_message(subject, strlen(subject), buf.buf, 1);
3538 repo_unuse_commit_buffer(r, commit,
3539 commit_buffer);
3541 strbuf_release(&buf);
3542 release_revisions(&log_tree_opt);
3544 return res;
3547 static int intend_to_amend(void)
3549 struct object_id head;
3550 char *p;
3552 if (repo_get_oid(the_repository, "HEAD", &head))
3553 return error(_("cannot read HEAD"));
3555 p = oid_to_hex(&head);
3556 return write_message(p, strlen(p), rebase_path_amend(), 1);
3559 static int error_with_patch(struct repository *r,
3560 struct commit *commit,
3561 const char *subject, int subject_len,
3562 struct replay_opts *opts,
3563 int exit_code, int to_amend)
3565 if (commit) {
3566 if (make_patch(r, commit, opts))
3567 return -1;
3568 } else if (copy_file(rebase_path_message(),
3569 git_path_merge_msg(r), 0666))
3570 return error(_("unable to copy '%s' to '%s'"),
3571 git_path_merge_msg(r), rebase_path_message());
3573 if (to_amend) {
3574 if (intend_to_amend())
3575 return -1;
3577 fprintf(stderr,
3578 _("You can amend the commit now, with\n"
3579 "\n"
3580 " git commit --amend %s\n"
3581 "\n"
3582 "Once you are satisfied with your changes, run\n"
3583 "\n"
3584 " git rebase --continue\n"),
3585 gpg_sign_opt_quoted(opts));
3586 } else if (exit_code) {
3587 if (commit)
3588 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3589 short_commit_name(commit), subject_len, subject);
3590 else
3592 * We don't have the hash of the parent so
3593 * just print the line from the todo file.
3595 fprintf_ln(stderr, _("Could not merge %.*s"),
3596 subject_len, subject);
3599 return exit_code;
3602 static int error_failed_squash(struct repository *r,
3603 struct commit *commit,
3604 struct replay_opts *opts,
3605 int subject_len,
3606 const char *subject)
3608 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3609 return error(_("could not copy '%s' to '%s'"),
3610 rebase_path_squash_msg(), rebase_path_message());
3611 unlink(git_path_merge_msg(r));
3612 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3613 return error(_("could not copy '%s' to '%s'"),
3614 rebase_path_message(),
3615 git_path_merge_msg(r));
3616 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3619 static int do_exec(struct repository *r, const char *command_line)
3621 struct child_process cmd = CHILD_PROCESS_INIT;
3622 int dirty, status;
3624 fprintf(stderr, _("Executing: %s\n"), command_line);
3625 cmd.use_shell = 1;
3626 strvec_push(&cmd.args, command_line);
3627 status = run_command(&cmd);
3629 /* force re-reading of the cache */
3630 discard_index(r->index);
3631 if (repo_read_index(r) < 0)
3632 return error(_("could not read index"));
3634 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3636 if (status) {
3637 warning(_("execution failed: %s\n%s"
3638 "You can fix the problem, and then run\n"
3639 "\n"
3640 " git rebase --continue\n"
3641 "\n"),
3642 command_line,
3643 dirty ? _("and made changes to the index and/or the "
3644 "working tree.\n") : "");
3645 if (status == 127)
3646 /* command not found */
3647 status = 1;
3648 } else if (dirty) {
3649 warning(_("execution succeeded: %s\nbut "
3650 "left changes to the index and/or the working tree.\n"
3651 "Commit or stash your changes, and then run\n"
3652 "\n"
3653 " git rebase --continue\n"
3654 "\n"), command_line);
3655 status = 1;
3658 return status;
3661 __attribute__((format (printf, 2, 3)))
3662 static int safe_append(const char *filename, const char *fmt, ...)
3664 va_list ap;
3665 struct lock_file lock = LOCK_INIT;
3666 int fd = hold_lock_file_for_update(&lock, filename,
3667 LOCK_REPORT_ON_ERROR);
3668 struct strbuf buf = STRBUF_INIT;
3670 if (fd < 0)
3671 return -1;
3673 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3674 error_errno(_("could not read '%s'"), filename);
3675 rollback_lock_file(&lock);
3676 return -1;
3678 strbuf_complete(&buf, '\n');
3679 va_start(ap, fmt);
3680 strbuf_vaddf(&buf, fmt, ap);
3681 va_end(ap);
3683 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3684 error_errno(_("could not write to '%s'"), filename);
3685 strbuf_release(&buf);
3686 rollback_lock_file(&lock);
3687 return -1;
3689 if (commit_lock_file(&lock) < 0) {
3690 strbuf_release(&buf);
3691 return error(_("failed to finalize '%s'"), filename);
3694 strbuf_release(&buf);
3695 return 0;
3698 static int do_label(struct repository *r, const char *name, int len)
3700 struct ref_store *refs = get_main_ref_store(r);
3701 struct ref_transaction *transaction;
3702 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3703 struct strbuf msg = STRBUF_INIT;
3704 int ret = 0;
3705 struct object_id head_oid;
3707 if (len == 1 && *name == '#')
3708 return error(_("illegal label name: '%.*s'"), len, name);
3710 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3711 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3713 transaction = ref_store_transaction_begin(refs, &err);
3714 if (!transaction) {
3715 error("%s", err.buf);
3716 ret = -1;
3717 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3718 error(_("could not read HEAD"));
3719 ret = -1;
3720 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3721 NULL, 0, msg.buf, &err) < 0 ||
3722 ref_transaction_commit(transaction, &err)) {
3723 error("%s", err.buf);
3724 ret = -1;
3726 ref_transaction_free(transaction);
3727 strbuf_release(&err);
3728 strbuf_release(&msg);
3730 if (!ret)
3731 ret = safe_append(rebase_path_refs_to_delete(),
3732 "%s\n", ref_name.buf);
3733 strbuf_release(&ref_name);
3735 return ret;
3738 static const char *sequencer_reflog_action(struct replay_opts *opts)
3740 if (!opts->reflog_action) {
3741 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3742 opts->reflog_action =
3743 xstrdup(opts->reflog_action ? opts->reflog_action
3744 : action_name(opts));
3747 return opts->reflog_action;
3750 __attribute__((format (printf, 3, 4)))
3751 static const char *reflog_message(struct replay_opts *opts,
3752 const char *sub_action, const char *fmt, ...)
3754 va_list ap;
3755 static struct strbuf buf = STRBUF_INIT;
3757 va_start(ap, fmt);
3758 strbuf_reset(&buf);
3759 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3760 if (sub_action)
3761 strbuf_addf(&buf, " (%s)", sub_action);
3762 if (fmt) {
3763 strbuf_addstr(&buf, ": ");
3764 strbuf_vaddf(&buf, fmt, ap);
3766 va_end(ap);
3768 return buf.buf;
3771 static struct commit *lookup_label(struct repository *r, const char *label,
3772 int len, struct strbuf *buf)
3774 struct commit *commit;
3775 struct object_id oid;
3777 strbuf_reset(buf);
3778 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3779 if (!read_ref(buf->buf, &oid)) {
3780 commit = lookup_commit_object(r, &oid);
3781 } else {
3782 /* fall back to non-rewritten ref or commit */
3783 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3784 commit = lookup_commit_reference_by_name(buf->buf);
3787 if (!commit)
3788 error(_("could not resolve '%s'"), buf->buf);
3790 return commit;
3793 static int do_reset(struct repository *r,
3794 const char *name, int len,
3795 struct replay_opts *opts)
3797 struct strbuf ref_name = STRBUF_INIT;
3798 struct object_id oid;
3799 struct lock_file lock = LOCK_INIT;
3800 struct tree_desc desc = { 0 };
3801 struct tree *tree;
3802 struct unpack_trees_options unpack_tree_opts = { 0 };
3803 int ret = 0;
3805 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3806 return -1;
3808 if (len == 10 && !strncmp("[new root]", name, len)) {
3809 if (!opts->have_squash_onto) {
3810 const char *hex;
3811 if (commit_tree("", 0, the_hash_algo->empty_tree,
3812 NULL, &opts->squash_onto,
3813 NULL, NULL))
3814 return error(_("writing fake root commit"));
3815 opts->have_squash_onto = 1;
3816 hex = oid_to_hex(&opts->squash_onto);
3817 if (write_message(hex, strlen(hex),
3818 rebase_path_squash_onto(), 0))
3819 return error(_("writing squash-onto"));
3821 oidcpy(&oid, &opts->squash_onto);
3822 } else {
3823 int i;
3824 struct commit *commit;
3826 /* Determine the length of the label */
3827 for (i = 0; i < len; i++)
3828 if (isspace(name[i]))
3829 break;
3830 len = i;
3832 commit = lookup_label(r, name, len, &ref_name);
3833 if (!commit) {
3834 ret = -1;
3835 goto cleanup;
3837 oid = commit->object.oid;
3840 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3841 unpack_tree_opts.head_idx = 1;
3842 unpack_tree_opts.src_index = r->index;
3843 unpack_tree_opts.dst_index = r->index;
3844 unpack_tree_opts.fn = oneway_merge;
3845 unpack_tree_opts.merge = 1;
3846 unpack_tree_opts.update = 1;
3847 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3848 unpack_tree_opts.skip_cache_tree_update = 1;
3849 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3851 if (repo_read_index_unmerged(r)) {
3852 ret = error_resolve_conflict(action_name(opts));
3853 goto cleanup;
3856 if (!fill_tree_descriptor(r, &desc, &oid)) {
3857 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3858 goto cleanup;
3861 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3862 ret = -1;
3863 goto cleanup;
3866 tree = parse_tree_indirect(&oid);
3867 prime_cache_tree(r, r->index, tree);
3869 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3870 ret = error(_("could not write index"));
3872 if (!ret)
3873 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3874 len, name), "HEAD", &oid,
3875 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3876 cleanup:
3877 free((void *)desc.buffer);
3878 if (ret < 0)
3879 rollback_lock_file(&lock);
3880 strbuf_release(&ref_name);
3881 clear_unpack_trees_porcelain(&unpack_tree_opts);
3882 return ret;
3885 static int do_merge(struct repository *r,
3886 struct commit *commit,
3887 const char *arg, int arg_len,
3888 int flags, int *check_todo, struct replay_opts *opts)
3890 int run_commit_flags = 0;
3891 struct strbuf ref_name = STRBUF_INIT;
3892 struct commit *head_commit, *merge_commit, *i;
3893 struct commit_list *bases, *j;
3894 struct commit_list *to_merge = NULL, **tail = &to_merge;
3895 const char *strategy = !opts->xopts.nr &&
3896 (!opts->strategy ||
3897 !strcmp(opts->strategy, "recursive") ||
3898 !strcmp(opts->strategy, "ort")) ?
3899 NULL : opts->strategy;
3900 struct merge_options o;
3901 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3902 static struct lock_file lock;
3903 const char *p;
3905 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3906 ret = -1;
3907 goto leave_merge;
3910 head_commit = lookup_commit_reference_by_name("HEAD");
3911 if (!head_commit) {
3912 ret = error(_("cannot merge without a current revision"));
3913 goto leave_merge;
3917 * For octopus merges, the arg starts with the list of revisions to be
3918 * merged. The list is optionally followed by '#' and the oneline.
3920 merge_arg_len = oneline_offset = arg_len;
3921 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3922 if (!*p)
3923 break;
3924 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3925 p += 1 + strspn(p + 1, " \t\n");
3926 oneline_offset = p - arg;
3927 break;
3929 k = strcspn(p, " \t\n");
3930 if (!k)
3931 continue;
3932 merge_commit = lookup_label(r, p, k, &ref_name);
3933 if (!merge_commit) {
3934 ret = error(_("unable to parse '%.*s'"), k, p);
3935 goto leave_merge;
3937 tail = &commit_list_insert(merge_commit, tail)->next;
3938 p += k;
3939 merge_arg_len = p - arg;
3942 if (!to_merge) {
3943 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3944 goto leave_merge;
3947 if (opts->have_squash_onto &&
3948 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3950 * When the user tells us to "merge" something into a
3951 * "[new root]", let's simply fast-forward to the merge head.
3953 rollback_lock_file(&lock);
3954 if (to_merge->next)
3955 ret = error(_("octopus merge cannot be executed on "
3956 "top of a [new root]"));
3957 else
3958 ret = fast_forward_to(r, &to_merge->item->object.oid,
3959 &head_commit->object.oid, 0,
3960 opts);
3961 goto leave_merge;
3965 * If HEAD is not identical to the first parent of the original merge
3966 * commit, we cannot fast-forward.
3968 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3969 oideq(&commit->parents->item->object.oid,
3970 &head_commit->object.oid);
3973 * If any merge head is different from the original one, we cannot
3974 * fast-forward.
3976 if (can_fast_forward) {
3977 struct commit_list *p = commit->parents->next;
3979 for (j = to_merge; j && p; j = j->next, p = p->next)
3980 if (!oideq(&j->item->object.oid,
3981 &p->item->object.oid)) {
3982 can_fast_forward = 0;
3983 break;
3986 * If the number of merge heads differs from the original merge
3987 * commit, we cannot fast-forward.
3989 if (j || p)
3990 can_fast_forward = 0;
3993 if (can_fast_forward) {
3994 rollback_lock_file(&lock);
3995 ret = fast_forward_to(r, &commit->object.oid,
3996 &head_commit->object.oid, 0, opts);
3997 if (flags & TODO_EDIT_MERGE_MSG)
3998 goto fast_forward_edit;
4000 goto leave_merge;
4003 if (commit) {
4004 const char *encoding = get_commit_output_encoding();
4005 const char *message = repo_logmsg_reencode(r, commit, NULL,
4006 encoding);
4007 const char *body;
4008 int len;
4010 if (!message) {
4011 ret = error(_("could not get commit message of '%s'"),
4012 oid_to_hex(&commit->object.oid));
4013 goto leave_merge;
4015 write_author_script(message);
4016 find_commit_subject(message, &body);
4017 len = strlen(body);
4018 ret = write_message(body, len, git_path_merge_msg(r), 0);
4019 repo_unuse_commit_buffer(r, commit, message);
4020 if (ret) {
4021 error_errno(_("could not write '%s'"),
4022 git_path_merge_msg(r));
4023 goto leave_merge;
4025 } else {
4026 struct strbuf buf = STRBUF_INIT;
4027 int len;
4029 strbuf_addf(&buf, "author %s", git_author_info(0));
4030 write_author_script(buf.buf);
4031 strbuf_reset(&buf);
4033 if (oneline_offset < arg_len) {
4034 p = arg + oneline_offset;
4035 len = arg_len - oneline_offset;
4036 } else {
4037 strbuf_addf(&buf, "Merge %s '%.*s'",
4038 to_merge->next ? "branches" : "branch",
4039 merge_arg_len, arg);
4040 p = buf.buf;
4041 len = buf.len;
4044 ret = write_message(p, len, git_path_merge_msg(r), 0);
4045 strbuf_release(&buf);
4046 if (ret) {
4047 error_errno(_("could not write '%s'"),
4048 git_path_merge_msg(r));
4049 goto leave_merge;
4053 if (strategy || to_merge->next) {
4054 /* Octopus merge */
4055 struct child_process cmd = CHILD_PROCESS_INIT;
4057 if (read_env_script(&cmd.env)) {
4058 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4060 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4061 goto leave_merge;
4064 if (opts->committer_date_is_author_date)
4065 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4066 opts->ignore_date ?
4067 "" :
4068 author_date_from_env(&cmd.env));
4069 if (opts->ignore_date)
4070 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4072 cmd.git_cmd = 1;
4073 strvec_push(&cmd.args, "merge");
4074 strvec_push(&cmd.args, "-s");
4075 if (!strategy)
4076 strvec_push(&cmd.args, "octopus");
4077 else {
4078 strvec_push(&cmd.args, strategy);
4079 for (k = 0; k < opts->xopts.nr; k++)
4080 strvec_pushf(&cmd.args,
4081 "-X%s", opts->xopts.v[k]);
4083 if (!(flags & TODO_EDIT_MERGE_MSG))
4084 strvec_push(&cmd.args, "--no-edit");
4085 else
4086 strvec_push(&cmd.args, "--edit");
4087 strvec_push(&cmd.args, "--no-ff");
4088 strvec_push(&cmd.args, "--no-log");
4089 strvec_push(&cmd.args, "--no-stat");
4090 strvec_push(&cmd.args, "-F");
4091 strvec_push(&cmd.args, git_path_merge_msg(r));
4092 if (opts->gpg_sign)
4093 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4094 else
4095 strvec_push(&cmd.args, "--no-gpg-sign");
4097 /* Add the tips to be merged */
4098 for (j = to_merge; j; j = j->next)
4099 strvec_push(&cmd.args,
4100 oid_to_hex(&j->item->object.oid));
4102 strbuf_release(&ref_name);
4103 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4104 NULL, 0);
4105 rollback_lock_file(&lock);
4107 ret = run_command(&cmd);
4109 /* force re-reading of the cache */
4110 if (!ret) {
4111 discard_index(r->index);
4112 if (repo_read_index(r) < 0)
4113 ret = error(_("could not read index"));
4115 goto leave_merge;
4118 merge_commit = to_merge->item;
4119 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4120 if (bases && oideq(&merge_commit->object.oid,
4121 &bases->item->object.oid)) {
4122 ret = 0;
4123 /* skip merging an ancestor of HEAD */
4124 goto leave_merge;
4127 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4128 git_path_merge_head(r), 0);
4129 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4131 bases = reverse_commit_list(bases);
4133 repo_read_index(r);
4134 init_merge_options(&o, r);
4135 o.branch1 = "HEAD";
4136 o.branch2 = ref_name.buf;
4137 o.buffer_output = 2;
4139 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4141 * TODO: Should use merge_incore_recursive() and
4142 * merge_switch_to_result(), skipping the call to
4143 * merge_switch_to_result() when we don't actually need to
4144 * update the index and working copy immediately.
4146 ret = merge_ort_recursive(&o,
4147 head_commit, merge_commit, bases,
4148 &i);
4149 } else {
4150 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4151 &i);
4153 if (ret <= 0)
4154 fputs(o.obuf.buf, stdout);
4155 strbuf_release(&o.obuf);
4156 if (ret < 0) {
4157 error(_("could not even attempt to merge '%.*s'"),
4158 merge_arg_len, arg);
4159 goto leave_merge;
4162 * The return value of merge_recursive() is 1 on clean, and 0 on
4163 * unclean merge.
4165 * Let's reverse that, so that do_merge() returns 0 upon success and
4166 * 1 upon failed merge (keeping the return value -1 for the cases where
4167 * we will want to reschedule the `merge` command).
4169 ret = !ret;
4171 if (r->index->cache_changed &&
4172 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4173 ret = error(_("merge: Unable to write new index file"));
4174 goto leave_merge;
4177 rollback_lock_file(&lock);
4178 if (ret)
4179 repo_rerere(r, opts->allow_rerere_auto);
4180 else
4182 * In case of problems, we now want to return a positive
4183 * value (a negative one would indicate that the `merge`
4184 * command needs to be rescheduled).
4186 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4187 run_commit_flags);
4189 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4190 fast_forward_edit:
4191 *check_todo = 1;
4192 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4193 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4197 leave_merge:
4198 strbuf_release(&ref_name);
4199 rollback_lock_file(&lock);
4200 free_commit_list(to_merge);
4201 return ret;
4204 static int write_update_refs_state(struct string_list *refs_to_oids)
4206 int result = 0;
4207 struct lock_file lock = LOCK_INIT;
4208 FILE *fp = NULL;
4209 struct string_list_item *item;
4210 char *path;
4212 path = rebase_path_update_refs(the_repository->gitdir);
4214 if (!refs_to_oids->nr) {
4215 if (unlink(path) && errno != ENOENT)
4216 result = error_errno(_("could not unlink: %s"), path);
4217 goto cleanup;
4220 if (safe_create_leading_directories(path)) {
4221 result = error(_("unable to create leading directories of %s"),
4222 path);
4223 goto cleanup;
4226 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4227 result = error(_("another 'rebase' process appears to be running; "
4228 "'%s.lock' already exists"),
4229 path);
4230 goto cleanup;
4233 fp = fdopen_lock_file(&lock, "w");
4234 if (!fp) {
4235 result = error_errno(_("could not open '%s' for writing"), path);
4236 rollback_lock_file(&lock);
4237 goto cleanup;
4240 for_each_string_list_item(item, refs_to_oids) {
4241 struct update_ref_record *rec = item->util;
4242 fprintf(fp, "%s\n%s\n%s\n", item->string,
4243 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4246 result = commit_lock_file(&lock);
4248 cleanup:
4249 free(path);
4250 return result;
4254 * Parse the update-refs file for the current rebase, then remove the
4255 * refs that do not appear in the todo_list (and have not had updated
4256 * values stored) and add refs that are in the todo_list but not
4257 * represented in the update-refs file.
4259 * If there are changes to the update-refs list, then write the new state
4260 * to disk.
4262 void todo_list_filter_update_refs(struct repository *r,
4263 struct todo_list *todo_list)
4265 int i;
4266 int updated = 0;
4267 struct string_list update_refs = STRING_LIST_INIT_DUP;
4269 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4272 * For each item in the update_refs list, if it has no updated
4273 * value and does not appear in the todo_list, then remove it
4274 * from the update_refs list.
4276 for (i = 0; i < update_refs.nr; i++) {
4277 int j;
4278 int found = 0;
4279 const char *ref = update_refs.items[i].string;
4280 size_t reflen = strlen(ref);
4281 struct update_ref_record *rec = update_refs.items[i].util;
4283 /* OID already stored as updated. */
4284 if (!is_null_oid(&rec->after))
4285 continue;
4287 for (j = 0; !found && j < todo_list->nr; j++) {
4288 struct todo_item *item = &todo_list->items[j];
4289 const char *arg = todo_list->buf.buf + item->arg_offset;
4291 if (item->command != TODO_UPDATE_REF)
4292 continue;
4294 if (item->arg_len != reflen ||
4295 strncmp(arg, ref, reflen))
4296 continue;
4298 found = 1;
4301 if (!found) {
4302 free(update_refs.items[i].string);
4303 free(update_refs.items[i].util);
4305 update_refs.nr--;
4306 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4308 updated = 1;
4309 i--;
4314 * For each todo_item, check if its ref is in the update_refs list.
4315 * If not, then add it as an un-updated ref.
4317 for (i = 0; i < todo_list->nr; i++) {
4318 struct todo_item *item = &todo_list->items[i];
4319 const char *arg = todo_list->buf.buf + item->arg_offset;
4320 int j, found = 0;
4322 if (item->command != TODO_UPDATE_REF)
4323 continue;
4325 for (j = 0; !found && j < update_refs.nr; j++) {
4326 const char *ref = update_refs.items[j].string;
4328 found = strlen(ref) == item->arg_len &&
4329 !strncmp(ref, arg, item->arg_len);
4332 if (!found) {
4333 struct string_list_item *inserted;
4334 struct strbuf argref = STRBUF_INIT;
4336 strbuf_add(&argref, arg, item->arg_len);
4337 inserted = string_list_insert(&update_refs, argref.buf);
4338 inserted->util = init_update_ref_record(argref.buf);
4339 strbuf_release(&argref);
4340 updated = 1;
4344 if (updated)
4345 write_update_refs_state(&update_refs);
4346 string_list_clear(&update_refs, 1);
4349 static int do_update_ref(struct repository *r, const char *refname)
4351 struct string_list_item *item;
4352 struct string_list list = STRING_LIST_INIT_DUP;
4354 if (sequencer_get_update_refs_state(r->gitdir, &list))
4355 return -1;
4357 for_each_string_list_item(item, &list) {
4358 if (!strcmp(item->string, refname)) {
4359 struct update_ref_record *rec = item->util;
4360 if (read_ref("HEAD", &rec->after))
4361 return -1;
4362 break;
4366 write_update_refs_state(&list);
4367 string_list_clear(&list, 1);
4368 return 0;
4371 static int do_update_refs(struct repository *r, int quiet)
4373 int res = 0;
4374 struct string_list_item *item;
4375 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4376 struct ref_store *refs = get_main_ref_store(r);
4377 struct strbuf update_msg = STRBUF_INIT;
4378 struct strbuf error_msg = STRBUF_INIT;
4380 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4381 return res;
4383 for_each_string_list_item(item, &refs_to_oids) {
4384 struct update_ref_record *rec = item->util;
4385 int loop_res;
4387 loop_res = refs_update_ref(refs, "rewritten during rebase",
4388 item->string,
4389 &rec->after, &rec->before,
4390 0, UPDATE_REFS_MSG_ON_ERR);
4391 res |= loop_res;
4393 if (quiet)
4394 continue;
4396 if (loop_res)
4397 strbuf_addf(&error_msg, "\t%s\n", item->string);
4398 else
4399 strbuf_addf(&update_msg, "\t%s\n", item->string);
4402 if (!quiet &&
4403 (update_msg.len || error_msg.len)) {
4404 fprintf(stderr,
4405 _("Updated the following refs with %s:\n%s"),
4406 "--update-refs",
4407 update_msg.buf);
4409 if (res)
4410 fprintf(stderr,
4411 _("Failed to update the following refs with %s:\n%s"),
4412 "--update-refs",
4413 error_msg.buf);
4416 string_list_clear(&refs_to_oids, 1);
4417 strbuf_release(&update_msg);
4418 strbuf_release(&error_msg);
4419 return res;
4422 static int is_final_fixup(struct todo_list *todo_list)
4424 int i = todo_list->current;
4426 if (!is_fixup(todo_list->items[i].command))
4427 return 0;
4429 while (++i < todo_list->nr)
4430 if (is_fixup(todo_list->items[i].command))
4431 return 0;
4432 else if (!is_noop(todo_list->items[i].command))
4433 break;
4434 return 1;
4437 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4439 int i;
4441 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4442 if (!is_noop(todo_list->items[i].command))
4443 return todo_list->items[i].command;
4445 return -1;
4448 void create_autostash(struct repository *r, const char *path)
4450 struct strbuf buf = STRBUF_INIT;
4451 struct lock_file lock_file = LOCK_INIT;
4452 int fd;
4454 fd = repo_hold_locked_index(r, &lock_file, 0);
4455 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4456 if (0 <= fd)
4457 repo_update_index_if_able(r, &lock_file);
4458 rollback_lock_file(&lock_file);
4460 if (has_unstaged_changes(r, 1) ||
4461 has_uncommitted_changes(r, 1)) {
4462 struct child_process stash = CHILD_PROCESS_INIT;
4463 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4464 struct object_id oid;
4466 strvec_pushl(&stash.args,
4467 "stash", "create", "autostash", NULL);
4468 stash.git_cmd = 1;
4469 stash.no_stdin = 1;
4470 strbuf_reset(&buf);
4471 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4472 die(_("Cannot autostash"));
4473 strbuf_trim_trailing_newline(&buf);
4474 if (repo_get_oid(r, buf.buf, &oid))
4475 die(_("Unexpected stash response: '%s'"),
4476 buf.buf);
4477 strbuf_reset(&buf);
4478 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4480 if (safe_create_leading_directories_const(path))
4481 die(_("Could not create directory for '%s'"),
4482 path);
4483 write_file(path, "%s", oid_to_hex(&oid));
4484 printf(_("Created autostash: %s\n"), buf.buf);
4485 if (reset_head(r, &ropts) < 0)
4486 die(_("could not reset --hard"));
4487 discard_index(r->index);
4488 if (repo_read_index(r) < 0)
4489 die(_("could not read index"));
4491 strbuf_release(&buf);
4494 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4496 struct child_process child = CHILD_PROCESS_INIT;
4497 int ret = 0;
4499 if (attempt_apply) {
4500 child.git_cmd = 1;
4501 child.no_stdout = 1;
4502 child.no_stderr = 1;
4503 strvec_push(&child.args, "stash");
4504 strvec_push(&child.args, "apply");
4505 strvec_push(&child.args, stash_oid);
4506 ret = run_command(&child);
4509 if (attempt_apply && !ret)
4510 fprintf(stderr, _("Applied autostash.\n"));
4511 else {
4512 struct child_process store = CHILD_PROCESS_INIT;
4514 store.git_cmd = 1;
4515 strvec_push(&store.args, "stash");
4516 strvec_push(&store.args, "store");
4517 strvec_push(&store.args, "-m");
4518 strvec_push(&store.args, "autostash");
4519 strvec_push(&store.args, "-q");
4520 strvec_push(&store.args, stash_oid);
4521 if (run_command(&store))
4522 ret = error(_("cannot store %s"), stash_oid);
4523 else
4524 fprintf(stderr,
4525 _("%s\n"
4526 "Your changes are safe in the stash.\n"
4527 "You can run \"git stash pop\" or"
4528 " \"git stash drop\" at any time.\n"),
4529 attempt_apply ?
4530 _("Applying autostash resulted in conflicts.") :
4531 _("Autostash exists; creating a new stash entry."));
4534 return ret;
4537 static int apply_save_autostash(const char *path, int attempt_apply)
4539 struct strbuf stash_oid = STRBUF_INIT;
4540 int ret = 0;
4542 if (!read_oneliner(&stash_oid, path,
4543 READ_ONELINER_SKIP_IF_EMPTY)) {
4544 strbuf_release(&stash_oid);
4545 return 0;
4547 strbuf_trim(&stash_oid);
4549 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4551 unlink(path);
4552 strbuf_release(&stash_oid);
4553 return ret;
4556 int save_autostash(const char *path)
4558 return apply_save_autostash(path, 0);
4561 int apply_autostash(const char *path)
4563 return apply_save_autostash(path, 1);
4566 int apply_autostash_oid(const char *stash_oid)
4568 return apply_save_autostash_oid(stash_oid, 1);
4571 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4572 const char *onto_name, const struct object_id *onto,
4573 const struct object_id *orig_head)
4575 struct reset_head_opts ropts = {
4576 .oid = onto,
4577 .orig_head = orig_head,
4578 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4579 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4580 .head_msg = reflog_message(opts, "start", "checkout %s",
4581 onto_name),
4582 .default_reflog_action = sequencer_reflog_action(opts)
4584 if (reset_head(r, &ropts)) {
4585 apply_autostash(rebase_path_autostash());
4586 sequencer_remove_state(opts);
4587 return error(_("could not detach HEAD"));
4590 return 0;
4593 static int stopped_at_head(struct repository *r)
4595 struct object_id head;
4596 struct commit *commit;
4597 struct commit_message message;
4599 if (repo_get_oid(r, "HEAD", &head) ||
4600 !(commit = lookup_commit(r, &head)) ||
4601 repo_parse_commit(r, commit) || get_message(commit, &message))
4602 fprintf(stderr, _("Stopped at HEAD\n"));
4603 else {
4604 fprintf(stderr, _("Stopped at %s\n"), message.label);
4605 free_message(commit, &message);
4607 return 0;
4611 static int reread_todo_if_changed(struct repository *r,
4612 struct todo_list *todo_list,
4613 struct replay_opts *opts)
4615 int offset;
4616 struct strbuf buf = STRBUF_INIT;
4618 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4619 return -1;
4620 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4621 if (buf.len != todo_list->buf.len - offset ||
4622 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4623 /* Reread the todo file if it has changed. */
4624 todo_list_release(todo_list);
4625 if (read_populate_todo(r, todo_list, opts))
4626 return -1; /* message was printed */
4627 /* `current` will be incremented on return */
4628 todo_list->current = -1;
4630 strbuf_release(&buf);
4632 return 0;
4635 static const char rescheduled_advice[] =
4636 N_("Could not execute the todo command\n"
4637 "\n"
4638 " %.*s"
4639 "\n"
4640 "It has been rescheduled; To edit the command before continuing, please\n"
4641 "edit the todo list first:\n"
4642 "\n"
4643 " git rebase --edit-todo\n"
4644 " git rebase --continue\n");
4646 static int pick_commits(struct repository *r,
4647 struct todo_list *todo_list,
4648 struct replay_opts *opts)
4650 int res = 0, reschedule = 0;
4652 opts->reflog_message = sequencer_reflog_action(opts);
4653 if (opts->allow_ff)
4654 assert(!(opts->signoff || opts->no_commit ||
4655 opts->record_origin || should_edit(opts) ||
4656 opts->committer_date_is_author_date ||
4657 opts->ignore_date));
4658 if (read_and_refresh_cache(r, opts))
4659 return -1;
4661 while (todo_list->current < todo_list->nr) {
4662 struct todo_item *item = todo_list->items + todo_list->current;
4663 const char *arg = todo_item_get_arg(todo_list, item);
4664 int check_todo = 0;
4666 if (save_todo(todo_list, opts))
4667 return -1;
4668 if (is_rebase_i(opts)) {
4669 if (item->command != TODO_COMMENT) {
4670 FILE *f = fopen(rebase_path_msgnum(), "w");
4672 todo_list->done_nr++;
4674 if (f) {
4675 fprintf(f, "%d\n", todo_list->done_nr);
4676 fclose(f);
4678 if (!opts->quiet)
4679 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4680 todo_list->done_nr,
4681 todo_list->total_nr,
4682 opts->verbose ? "\n" : "\r");
4684 unlink(rebase_path_message());
4685 unlink(rebase_path_author_script());
4686 unlink(rebase_path_stopped_sha());
4687 unlink(rebase_path_amend());
4688 unlink(git_path_merge_head(r));
4689 unlink(git_path_auto_merge(r));
4690 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4692 if (item->command == TODO_BREAK) {
4693 if (!opts->verbose)
4694 term_clear_line();
4695 return stopped_at_head(r);
4698 if (item->command <= TODO_SQUASH) {
4699 if (is_rebase_i(opts))
4700 opts->reflog_message = reflog_message(opts,
4701 command_to_string(item->command), NULL);
4703 res = do_pick_commit(r, item, opts,
4704 is_final_fixup(todo_list),
4705 &check_todo);
4706 if (is_rebase_i(opts) && res < 0) {
4707 /* Reschedule */
4708 advise(_(rescheduled_advice),
4709 get_item_line_length(todo_list,
4710 todo_list->current),
4711 get_item_line(todo_list,
4712 todo_list->current));
4713 todo_list->current--;
4714 if (save_todo(todo_list, opts))
4715 return -1;
4717 if (item->command == TODO_EDIT) {
4718 struct commit *commit = item->commit;
4719 if (!res) {
4720 if (!opts->verbose)
4721 term_clear_line();
4722 fprintf(stderr,
4723 _("Stopped at %s... %.*s\n"),
4724 short_commit_name(commit),
4725 item->arg_len, arg);
4727 return error_with_patch(r, commit,
4728 arg, item->arg_len, opts, res, !res);
4730 if (is_rebase_i(opts) && !res)
4731 record_in_rewritten(&item->commit->object.oid,
4732 peek_command(todo_list, 1));
4733 if (res && is_fixup(item->command)) {
4734 if (res == 1)
4735 intend_to_amend();
4736 return error_failed_squash(r, item->commit, opts,
4737 item->arg_len, arg);
4738 } else if (res && is_rebase_i(opts) && item->commit) {
4739 int to_amend = 0;
4740 struct object_id oid;
4743 * If we are rewording and have either
4744 * fast-forwarded already, or are about to
4745 * create a new root commit, we want to amend,
4746 * otherwise we do not.
4748 if (item->command == TODO_REWORD &&
4749 !repo_get_oid(r, "HEAD", &oid) &&
4750 (oideq(&item->commit->object.oid, &oid) ||
4751 (opts->have_squash_onto &&
4752 oideq(&opts->squash_onto, &oid))))
4753 to_amend = 1;
4755 return res | error_with_patch(r, item->commit,
4756 arg, item->arg_len, opts,
4757 res, to_amend);
4759 } else if (item->command == TODO_EXEC) {
4760 char *end_of_arg = (char *)(arg + item->arg_len);
4761 int saved = *end_of_arg;
4763 if (!opts->verbose)
4764 term_clear_line();
4765 *end_of_arg = '\0';
4766 res = do_exec(r, arg);
4767 *end_of_arg = saved;
4769 if (res) {
4770 if (opts->reschedule_failed_exec)
4771 reschedule = 1;
4773 check_todo = 1;
4774 } else if (item->command == TODO_LABEL) {
4775 if ((res = do_label(r, arg, item->arg_len)))
4776 reschedule = 1;
4777 } else if (item->command == TODO_RESET) {
4778 if ((res = do_reset(r, arg, item->arg_len, opts)))
4779 reschedule = 1;
4780 } else if (item->command == TODO_MERGE) {
4781 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4782 item->flags, &check_todo, opts)) < 0)
4783 reschedule = 1;
4784 else if (item->commit)
4785 record_in_rewritten(&item->commit->object.oid,
4786 peek_command(todo_list, 1));
4787 if (res > 0)
4788 /* failed with merge conflicts */
4789 return error_with_patch(r, item->commit,
4790 arg, item->arg_len,
4791 opts, res, 0);
4792 } else if (item->command == TODO_UPDATE_REF) {
4793 struct strbuf ref = STRBUF_INIT;
4794 strbuf_add(&ref, arg, item->arg_len);
4795 if ((res = do_update_ref(r, ref.buf)))
4796 reschedule = 1;
4797 strbuf_release(&ref);
4798 } else if (!is_noop(item->command))
4799 return error(_("unknown command %d"), item->command);
4801 if (reschedule) {
4802 advise(_(rescheduled_advice),
4803 get_item_line_length(todo_list,
4804 todo_list->current),
4805 get_item_line(todo_list, todo_list->current));
4806 todo_list->current--;
4807 if (save_todo(todo_list, opts))
4808 return -1;
4809 if (item->commit)
4810 return error_with_patch(r,
4811 item->commit,
4812 arg, item->arg_len,
4813 opts, res, 0);
4814 } else if (is_rebase_i(opts) && check_todo && !res &&
4815 reread_todo_if_changed(r, todo_list, opts)) {
4816 return -1;
4819 todo_list->current++;
4820 if (res)
4821 return res;
4824 if (is_rebase_i(opts)) {
4825 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4826 struct stat st;
4828 /* Stopped in the middle, as planned? */
4829 if (todo_list->current < todo_list->nr)
4830 return 0;
4832 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4833 starts_with(head_ref.buf, "refs/")) {
4834 const char *msg;
4835 struct object_id head, orig;
4836 int res;
4838 if (repo_get_oid(r, "HEAD", &head)) {
4839 res = error(_("cannot read HEAD"));
4840 cleanup_head_ref:
4841 strbuf_release(&head_ref);
4842 strbuf_release(&buf);
4843 return res;
4845 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4846 get_oid_hex(buf.buf, &orig)) {
4847 res = error(_("could not read orig-head"));
4848 goto cleanup_head_ref;
4850 strbuf_reset(&buf);
4851 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4852 res = error(_("could not read 'onto'"));
4853 goto cleanup_head_ref;
4855 msg = reflog_message(opts, "finish", "%s onto %s",
4856 head_ref.buf, buf.buf);
4857 if (update_ref(msg, head_ref.buf, &head, &orig,
4858 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4859 res = error(_("could not update %s"),
4860 head_ref.buf);
4861 goto cleanup_head_ref;
4863 msg = reflog_message(opts, "finish", "returning to %s",
4864 head_ref.buf);
4865 if (create_symref("HEAD", head_ref.buf, msg)) {
4866 res = error(_("could not update HEAD to %s"),
4867 head_ref.buf);
4868 goto cleanup_head_ref;
4870 strbuf_reset(&buf);
4873 if (opts->verbose) {
4874 struct rev_info log_tree_opt;
4875 struct object_id orig, head;
4877 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4878 repo_init_revisions(r, &log_tree_opt, NULL);
4879 log_tree_opt.diff = 1;
4880 log_tree_opt.diffopt.output_format =
4881 DIFF_FORMAT_DIFFSTAT;
4882 log_tree_opt.disable_stdin = 1;
4884 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4885 !repo_get_oid(r, buf.buf, &orig) &&
4886 !repo_get_oid(r, "HEAD", &head)) {
4887 diff_tree_oid(&orig, &head, "",
4888 &log_tree_opt.diffopt);
4889 log_tree_diff_flush(&log_tree_opt);
4891 release_revisions(&log_tree_opt);
4893 flush_rewritten_pending();
4894 if (!stat(rebase_path_rewritten_list(), &st) &&
4895 st.st_size > 0) {
4896 struct child_process child = CHILD_PROCESS_INIT;
4897 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4899 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4900 child.git_cmd = 1;
4901 strvec_push(&child.args, "notes");
4902 strvec_push(&child.args, "copy");
4903 strvec_push(&child.args, "--for-rewrite=rebase");
4904 /* we don't care if this copying failed */
4905 run_command(&child);
4907 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4908 strvec_push(&hook_opt.args, "rebase");
4909 run_hooks_opt("post-rewrite", &hook_opt);
4911 apply_autostash(rebase_path_autostash());
4913 if (!opts->quiet) {
4914 if (!opts->verbose)
4915 term_clear_line();
4916 fprintf(stderr,
4917 _("Successfully rebased and updated %s.\n"),
4918 head_ref.buf);
4921 strbuf_release(&buf);
4922 strbuf_release(&head_ref);
4924 if (do_update_refs(r, opts->quiet))
4925 return -1;
4929 * Sequence of picks finished successfully; cleanup by
4930 * removing the .git/sequencer directory
4932 return sequencer_remove_state(opts);
4935 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4937 struct child_process cmd = CHILD_PROCESS_INIT;
4939 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4940 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4941 return error(_("no cherry-pick or revert in progress"));
4943 cmd.git_cmd = 1;
4944 strvec_push(&cmd.args, "commit");
4947 * continue_single_pick() handles the case of recovering from a
4948 * conflict. should_edit() doesn't handle that case; for a conflict,
4949 * we want to edit if the user asked for it, or if they didn't specify
4950 * and stdin is a tty.
4952 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4954 * Include --cleanup=strip as well because we don't want the
4955 * "# Conflicts:" messages.
4957 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4959 return run_command(&cmd);
4962 static int commit_staged_changes(struct repository *r,
4963 struct replay_opts *opts,
4964 struct todo_list *todo_list)
4966 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4967 unsigned int final_fixup = 0, is_clean;
4969 if (has_unstaged_changes(r, 1))
4970 return error(_("cannot rebase: You have unstaged changes."));
4972 is_clean = !has_uncommitted_changes(r, 0);
4974 if (file_exists(rebase_path_amend())) {
4975 struct strbuf rev = STRBUF_INIT;
4976 struct object_id head, to_amend;
4978 if (repo_get_oid(r, "HEAD", &head))
4979 return error(_("cannot amend non-existing commit"));
4980 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4981 return error(_("invalid file: '%s'"), rebase_path_amend());
4982 if (get_oid_hex(rev.buf, &to_amend))
4983 return error(_("invalid contents: '%s'"),
4984 rebase_path_amend());
4985 if (!is_clean && !oideq(&head, &to_amend))
4986 return error(_("\nYou have uncommitted changes in your "
4987 "working tree. Please, commit them\n"
4988 "first and then run 'git rebase "
4989 "--continue' again."));
4991 * When skipping a failed fixup/squash, we need to edit the
4992 * commit message, the current fixup list and count, and if it
4993 * was the last fixup/squash in the chain, we need to clean up
4994 * the commit message and if there was a squash, let the user
4995 * edit it.
4997 if (!is_clean || !opts->current_fixup_count)
4998 ; /* this is not the final fixup */
4999 else if (!oideq(&head, &to_amend) ||
5000 !file_exists(rebase_path_stopped_sha())) {
5001 /* was a final fixup or squash done manually? */
5002 if (!is_fixup(peek_command(todo_list, 0))) {
5003 unlink(rebase_path_fixup_msg());
5004 unlink(rebase_path_squash_msg());
5005 unlink(rebase_path_current_fixups());
5006 strbuf_reset(&opts->current_fixups);
5007 opts->current_fixup_count = 0;
5009 } else {
5010 /* we are in a fixup/squash chain */
5011 const char *p = opts->current_fixups.buf;
5012 int len = opts->current_fixups.len;
5014 opts->current_fixup_count--;
5015 if (!len)
5016 BUG("Incorrect current_fixups:\n%s", p);
5017 while (len && p[len - 1] != '\n')
5018 len--;
5019 strbuf_setlen(&opts->current_fixups, len);
5020 if (write_message(p, len, rebase_path_current_fixups(),
5021 0) < 0)
5022 return error(_("could not write file: '%s'"),
5023 rebase_path_current_fixups());
5026 * If a fixup/squash in a fixup/squash chain failed, the
5027 * commit message is already correct, no need to commit
5028 * it again.
5030 * Only if it is the final command in the fixup/squash
5031 * chain, and only if the chain is longer than a single
5032 * fixup/squash command (which was just skipped), do we
5033 * actually need to re-commit with a cleaned up commit
5034 * message.
5036 if (opts->current_fixup_count > 0 &&
5037 !is_fixup(peek_command(todo_list, 0))) {
5038 final_fixup = 1;
5040 * If there was not a single "squash" in the
5041 * chain, we only need to clean up the commit
5042 * message, no need to bother the user with
5043 * opening the commit message in the editor.
5045 if (!starts_with(p, "squash ") &&
5046 !strstr(p, "\nsquash "))
5047 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5048 } else if (is_fixup(peek_command(todo_list, 0))) {
5050 * We need to update the squash message to skip
5051 * the latest commit message.
5053 struct commit *commit;
5054 const char *path = rebase_path_squash_msg();
5055 const char *encoding = get_commit_output_encoding();
5057 if (parse_head(r, &commit) ||
5058 !(p = repo_logmsg_reencode(r, commit, NULL, encoding)) ||
5059 write_message(p, strlen(p), path, 0)) {
5060 repo_unuse_commit_buffer(r, commit, p);
5061 return error(_("could not write file: "
5062 "'%s'"), path);
5064 repo_unuse_commit_buffer(r,
5065 commit, p);
5069 strbuf_release(&rev);
5070 flags |= AMEND_MSG;
5073 if (is_clean) {
5074 if (refs_ref_exists(get_main_ref_store(r),
5075 "CHERRY_PICK_HEAD") &&
5076 refs_delete_ref(get_main_ref_store(r), "",
5077 "CHERRY_PICK_HEAD", NULL, 0))
5078 return error(_("could not remove CHERRY_PICK_HEAD"));
5079 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5080 return error_errno(_("could not remove '%s'"),
5081 git_path_merge_msg(r));
5082 if (!final_fixup)
5083 return 0;
5086 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5087 opts, flags))
5088 return error(_("could not commit staged changes."));
5089 unlink(rebase_path_amend());
5090 unlink(git_path_merge_head(r));
5091 unlink(git_path_auto_merge(r));
5092 if (final_fixup) {
5093 unlink(rebase_path_fixup_msg());
5094 unlink(rebase_path_squash_msg());
5096 if (opts->current_fixup_count > 0) {
5098 * Whether final fixup or not, we just cleaned up the commit
5099 * message...
5101 unlink(rebase_path_current_fixups());
5102 strbuf_reset(&opts->current_fixups);
5103 opts->current_fixup_count = 0;
5105 return 0;
5108 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5110 struct todo_list todo_list = TODO_LIST_INIT;
5111 int res;
5113 if (read_and_refresh_cache(r, opts))
5114 return -1;
5116 if (read_populate_opts(opts))
5117 return -1;
5118 if (is_rebase_i(opts)) {
5119 if ((res = read_populate_todo(r, &todo_list, opts)))
5120 goto release_todo_list;
5122 if (file_exists(rebase_path_dropped())) {
5123 if ((res = todo_list_check_against_backup(r, &todo_list)))
5124 goto release_todo_list;
5126 unlink(rebase_path_dropped());
5129 opts->reflog_message = reflog_message(opts, "continue", NULL);
5130 if (commit_staged_changes(r, opts, &todo_list)) {
5131 res = -1;
5132 goto release_todo_list;
5134 } else if (!file_exists(get_todo_path(opts)))
5135 return continue_single_pick(r, opts);
5136 else if ((res = read_populate_todo(r, &todo_list, opts)))
5137 goto release_todo_list;
5139 if (!is_rebase_i(opts)) {
5140 /* Verify that the conflict has been resolved */
5141 if (refs_ref_exists(get_main_ref_store(r),
5142 "CHERRY_PICK_HEAD") ||
5143 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5144 res = continue_single_pick(r, opts);
5145 if (res)
5146 goto release_todo_list;
5148 if (index_differs_from(r, "HEAD", NULL, 0)) {
5149 res = error_dirty_index(r, opts);
5150 goto release_todo_list;
5152 todo_list.current++;
5153 } else if (file_exists(rebase_path_stopped_sha())) {
5154 struct strbuf buf = STRBUF_INIT;
5155 struct object_id oid;
5157 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5158 READ_ONELINER_SKIP_IF_EMPTY) &&
5159 !get_oid_hex(buf.buf, &oid))
5160 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5161 strbuf_release(&buf);
5164 res = pick_commits(r, &todo_list, opts);
5165 release_todo_list:
5166 todo_list_release(&todo_list);
5167 return res;
5170 static int single_pick(struct repository *r,
5171 struct commit *cmit,
5172 struct replay_opts *opts)
5174 int check_todo;
5175 struct todo_item item;
5177 item.command = opts->action == REPLAY_PICK ?
5178 TODO_PICK : TODO_REVERT;
5179 item.commit = cmit;
5181 opts->reflog_message = sequencer_reflog_action(opts);
5182 return do_pick_commit(r, &item, opts, 0, &check_todo);
5185 int sequencer_pick_revisions(struct repository *r,
5186 struct replay_opts *opts)
5188 struct todo_list todo_list = TODO_LIST_INIT;
5189 struct object_id oid;
5190 int i, res;
5192 assert(opts->revs);
5193 if (read_and_refresh_cache(r, opts))
5194 return -1;
5196 for (i = 0; i < opts->revs->pending.nr; i++) {
5197 struct object_id oid;
5198 const char *name = opts->revs->pending.objects[i].name;
5200 /* This happens when using --stdin. */
5201 if (!strlen(name))
5202 continue;
5204 if (!repo_get_oid(r, name, &oid)) {
5205 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5206 enum object_type type = oid_object_info(r,
5207 &oid,
5208 NULL);
5209 return error(_("%s: can't cherry-pick a %s"),
5210 name, type_name(type));
5212 } else
5213 return error(_("%s: bad revision"), name);
5217 * If we were called as "git cherry-pick <commit>", just
5218 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5219 * REVERT_HEAD, and don't touch the sequencer state.
5220 * This means it is possible to cherry-pick in the middle
5221 * of a cherry-pick sequence.
5223 if (opts->revs->cmdline.nr == 1 &&
5224 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5225 opts->revs->no_walk &&
5226 !opts->revs->cmdline.rev->flags) {
5227 struct commit *cmit;
5228 if (prepare_revision_walk(opts->revs))
5229 return error(_("revision walk setup failed"));
5230 cmit = get_revision(opts->revs);
5231 if (!cmit)
5232 return error(_("empty commit set passed"));
5233 if (get_revision(opts->revs))
5234 BUG("unexpected extra commit from walk");
5235 return single_pick(r, cmit, opts);
5239 * Start a new cherry-pick/ revert sequence; but
5240 * first, make sure that an existing one isn't in
5241 * progress
5244 if (walk_revs_populate_todo(&todo_list, opts) ||
5245 create_seq_dir(r) < 0)
5246 return -1;
5247 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5248 return error(_("can't revert as initial commit"));
5249 if (save_head(oid_to_hex(&oid)))
5250 return -1;
5251 if (save_opts(opts))
5252 return -1;
5253 update_abort_safety_file();
5254 res = pick_commits(r, &todo_list, opts);
5255 todo_list_release(&todo_list);
5256 return res;
5259 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5261 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5262 struct strbuf sob = STRBUF_INIT;
5263 int has_footer;
5265 strbuf_addstr(&sob, sign_off_header);
5266 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5267 strbuf_addch(&sob, '\n');
5269 if (!ignore_footer)
5270 strbuf_complete_line(msgbuf);
5273 * If the whole message buffer is equal to the sob, pretend that we
5274 * found a conforming footer with a matching sob
5276 if (msgbuf->len - ignore_footer == sob.len &&
5277 !strncmp(msgbuf->buf, sob.buf, sob.len))
5278 has_footer = 3;
5279 else
5280 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5282 if (!has_footer) {
5283 const char *append_newlines = NULL;
5284 size_t len = msgbuf->len - ignore_footer;
5286 if (!len) {
5288 * The buffer is completely empty. Leave foom for
5289 * the title and body to be filled in by the user.
5291 append_newlines = "\n\n";
5292 } else if (len == 1) {
5294 * Buffer contains a single newline. Add another
5295 * so that we leave room for the title and body.
5297 append_newlines = "\n";
5298 } else if (msgbuf->buf[len - 2] != '\n') {
5300 * Buffer ends with a single newline. Add another
5301 * so that there is an empty line between the message
5302 * body and the sob.
5304 append_newlines = "\n";
5305 } /* else, the buffer already ends with two newlines. */
5307 if (append_newlines)
5308 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5309 append_newlines, strlen(append_newlines));
5312 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5313 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5314 sob.buf, sob.len);
5316 strbuf_release(&sob);
5319 struct labels_entry {
5320 struct hashmap_entry entry;
5321 char label[FLEX_ARRAY];
5324 static int labels_cmp(const void *fndata UNUSED,
5325 const struct hashmap_entry *eptr,
5326 const struct hashmap_entry *entry_or_key, const void *key)
5328 const struct labels_entry *a, *b;
5330 a = container_of(eptr, const struct labels_entry, entry);
5331 b = container_of(entry_or_key, const struct labels_entry, entry);
5333 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5336 struct string_entry {
5337 struct oidmap_entry entry;
5338 char string[FLEX_ARRAY];
5341 struct label_state {
5342 struct oidmap commit2label;
5343 struct hashmap labels;
5344 struct strbuf buf;
5347 static const char *label_oid(struct object_id *oid, const char *label,
5348 struct label_state *state)
5350 struct labels_entry *labels_entry;
5351 struct string_entry *string_entry;
5352 struct object_id dummy;
5353 int i;
5355 string_entry = oidmap_get(&state->commit2label, oid);
5356 if (string_entry)
5357 return string_entry->string;
5360 * For "uninteresting" commits, i.e. commits that are not to be
5361 * rebased, and which can therefore not be labeled, we use a unique
5362 * abbreviation of the commit name. This is slightly more complicated
5363 * than calling repo_find_unique_abbrev() because we also need to make
5364 * sure that the abbreviation does not conflict with any other
5365 * label.
5367 * We disallow "interesting" commits to be labeled by a string that
5368 * is a valid full-length hash, to ensure that we always can find an
5369 * abbreviation for any uninteresting commit's names that does not
5370 * clash with any other label.
5372 strbuf_reset(&state->buf);
5373 if (!label) {
5374 char *p;
5376 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5377 label = p = state->buf.buf;
5379 repo_find_unique_abbrev_r(the_repository, p, oid,
5380 default_abbrev);
5383 * We may need to extend the abbreviated hash so that there is
5384 * no conflicting label.
5386 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5387 size_t i = strlen(p) + 1;
5389 oid_to_hex_r(p, oid);
5390 for (; i < the_hash_algo->hexsz; i++) {
5391 char save = p[i];
5392 p[i] = '\0';
5393 if (!hashmap_get_from_hash(&state->labels,
5394 strihash(p), p))
5395 break;
5396 p[i] = save;
5399 } else {
5400 struct strbuf *buf = &state->buf;
5403 * Sanitize labels by replacing non-alpha-numeric characters
5404 * (including white-space ones) by dashes, as they might be
5405 * illegal in file names (and hence in ref names).
5407 * Note that we retain non-ASCII UTF-8 characters (identified
5408 * via the most significant bit). They should be all acceptable
5409 * in file names. We do not validate the UTF-8 here, that's not
5410 * the job of this function.
5412 for (; *label; label++)
5413 if ((*label & 0x80) || isalnum(*label))
5414 strbuf_addch(buf, *label);
5415 /* avoid leading dash and double-dashes */
5416 else if (buf->len && buf->buf[buf->len - 1] != '-')
5417 strbuf_addch(buf, '-');
5418 if (!buf->len) {
5419 strbuf_addstr(buf, "rev-");
5420 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5422 label = buf->buf;
5424 if ((buf->len == the_hash_algo->hexsz &&
5425 !get_oid_hex(label, &dummy)) ||
5426 (buf->len == 1 && *label == '#') ||
5427 hashmap_get_from_hash(&state->labels,
5428 strihash(label), label)) {
5430 * If the label already exists, or if the label is a
5431 * valid full OID, or the label is a '#' (which we use
5432 * as a separator between merge heads and oneline), we
5433 * append a dash and a number to make it unique.
5435 size_t len = buf->len;
5437 for (i = 2; ; i++) {
5438 strbuf_setlen(buf, len);
5439 strbuf_addf(buf, "-%d", i);
5440 if (!hashmap_get_from_hash(&state->labels,
5441 strihash(buf->buf),
5442 buf->buf))
5443 break;
5446 label = buf->buf;
5450 FLEX_ALLOC_STR(labels_entry, label, label);
5451 hashmap_entry_init(&labels_entry->entry, strihash(label));
5452 hashmap_add(&state->labels, &labels_entry->entry);
5454 FLEX_ALLOC_STR(string_entry, string, label);
5455 oidcpy(&string_entry->entry.oid, oid);
5456 oidmap_put(&state->commit2label, string_entry);
5458 return string_entry->string;
5461 static int make_script_with_merges(struct pretty_print_context *pp,
5462 struct rev_info *revs, struct strbuf *out,
5463 unsigned flags)
5465 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5466 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5467 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5468 int skipped_commit = 0;
5469 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5470 struct strbuf label = STRBUF_INIT;
5471 struct commit_list *commits = NULL, **tail = &commits, *iter;
5472 struct commit_list *tips = NULL, **tips_tail = &tips;
5473 struct commit *commit;
5474 struct oidmap commit2todo = OIDMAP_INIT;
5475 struct string_entry *entry;
5476 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5477 shown = OIDSET_INIT;
5478 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5480 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5481 const char *cmd_pick = abbr ? "p" : "pick",
5482 *cmd_label = abbr ? "l" : "label",
5483 *cmd_reset = abbr ? "t" : "reset",
5484 *cmd_merge = abbr ? "m" : "merge";
5486 oidmap_init(&commit2todo, 0);
5487 oidmap_init(&state.commit2label, 0);
5488 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5489 strbuf_init(&state.buf, 32);
5491 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5492 struct labels_entry *onto_label_entry;
5493 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5494 FLEX_ALLOC_STR(entry, string, "onto");
5495 oidcpy(&entry->entry.oid, oid);
5496 oidmap_put(&state.commit2label, entry);
5498 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5499 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5500 hashmap_add(&state.labels, &onto_label_entry->entry);
5504 * First phase:
5505 * - get onelines for all commits
5506 * - gather all branch tips (i.e. 2nd or later parents of merges)
5507 * - label all branch tips
5509 while ((commit = get_revision(revs))) {
5510 struct commit_list *to_merge;
5511 const char *p1, *p2;
5512 struct object_id *oid;
5513 int is_empty;
5515 tail = &commit_list_insert(commit, tail)->next;
5516 oidset_insert(&interesting, &commit->object.oid);
5518 is_empty = is_original_commit_empty(commit);
5519 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5520 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5521 warning(_("skipped previously applied commit %s"),
5522 short_commit_name(commit));
5523 skipped_commit = 1;
5524 continue;
5526 if (is_empty && !keep_empty)
5527 continue;
5529 strbuf_reset(&oneline);
5530 pretty_print_commit(pp, commit, &oneline);
5532 to_merge = commit->parents ? commit->parents->next : NULL;
5533 if (!to_merge) {
5534 /* non-merge commit: easy case */
5535 strbuf_reset(&buf);
5536 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5537 oid_to_hex(&commit->object.oid),
5538 oneline.buf);
5539 if (is_empty)
5540 strbuf_addf(&buf, " %c empty",
5541 comment_line_char);
5543 FLEX_ALLOC_STR(entry, string, buf.buf);
5544 oidcpy(&entry->entry.oid, &commit->object.oid);
5545 oidmap_put(&commit2todo, entry);
5547 continue;
5550 /* Create a label */
5551 strbuf_reset(&label);
5552 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5553 (p1 = strchr(p1, '\'')) &&
5554 (p2 = strchr(++p1, '\'')))
5555 strbuf_add(&label, p1, p2 - p1);
5556 else if (skip_prefix(oneline.buf, "Merge pull request ",
5557 &p1) &&
5558 (p1 = strstr(p1, " from ")))
5559 strbuf_addstr(&label, p1 + strlen(" from "));
5560 else
5561 strbuf_addbuf(&label, &oneline);
5563 strbuf_reset(&buf);
5564 strbuf_addf(&buf, "%s -C %s",
5565 cmd_merge, oid_to_hex(&commit->object.oid));
5567 /* label the tips of merged branches */
5568 for (; to_merge; to_merge = to_merge->next) {
5569 oid = &to_merge->item->object.oid;
5570 strbuf_addch(&buf, ' ');
5572 if (!oidset_contains(&interesting, oid)) {
5573 strbuf_addstr(&buf, label_oid(oid, NULL,
5574 &state));
5575 continue;
5578 tips_tail = &commit_list_insert(to_merge->item,
5579 tips_tail)->next;
5581 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5583 strbuf_addf(&buf, " # %s", oneline.buf);
5585 FLEX_ALLOC_STR(entry, string, buf.buf);
5586 oidcpy(&entry->entry.oid, &commit->object.oid);
5587 oidmap_put(&commit2todo, entry);
5589 if (skipped_commit)
5590 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5591 _("use --reapply-cherry-picks to include skipped commits"));
5594 * Second phase:
5595 * - label branch points
5596 * - add HEAD to the branch tips
5598 for (iter = commits; iter; iter = iter->next) {
5599 struct commit_list *parent = iter->item->parents;
5600 for (; parent; parent = parent->next) {
5601 struct object_id *oid = &parent->item->object.oid;
5602 if (!oidset_contains(&interesting, oid))
5603 continue;
5604 if (oidset_insert(&child_seen, oid))
5605 label_oid(oid, "branch-point", &state);
5608 /* Add HEAD as implicit "tip of branch" */
5609 if (!iter->next)
5610 tips_tail = &commit_list_insert(iter->item,
5611 tips_tail)->next;
5615 * Third phase: output the todo list. This is a bit tricky, as we
5616 * want to avoid jumping back and forth between revisions. To
5617 * accomplish that goal, we walk backwards from the branch tips,
5618 * gathering commits not yet shown, reversing the list on the fly,
5619 * then outputting that list (labeling revisions as needed).
5621 strbuf_addf(out, "%s onto\n", cmd_label);
5622 for (iter = tips; iter; iter = iter->next) {
5623 struct commit_list *list = NULL, *iter2;
5625 commit = iter->item;
5626 if (oidset_contains(&shown, &commit->object.oid))
5627 continue;
5628 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5630 if (entry)
5631 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5632 else
5633 strbuf_addch(out, '\n');
5635 while (oidset_contains(&interesting, &commit->object.oid) &&
5636 !oidset_contains(&shown, &commit->object.oid)) {
5637 commit_list_insert(commit, &list);
5638 if (!commit->parents) {
5639 commit = NULL;
5640 break;
5642 commit = commit->parents->item;
5645 if (!commit)
5646 strbuf_addf(out, "%s %s\n", cmd_reset,
5647 rebase_cousins || root_with_onto ?
5648 "onto" : "[new root]");
5649 else {
5650 const char *to = NULL;
5652 entry = oidmap_get(&state.commit2label,
5653 &commit->object.oid);
5654 if (entry)
5655 to = entry->string;
5656 else if (!rebase_cousins)
5657 to = label_oid(&commit->object.oid, NULL,
5658 &state);
5660 if (!to || !strcmp(to, "onto"))
5661 strbuf_addf(out, "%s onto\n", cmd_reset);
5662 else {
5663 strbuf_reset(&oneline);
5664 pretty_print_commit(pp, commit, &oneline);
5665 strbuf_addf(out, "%s %s # %s\n",
5666 cmd_reset, to, oneline.buf);
5670 for (iter2 = list; iter2; iter2 = iter2->next) {
5671 struct object_id *oid = &iter2->item->object.oid;
5672 entry = oidmap_get(&commit2todo, oid);
5673 /* only show if not already upstream */
5674 if (entry)
5675 strbuf_addf(out, "%s\n", entry->string);
5676 entry = oidmap_get(&state.commit2label, oid);
5677 if (entry)
5678 strbuf_addf(out, "%s %s\n",
5679 cmd_label, entry->string);
5680 oidset_insert(&shown, oid);
5683 free_commit_list(list);
5686 free_commit_list(commits);
5687 free_commit_list(tips);
5689 strbuf_release(&label);
5690 strbuf_release(&oneline);
5691 strbuf_release(&buf);
5693 oidmap_free(&commit2todo, 1);
5694 oidmap_free(&state.commit2label, 1);
5695 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5696 strbuf_release(&state.buf);
5698 return 0;
5701 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5702 const char **argv, unsigned flags)
5704 char *format = NULL;
5705 struct pretty_print_context pp = {0};
5706 struct rev_info revs;
5707 struct commit *commit;
5708 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5709 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5710 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5711 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5712 int skipped_commit = 0;
5713 int ret = 0;
5715 repo_init_revisions(r, &revs, NULL);
5716 revs.verbose_header = 1;
5717 if (!rebase_merges)
5718 revs.max_parents = 1;
5719 revs.cherry_mark = !reapply_cherry_picks;
5720 revs.limited = 1;
5721 revs.reverse = 1;
5722 revs.right_only = 1;
5723 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5724 revs.topo_order = 1;
5726 revs.pretty_given = 1;
5727 git_config_get_string("rebase.instructionFormat", &format);
5728 if (!format || !*format) {
5729 free(format);
5730 format = xstrdup("%s");
5732 get_commit_format(format, &revs);
5733 free(format);
5734 pp.fmt = revs.commit_format;
5735 pp.output_encoding = get_log_output_encoding();
5737 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5738 ret = error(_("make_script: unhandled options"));
5739 goto cleanup;
5742 if (prepare_revision_walk(&revs) < 0) {
5743 ret = error(_("make_script: error preparing revisions"));
5744 goto cleanup;
5747 if (rebase_merges) {
5748 ret = make_script_with_merges(&pp, &revs, out, flags);
5749 goto cleanup;
5752 while ((commit = get_revision(&revs))) {
5753 int is_empty = is_original_commit_empty(commit);
5755 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5756 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5757 warning(_("skipped previously applied commit %s"),
5758 short_commit_name(commit));
5759 skipped_commit = 1;
5760 continue;
5762 if (is_empty && !keep_empty)
5763 continue;
5764 strbuf_addf(out, "%s %s ", insn,
5765 oid_to_hex(&commit->object.oid));
5766 pretty_print_commit(&pp, commit, out);
5767 if (is_empty)
5768 strbuf_addf(out, " %c empty", comment_line_char);
5769 strbuf_addch(out, '\n');
5771 if (skipped_commit)
5772 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5773 _("use --reapply-cherry-picks to include skipped commits"));
5774 cleanup:
5775 release_revisions(&revs);
5776 return ret;
5780 * Add commands after pick and (series of) squash/fixup commands
5781 * in the todo list.
5783 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5784 struct string_list *commands)
5786 struct strbuf *buf = &todo_list->buf;
5787 size_t base_offset = buf->len;
5788 int i, insert, nr = 0, alloc = 0;
5789 struct todo_item *items = NULL, *base_items = NULL;
5791 CALLOC_ARRAY(base_items, commands->nr);
5792 for (i = 0; i < commands->nr; i++) {
5793 size_t command_len = strlen(commands->items[i].string);
5795 strbuf_addstr(buf, commands->items[i].string);
5796 strbuf_addch(buf, '\n');
5798 base_items[i].command = TODO_EXEC;
5799 base_items[i].offset_in_buf = base_offset;
5800 base_items[i].arg_offset = base_offset;
5801 base_items[i].arg_len = command_len;
5803 base_offset += command_len + 1;
5807 * Insert <commands> after every pick. Here, fixup/squash chains
5808 * are considered part of the pick, so we insert the commands *after*
5809 * those chains if there are any.
5811 * As we insert the exec commands immediately after rearranging
5812 * any fixups and before the user edits the list, a fixup chain
5813 * can never contain comments (any comments are empty picks that
5814 * have been commented out because the user did not specify
5815 * --keep-empty). So, it is safe to insert an exec command
5816 * without looking at the command following a comment.
5818 insert = 0;
5819 for (i = 0; i < todo_list->nr; i++) {
5820 enum todo_command command = todo_list->items[i].command;
5821 if (insert && !is_fixup(command)) {
5822 ALLOC_GROW(items, nr + commands->nr, alloc);
5823 COPY_ARRAY(items + nr, base_items, commands->nr);
5824 nr += commands->nr;
5826 insert = 0;
5829 ALLOC_GROW(items, nr + 1, alloc);
5830 items[nr++] = todo_list->items[i];
5832 if (command == TODO_PICK || command == TODO_MERGE)
5833 insert = 1;
5836 /* insert or append final <commands> */
5837 if (insert) {
5838 ALLOC_GROW(items, nr + commands->nr, alloc);
5839 COPY_ARRAY(items + nr, base_items, commands->nr);
5840 nr += commands->nr;
5843 free(base_items);
5844 FREE_AND_NULL(todo_list->items);
5845 todo_list->items = items;
5846 todo_list->nr = nr;
5847 todo_list->alloc = alloc;
5850 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5851 struct strbuf *buf, int num, unsigned flags)
5853 struct todo_item *item;
5854 int i, max = todo_list->nr;
5856 if (num > 0 && num < max)
5857 max = num;
5859 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5860 char cmd;
5862 /* if the item is not a command write it and continue */
5863 if (item->command >= TODO_COMMENT) {
5864 strbuf_addf(buf, "%.*s\n", item->arg_len,
5865 todo_item_get_arg(todo_list, item));
5866 continue;
5869 /* add command to the buffer */
5870 cmd = command_to_char(item->command);
5871 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5872 strbuf_addch(buf, cmd);
5873 else
5874 strbuf_addstr(buf, command_to_string(item->command));
5876 /* add commit id */
5877 if (item->commit) {
5878 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5879 short_commit_name(item->commit) :
5880 oid_to_hex(&item->commit->object.oid);
5882 if (item->command == TODO_FIXUP) {
5883 if (item->flags & TODO_EDIT_FIXUP_MSG)
5884 strbuf_addstr(buf, " -c");
5885 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5886 strbuf_addstr(buf, " -C");
5890 if (item->command == TODO_MERGE) {
5891 if (item->flags & TODO_EDIT_MERGE_MSG)
5892 strbuf_addstr(buf, " -c");
5893 else
5894 strbuf_addstr(buf, " -C");
5897 strbuf_addf(buf, " %s", oid);
5900 /* add all the rest */
5901 if (!item->arg_len)
5902 strbuf_addch(buf, '\n');
5903 else
5904 strbuf_addf(buf, " %.*s\n", item->arg_len,
5905 todo_item_get_arg(todo_list, item));
5909 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5910 const char *file, const char *shortrevisions,
5911 const char *shortonto, int num, unsigned flags)
5913 int res;
5914 struct strbuf buf = STRBUF_INIT;
5916 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5917 if (flags & TODO_LIST_APPEND_TODO_HELP)
5918 append_todo_help(count_commands(todo_list),
5919 shortrevisions, shortonto, &buf);
5921 res = write_message(buf.buf, buf.len, file, 0);
5922 strbuf_release(&buf);
5924 return res;
5927 /* skip picking commits whose parents are unchanged */
5928 static int skip_unnecessary_picks(struct repository *r,
5929 struct todo_list *todo_list,
5930 struct object_id *base_oid)
5932 struct object_id *parent_oid;
5933 int i;
5935 for (i = 0; i < todo_list->nr; i++) {
5936 struct todo_item *item = todo_list->items + i;
5938 if (item->command >= TODO_NOOP)
5939 continue;
5940 if (item->command != TODO_PICK)
5941 break;
5942 if (repo_parse_commit(r, item->commit)) {
5943 return error(_("could not parse commit '%s'"),
5944 oid_to_hex(&item->commit->object.oid));
5946 if (!item->commit->parents)
5947 break; /* root commit */
5948 if (item->commit->parents->next)
5949 break; /* merge commit */
5950 parent_oid = &item->commit->parents->item->object.oid;
5951 if (!oideq(parent_oid, base_oid))
5952 break;
5953 oidcpy(base_oid, &item->commit->object.oid);
5955 if (i > 0) {
5956 const char *done_path = rebase_path_done();
5958 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5959 error_errno(_("could not write to '%s'"), done_path);
5960 return -1;
5963 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5964 todo_list->nr -= i;
5965 todo_list->current = 0;
5966 todo_list->done_nr += i;
5968 if (is_fixup(peek_command(todo_list, 0)))
5969 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5972 return 0;
5975 struct todo_add_branch_context {
5976 struct todo_item *items;
5977 size_t items_nr;
5978 size_t items_alloc;
5979 struct strbuf *buf;
5980 struct commit *commit;
5981 struct string_list refs_to_oids;
5984 static int add_decorations_to_list(const struct commit *commit,
5985 struct todo_add_branch_context *ctx)
5987 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5988 const char *head_ref = resolve_ref_unsafe("HEAD",
5989 RESOLVE_REF_READING,
5990 NULL,
5991 NULL);
5993 while (decoration) {
5994 struct todo_item *item;
5995 const char *path;
5996 size_t base_offset = ctx->buf->len;
5999 * If the branch is the current HEAD, then it will be
6000 * updated by the default rebase behavior.
6002 if (head_ref && !strcmp(head_ref, decoration->name)) {
6003 decoration = decoration->next;
6004 continue;
6007 ALLOC_GROW(ctx->items,
6008 ctx->items_nr + 1,
6009 ctx->items_alloc);
6010 item = &ctx->items[ctx->items_nr];
6011 memset(item, 0, sizeof(*item));
6013 /* If the branch is checked out, then leave a comment instead. */
6014 if ((path = branch_checked_out(decoration->name))) {
6015 item->command = TODO_COMMENT;
6016 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6017 decoration->name, path);
6018 } else {
6019 struct string_list_item *sti;
6020 item->command = TODO_UPDATE_REF;
6021 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6023 sti = string_list_insert(&ctx->refs_to_oids,
6024 decoration->name);
6025 sti->util = init_update_ref_record(decoration->name);
6028 item->offset_in_buf = base_offset;
6029 item->arg_offset = base_offset;
6030 item->arg_len = ctx->buf->len - base_offset;
6031 ctx->items_nr++;
6033 decoration = decoration->next;
6036 return 0;
6040 * For each 'pick' command, find out if the commit has a decoration in
6041 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6043 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6045 int i, res;
6046 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6047 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6048 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6049 struct decoration_filter decoration_filter = {
6050 .include_ref_pattern = &decorate_refs_include,
6051 .exclude_ref_pattern = &decorate_refs_exclude,
6052 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6054 struct todo_add_branch_context ctx = {
6055 .buf = &todo_list->buf,
6056 .refs_to_oids = STRING_LIST_INIT_DUP,
6059 ctx.items_alloc = 2 * todo_list->nr + 1;
6060 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6062 string_list_append(&decorate_refs_include, "refs/heads/");
6063 load_ref_decorations(&decoration_filter, 0);
6065 for (i = 0; i < todo_list->nr; ) {
6066 struct todo_item *item = &todo_list->items[i];
6068 /* insert ith item into new list */
6069 ALLOC_GROW(ctx.items,
6070 ctx.items_nr + 1,
6071 ctx.items_alloc);
6073 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6075 if (item->commit) {
6076 ctx.commit = item->commit;
6077 add_decorations_to_list(item->commit, &ctx);
6081 res = write_update_refs_state(&ctx.refs_to_oids);
6083 string_list_clear(&ctx.refs_to_oids, 1);
6085 if (res) {
6086 /* we failed, so clean up the new list. */
6087 free(ctx.items);
6088 return res;
6091 free(todo_list->items);
6092 todo_list->items = ctx.items;
6093 todo_list->nr = ctx.items_nr;
6094 todo_list->alloc = ctx.items_alloc;
6096 return 0;
6099 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6100 const char *shortrevisions, const char *onto_name,
6101 struct commit *onto, const struct object_id *orig_head,
6102 struct string_list *commands, unsigned autosquash,
6103 unsigned update_refs,
6104 struct todo_list *todo_list)
6106 char shortonto[GIT_MAX_HEXSZ + 1];
6107 const char *todo_file = rebase_path_todo();
6108 struct todo_list new_todo = TODO_LIST_INIT;
6109 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6110 struct object_id oid = onto->object.oid;
6111 int res;
6113 repo_find_unique_abbrev_r(r, shortonto, &oid,
6114 DEFAULT_ABBREV);
6116 if (buf->len == 0) {
6117 struct todo_item *item = append_new_todo(todo_list);
6118 item->command = TODO_NOOP;
6119 item->commit = NULL;
6120 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6123 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6124 return -1;
6126 if (autosquash && todo_list_rearrange_squash(todo_list))
6127 return -1;
6129 if (commands->nr)
6130 todo_list_add_exec_commands(todo_list, commands);
6132 if (count_commands(todo_list) == 0) {
6133 apply_autostash(rebase_path_autostash());
6134 sequencer_remove_state(opts);
6136 return error(_("nothing to do"));
6139 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6140 shortonto, flags);
6141 if (res == -1)
6142 return -1;
6143 else if (res == -2) {
6144 apply_autostash(rebase_path_autostash());
6145 sequencer_remove_state(opts);
6147 return -1;
6148 } else if (res == -3) {
6149 apply_autostash(rebase_path_autostash());
6150 sequencer_remove_state(opts);
6151 todo_list_release(&new_todo);
6153 return error(_("nothing to do"));
6154 } else if (res == -4) {
6155 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6156 todo_list_release(&new_todo);
6158 return -1;
6161 /* Expand the commit IDs */
6162 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6163 strbuf_swap(&new_todo.buf, &buf2);
6164 strbuf_release(&buf2);
6165 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6166 new_todo.total_nr = 0;
6167 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6168 BUG("invalid todo list after expanding IDs:\n%s",
6169 new_todo.buf.buf);
6171 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6172 todo_list_release(&new_todo);
6173 return error(_("could not skip unnecessary pick commands"));
6176 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6177 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6178 todo_list_release(&new_todo);
6179 return error_errno(_("could not write '%s'"), todo_file);
6182 res = -1;
6184 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6185 goto cleanup;
6187 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6188 goto cleanup;
6190 todo_list_write_total_nr(&new_todo);
6191 res = pick_commits(r, &new_todo, opts);
6193 cleanup:
6194 todo_list_release(&new_todo);
6196 return res;
6199 struct subject2item_entry {
6200 struct hashmap_entry entry;
6201 int i;
6202 char subject[FLEX_ARRAY];
6205 static int subject2item_cmp(const void *fndata UNUSED,
6206 const struct hashmap_entry *eptr,
6207 const struct hashmap_entry *entry_or_key,
6208 const void *key)
6210 const struct subject2item_entry *a, *b;
6212 a = container_of(eptr, const struct subject2item_entry, entry);
6213 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6215 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6218 define_commit_slab(commit_todo_item, struct todo_item *);
6220 static int skip_fixupish(const char *subject, const char **p) {
6221 return skip_prefix(subject, "fixup! ", p) ||
6222 skip_prefix(subject, "amend! ", p) ||
6223 skip_prefix(subject, "squash! ", p);
6227 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6228 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6229 * after the former, and change "pick" to "fixup"/"squash".
6231 * Note that if the config has specified a custom instruction format, each log
6232 * message will have to be retrieved from the commit (as the oneline in the
6233 * script cannot be trusted) in order to normalize the autosquash arrangement.
6235 int todo_list_rearrange_squash(struct todo_list *todo_list)
6237 struct hashmap subject2item;
6238 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6239 char **subjects;
6240 struct commit_todo_item commit_todo;
6241 struct todo_item *items = NULL;
6243 init_commit_todo_item(&commit_todo);
6245 * The hashmap maps onelines to the respective todo list index.
6247 * If any items need to be rearranged, the next[i] value will indicate
6248 * which item was moved directly after the i'th.
6250 * In that case, last[i] will indicate the index of the latest item to
6251 * be moved to appear after the i'th.
6253 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6254 ALLOC_ARRAY(next, todo_list->nr);
6255 ALLOC_ARRAY(tail, todo_list->nr);
6256 ALLOC_ARRAY(subjects, todo_list->nr);
6257 for (i = 0; i < todo_list->nr; i++) {
6258 struct strbuf buf = STRBUF_INIT;
6259 struct todo_item *item = todo_list->items + i;
6260 const char *commit_buffer, *subject, *p;
6261 size_t subject_len;
6262 int i2 = -1;
6263 struct subject2item_entry *entry;
6265 next[i] = tail[i] = -1;
6266 if (!item->commit || item->command == TODO_DROP) {
6267 subjects[i] = NULL;
6268 continue;
6271 if (is_fixup(item->command)) {
6272 clear_commit_todo_item(&commit_todo);
6273 return error(_("the script was already rearranged."));
6276 repo_parse_commit(the_repository, item->commit);
6277 commit_buffer = repo_logmsg_reencode(the_repository,
6278 item->commit, NULL,
6279 "UTF-8");
6280 find_commit_subject(commit_buffer, &subject);
6281 format_subject(&buf, subject, " ");
6282 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6283 repo_unuse_commit_buffer(the_repository, item->commit,
6284 commit_buffer);
6285 if (skip_fixupish(subject, &p)) {
6286 struct commit *commit2;
6288 for (;;) {
6289 while (isspace(*p))
6290 p++;
6291 if (!skip_fixupish(p, &p))
6292 break;
6295 entry = hashmap_get_entry_from_hash(&subject2item,
6296 strhash(p), p,
6297 struct subject2item_entry,
6298 entry);
6299 if (entry)
6300 /* found by title */
6301 i2 = entry->i;
6302 else if (!strchr(p, ' ') &&
6303 (commit2 =
6304 lookup_commit_reference_by_name(p)) &&
6305 *commit_todo_item_at(&commit_todo, commit2))
6306 /* found by commit name */
6307 i2 = *commit_todo_item_at(&commit_todo, commit2)
6308 - todo_list->items;
6309 else {
6310 /* copy can be a prefix of the commit subject */
6311 for (i2 = 0; i2 < i; i2++)
6312 if (subjects[i2] &&
6313 starts_with(subjects[i2], p))
6314 break;
6315 if (i2 == i)
6316 i2 = -1;
6319 if (i2 >= 0) {
6320 rearranged = 1;
6321 if (starts_with(subject, "fixup!")) {
6322 todo_list->items[i].command = TODO_FIXUP;
6323 } else if (starts_with(subject, "amend!")) {
6324 todo_list->items[i].command = TODO_FIXUP;
6325 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6326 } else {
6327 todo_list->items[i].command = TODO_SQUASH;
6329 if (tail[i2] < 0) {
6330 next[i] = next[i2];
6331 next[i2] = i;
6332 } else {
6333 next[i] = next[tail[i2]];
6334 next[tail[i2]] = i;
6336 tail[i2] = i;
6337 } else if (!hashmap_get_from_hash(&subject2item,
6338 strhash(subject), subject)) {
6339 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6340 entry->i = i;
6341 hashmap_entry_init(&entry->entry,
6342 strhash(entry->subject));
6343 hashmap_put(&subject2item, &entry->entry);
6346 *commit_todo_item_at(&commit_todo, item->commit) = item;
6349 if (rearranged) {
6350 for (i = 0; i < todo_list->nr; i++) {
6351 enum todo_command command = todo_list->items[i].command;
6352 int cur = i;
6355 * Initially, all commands are 'pick's. If it is a
6356 * fixup or a squash now, we have rearranged it.
6358 if (is_fixup(command))
6359 continue;
6361 while (cur >= 0) {
6362 ALLOC_GROW(items, nr + 1, alloc);
6363 items[nr++] = todo_list->items[cur];
6364 cur = next[cur];
6368 FREE_AND_NULL(todo_list->items);
6369 todo_list->items = items;
6370 todo_list->nr = nr;
6371 todo_list->alloc = alloc;
6374 free(next);
6375 free(tail);
6376 for (i = 0; i < todo_list->nr; i++)
6377 free(subjects[i]);
6378 free(subjects);
6379 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6381 clear_commit_todo_item(&commit_todo);
6383 return 0;
6386 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6388 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6389 struct object_id cherry_pick_head, rebase_head;
6391 if (file_exists(git_path_seq_dir()))
6392 *whence = FROM_CHERRY_PICK_MULTI;
6393 if (file_exists(rebase_path()) &&
6394 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6395 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6396 oideq(&rebase_head, &cherry_pick_head))
6397 *whence = FROM_REBASE_PICK;
6398 else
6399 *whence = FROM_CHERRY_PICK_SINGLE;
6401 return 1;
6404 return 0;
6407 int sequencer_get_update_refs_state(const char *wt_dir,
6408 struct string_list *refs)
6410 int result = 0;
6411 FILE *fp = NULL;
6412 struct strbuf ref = STRBUF_INIT;
6413 struct strbuf hash = STRBUF_INIT;
6414 struct update_ref_record *rec = NULL;
6416 char *path = rebase_path_update_refs(wt_dir);
6418 fp = fopen(path, "r");
6419 if (!fp)
6420 goto cleanup;
6422 while (strbuf_getline(&ref, fp) != EOF) {
6423 struct string_list_item *item;
6425 CALLOC_ARRAY(rec, 1);
6427 if (strbuf_getline(&hash, fp) == EOF ||
6428 get_oid_hex(hash.buf, &rec->before)) {
6429 warning(_("update-refs file at '%s' is invalid"),
6430 path);
6431 result = -1;
6432 goto cleanup;
6435 if (strbuf_getline(&hash, fp) == EOF ||
6436 get_oid_hex(hash.buf, &rec->after)) {
6437 warning(_("update-refs file at '%s' is invalid"),
6438 path);
6439 result = -1;
6440 goto cleanup;
6443 item = string_list_insert(refs, ref.buf);
6444 item->util = rec;
6445 rec = NULL;
6448 cleanup:
6449 if (fp)
6450 fclose(fp);
6451 free(path);
6452 free(rec);
6453 strbuf_release(&ref);
6454 strbuf_release(&hash);
6455 return result;