BreakingChanges: document removal of grafting
[git/gitster.git] / sequencer.c
blob2c19846385baa1df3240e865752087db827ba36e
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
14 #include "object.h"
15 #include "pager.h"
16 #include "commit.h"
17 #include "sequencer.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "utf8.h"
21 #include "cache-tree.h"
22 #include "diff.h"
23 #include "path.h"
24 #include "revision.h"
25 #include "rerere.h"
26 #include "merge.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
29 #include "refs.h"
30 #include "sparse-index.h"
31 #include "strvec.h"
32 #include "quote.h"
33 #include "trailer.h"
34 #include "log-tree.h"
35 #include "wt-status.h"
36 #include "hashmap.h"
37 #include "notes-utils.h"
38 #include "sigchain.h"
39 #include "unpack-trees.h"
40 #include "oidmap.h"
41 #include "oidset.h"
42 #include "commit-slab.h"
43 #include "alias.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
46 #include "reset.h"
47 #include "branch.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
55 * are too long.
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
87 * actions.
89 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
92 * for the prompt).
94 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
130 * being rebased.
132 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189 * The following files are written by git-rebase just after parsing the
190 * command-line.
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
211 * A 'struct update_refs_record' represents a value in the update-refs
212 * list. We use a string_list to map refs to these (before, after) pairs.
214 struct update_ref_record {
215 struct object_id before;
216 struct object_id after;
219 static struct update_ref_record *init_update_ref_record(const char *ref)
221 struct update_ref_record *rec;
223 CALLOC_ARRAY(rec, 1);
225 oidcpy(&rec->before, null_oid());
226 oidcpy(&rec->after, null_oid());
228 /* This may fail, but that's fine, we will keep the null OID. */
229 read_ref(ref, &rec->before);
231 return rec;
234 static int git_sequencer_config(const char *k, const char *v,
235 const struct config_context *ctx, void *cb)
237 struct replay_opts *opts = cb;
239 if (!strcmp(k, "commit.cleanup")) {
240 if (!v)
241 return config_error_nonbool(k);
243 if (!strcmp(v, "verbatim")) {
244 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
245 opts->explicit_cleanup = 1;
246 } else if (!strcmp(v, "whitespace")) {
247 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
248 opts->explicit_cleanup = 1;
249 } else if (!strcmp(v, "strip")) {
250 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
251 opts->explicit_cleanup = 1;
252 } else if (!strcmp(v, "scissors")) {
253 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
254 opts->explicit_cleanup = 1;
255 } else {
256 warning(_("invalid commit message cleanup mode '%s'"),
260 return 0;
263 if (!strcmp(k, "commit.gpgsign")) {
264 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
265 return 0;
268 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
269 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
270 if (ret == 0) {
272 * pull.twohead is allowed to be multi-valued; we only
273 * care about the first value.
275 char *tmp = strchr(opts->default_strategy, ' ');
276 if (tmp)
277 *tmp = '\0';
279 return ret;
282 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
283 opts->commit_use_reference = git_config_bool(k, v);
285 return git_diff_basic_config(k, v, ctx, NULL);
288 void sequencer_init_config(struct replay_opts *opts)
290 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
291 git_config(git_sequencer_config, opts);
294 static inline int is_rebase_i(const struct replay_opts *opts)
296 return opts->action == REPLAY_INTERACTIVE_REBASE;
299 static const char *get_dir(const struct replay_opts *opts)
301 if (is_rebase_i(opts))
302 return rebase_path();
303 return git_path_seq_dir();
306 static const char *get_todo_path(const struct replay_opts *opts)
308 if (is_rebase_i(opts))
309 return rebase_path_todo();
310 return git_path_todo_file();
314 * Returns 0 for non-conforming footer
315 * Returns 1 for conforming footer
316 * Returns 2 when sob exists within conforming footer
317 * Returns 3 when sob exists within conforming footer as last entry
319 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
320 size_t ignore_footer)
322 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
323 struct trailer_info info;
324 size_t i;
325 int found_sob = 0, found_sob_last = 0;
326 char saved_char;
328 opts.no_divider = 1;
330 if (ignore_footer) {
331 saved_char = sb->buf[sb->len - ignore_footer];
332 sb->buf[sb->len - ignore_footer] = '\0';
335 trailer_info_get(&opts, sb->buf, &info);
337 if (ignore_footer)
338 sb->buf[sb->len - ignore_footer] = saved_char;
340 if (info.trailer_block_start == info.trailer_block_end)
341 return 0;
343 for (i = 0; i < info.trailer_nr; i++)
344 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
345 found_sob = 1;
346 if (i == info.trailer_nr - 1)
347 found_sob_last = 1;
350 trailer_info_release(&info);
352 if (found_sob_last)
353 return 3;
354 if (found_sob)
355 return 2;
356 return 1;
359 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
361 static struct strbuf buf = STRBUF_INIT;
363 strbuf_reset(&buf);
364 if (opts->gpg_sign)
365 sq_quotef(&buf, "-S%s", opts->gpg_sign);
366 return buf.buf;
369 void replay_opts_release(struct replay_opts *opts)
371 free(opts->gpg_sign);
372 free(opts->reflog_action);
373 free(opts->default_strategy);
374 free(opts->strategy);
375 strvec_clear (&opts->xopts);
376 strbuf_release(&opts->current_fixups);
377 if (opts->revs)
378 release_revisions(opts->revs);
379 free(opts->revs);
382 int sequencer_remove_state(struct replay_opts *opts)
384 struct strbuf buf = STRBUF_INIT;
385 int ret = 0;
387 if (is_rebase_i(opts) &&
388 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
389 char *p = buf.buf;
390 while (*p) {
391 char *eol = strchr(p, '\n');
392 if (eol)
393 *eol = '\0';
394 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
395 warning(_("could not delete '%s'"), p);
396 ret = -1;
398 if (!eol)
399 break;
400 p = eol + 1;
404 strbuf_reset(&buf);
405 strbuf_addstr(&buf, get_dir(opts));
406 if (remove_dir_recursively(&buf, 0))
407 ret = error(_("could not remove '%s'"), buf.buf);
408 strbuf_release(&buf);
410 return ret;
413 static const char *action_name(const struct replay_opts *opts)
415 switch (opts->action) {
416 case REPLAY_REVERT:
417 return N_("revert");
418 case REPLAY_PICK:
419 return N_("cherry-pick");
420 case REPLAY_INTERACTIVE_REBASE:
421 return N_("rebase");
423 die(_("unknown action: %d"), opts->action);
426 struct commit_message {
427 char *parent_label;
428 char *label;
429 char *subject;
430 const char *message;
433 static const char *short_commit_name(struct repository *r, struct commit *commit)
435 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
438 static int get_message(struct commit *commit, struct commit_message *out)
440 const char *abbrev, *subject;
441 int subject_len;
443 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
444 get_commit_output_encoding());
445 abbrev = short_commit_name(the_repository, commit);
447 subject_len = find_commit_subject(out->message, &subject);
449 out->subject = xmemdupz(subject, subject_len);
450 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
451 out->parent_label = xstrfmt("parent of %s", out->label);
453 return 0;
456 static void free_message(struct commit *commit, struct commit_message *msg)
458 free(msg->parent_label);
459 free(msg->label);
460 free(msg->subject);
461 repo_unuse_commit_buffer(the_repository, commit, msg->message);
464 const char *rebase_resolvemsg =
465 N_("Resolve all conflicts manually, mark them as resolved with\n"
466 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
467 "You can instead skip this commit: run \"git rebase --skip\".\n"
468 "To abort and get back to the state before \"git rebase\", run "
469 "\"git rebase --abort\".");
471 static void print_advice(struct repository *r, int show_hint,
472 struct replay_opts *opts)
474 const char *msg;
476 if (is_rebase_i(opts))
477 msg = rebase_resolvemsg;
478 else
479 msg = getenv("GIT_CHERRY_PICK_HELP");
481 if (msg) {
482 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
484 * A conflict has occurred but the porcelain
485 * (typically rebase --interactive) wants to take care
486 * of the commit itself so remove CHERRY_PICK_HEAD
488 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
489 NULL, REF_NO_DEREF);
490 return;
493 if (show_hint) {
494 if (opts->no_commit)
495 advise_if_enabled(ADVICE_MERGE_CONFLICT,
496 _("after resolving the conflicts, mark the corrected paths\n"
497 "with 'git add <paths>' or 'git rm <paths>'"));
498 else if (opts->action == REPLAY_PICK)
499 advise_if_enabled(ADVICE_MERGE_CONFLICT,
500 _("After resolving the conflicts, mark them with\n"
501 "\"git add/rm <pathspec>\", then run\n"
502 "\"git cherry-pick --continue\".\n"
503 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
504 "To abort and get back to the state before \"git cherry-pick\",\n"
505 "run \"git cherry-pick --abort\"."));
506 else if (opts->action == REPLAY_REVERT)
507 advise_if_enabled(ADVICE_MERGE_CONFLICT,
508 _("After resolving the conflicts, mark them with\n"
509 "\"git add/rm <pathspec>\", then run\n"
510 "\"git revert --continue\".\n"
511 "You can instead skip this commit with \"git revert --skip\".\n"
512 "To abort and get back to the state before \"git revert\",\n"
513 "run \"git revert --abort\"."));
514 else
515 BUG("unexpected pick action in print_advice()");
519 static int write_message(const void *buf, size_t len, const char *filename,
520 int append_eol)
522 struct lock_file msg_file = LOCK_INIT;
524 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
525 if (msg_fd < 0)
526 return error_errno(_("could not lock '%s'"), filename);
527 if (write_in_full(msg_fd, buf, len) < 0) {
528 error_errno(_("could not write to '%s'"), filename);
529 rollback_lock_file(&msg_file);
530 return -1;
532 if (append_eol && write(msg_fd, "\n", 1) < 0) {
533 error_errno(_("could not write eol to '%s'"), filename);
534 rollback_lock_file(&msg_file);
535 return -1;
537 if (commit_lock_file(&msg_file) < 0)
538 return error(_("failed to finalize '%s'"), filename);
540 return 0;
543 int read_oneliner(struct strbuf *buf,
544 const char *path, unsigned flags)
546 int orig_len = buf->len;
548 if (strbuf_read_file(buf, path, 0) < 0) {
549 if ((flags & READ_ONELINER_WARN_MISSING) ||
550 (errno != ENOENT && errno != ENOTDIR))
551 warning_errno(_("could not read '%s'"), path);
552 return 0;
555 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
556 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
557 --buf->len;
558 buf->buf[buf->len] = '\0';
561 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
562 return 0;
564 return 1;
567 static struct tree *empty_tree(struct repository *r)
569 return lookup_tree(r, the_hash_algo->empty_tree);
572 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
574 if (repo_read_index_unmerged(repo))
575 return error_resolve_conflict(action_name(opts));
577 error(_("your local changes would be overwritten by %s."),
578 _(action_name(opts)));
580 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
581 advise(_("commit your changes or stash them to proceed."));
582 return -1;
585 static void update_abort_safety_file(void)
587 struct object_id head;
589 /* Do nothing on a single-pick */
590 if (!file_exists(git_path_seq_dir()))
591 return;
593 if (!repo_get_oid(the_repository, "HEAD", &head))
594 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
595 else
596 write_file(git_path_abort_safety_file(), "%s", "");
599 static int fast_forward_to(struct repository *r,
600 const struct object_id *to,
601 const struct object_id *from,
602 int unborn,
603 struct replay_opts *opts)
605 struct ref_transaction *transaction;
606 struct strbuf sb = STRBUF_INIT;
607 struct strbuf err = STRBUF_INIT;
609 repo_read_index(r);
610 if (checkout_fast_forward(r, from, to, 1))
611 return -1; /* the callee should have complained already */
613 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
615 transaction = ref_transaction_begin(&err);
616 if (!transaction ||
617 ref_transaction_update(transaction, "HEAD",
618 to, unborn && !is_rebase_i(opts) ?
619 null_oid() : from,
620 0, sb.buf, &err) ||
621 ref_transaction_commit(transaction, &err)) {
622 ref_transaction_free(transaction);
623 error("%s", err.buf);
624 strbuf_release(&sb);
625 strbuf_release(&err);
626 return -1;
629 strbuf_release(&sb);
630 strbuf_release(&err);
631 ref_transaction_free(transaction);
632 update_abort_safety_file();
633 return 0;
636 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
637 int use_editor)
639 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
640 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
641 COMMIT_MSG_CLEANUP_SPACE;
642 else if (!strcmp(cleanup_arg, "verbatim"))
643 return COMMIT_MSG_CLEANUP_NONE;
644 else if (!strcmp(cleanup_arg, "whitespace"))
645 return COMMIT_MSG_CLEANUP_SPACE;
646 else if (!strcmp(cleanup_arg, "strip"))
647 return COMMIT_MSG_CLEANUP_ALL;
648 else if (!strcmp(cleanup_arg, "scissors"))
649 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
650 COMMIT_MSG_CLEANUP_SPACE;
651 else
652 die(_("Invalid cleanup mode %s"), cleanup_arg);
656 * NB using int rather than enum cleanup_mode to stop clang's
657 * -Wtautological-constant-out-of-range-compare complaining that the comparison
658 * is always true.
660 static const char *describe_cleanup_mode(int cleanup_mode)
662 static const char *modes[] = { "whitespace",
663 "verbatim",
664 "scissors",
665 "strip" };
667 if (cleanup_mode < ARRAY_SIZE(modes))
668 return modes[cleanup_mode];
670 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
673 void append_conflicts_hint(struct index_state *istate,
674 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
676 int i;
678 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
679 strbuf_addch(msgbuf, '\n');
680 wt_status_append_cut_line(msgbuf);
681 strbuf_addstr(msgbuf, comment_line_str);
684 strbuf_addch(msgbuf, '\n');
685 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
686 for (i = 0; i < istate->cache_nr;) {
687 const struct cache_entry *ce = istate->cache[i++];
688 if (ce_stage(ce)) {
689 strbuf_commented_addf(msgbuf, comment_line_str,
690 "\t%s\n", ce->name);
691 while (i < istate->cache_nr &&
692 !strcmp(ce->name, istate->cache[i]->name))
693 i++;
698 static int do_recursive_merge(struct repository *r,
699 struct commit *base, struct commit *next,
700 const char *base_label, const char *next_label,
701 struct object_id *head, struct strbuf *msgbuf,
702 struct replay_opts *opts)
704 struct merge_options o;
705 struct merge_result result;
706 struct tree *next_tree, *base_tree, *head_tree;
707 int clean, show_output;
708 int i;
709 struct lock_file index_lock = LOCK_INIT;
711 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
712 return -1;
714 repo_read_index(r);
716 init_merge_options(&o, r);
717 o.ancestor = base ? base_label : "(empty tree)";
718 o.branch1 = "HEAD";
719 o.branch2 = next ? next_label : "(empty tree)";
720 if (is_rebase_i(opts))
721 o.buffer_output = 2;
722 o.show_rename_progress = 1;
724 head_tree = parse_tree_indirect(head);
725 if (!head_tree)
726 return error(_("unable to read tree (%s)"), oid_to_hex(head));
727 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
728 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
730 for (i = 0; i < opts->xopts.nr; i++)
731 parse_merge_opt(&o, opts->xopts.v[i]);
733 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
734 memset(&result, 0, sizeof(result));
735 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
736 &result);
737 show_output = !is_rebase_i(opts) || !result.clean;
739 * TODO: merge_switch_to_result will update index/working tree;
740 * we only really want to do that if !result.clean || this is
741 * the final patch to be picked. But determining this is the
742 * final patch would take some work, and "head_tree" would need
743 * to be replace with the tree the index matched before we
744 * started doing any picks.
746 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
747 clean = result.clean;
748 } else {
749 ensure_full_index(r->index);
750 clean = merge_trees(&o, head_tree, next_tree, base_tree);
751 if (is_rebase_i(opts) && clean <= 0)
752 fputs(o.obuf.buf, stdout);
753 strbuf_release(&o.obuf);
755 if (clean < 0) {
756 rollback_lock_file(&index_lock);
757 return clean;
760 if (write_locked_index(r->index, &index_lock,
761 COMMIT_LOCK | SKIP_IF_UNCHANGED))
763 * TRANSLATORS: %s will be "revert", "cherry-pick" or
764 * "rebase".
766 return error(_("%s: Unable to write new index file"),
767 _(action_name(opts)));
769 if (!clean)
770 append_conflicts_hint(r->index, msgbuf,
771 opts->default_msg_cleanup);
773 return !clean;
776 static struct object_id *get_cache_tree_oid(struct index_state *istate)
778 if (!cache_tree_fully_valid(istate->cache_tree))
779 if (cache_tree_update(istate, 0)) {
780 error(_("unable to update cache tree"));
781 return NULL;
784 return &istate->cache_tree->oid;
787 static int is_index_unchanged(struct repository *r)
789 struct object_id head_oid, *cache_tree_oid;
790 const struct object_id *head_tree_oid;
791 struct commit *head_commit;
792 struct index_state *istate = r->index;
793 const char *head_name;
795 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
796 /* Check to see if this is an unborn branch */
797 head_name = resolve_ref_unsafe("HEAD",
798 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
799 &head_oid, NULL);
800 if (!head_name ||
801 !starts_with(head_name, "refs/heads/") ||
802 !is_null_oid(&head_oid))
803 return error(_("could not resolve HEAD commit"));
804 head_tree_oid = the_hash_algo->empty_tree;
805 } else {
806 head_commit = lookup_commit(r, &head_oid);
809 * If head_commit is NULL, check_commit, called from
810 * lookup_commit, would have indicated that head_commit is not
811 * a commit object already. repo_parse_commit() will return failure
812 * without further complaints in such a case. Otherwise, if
813 * the commit is invalid, repo_parse_commit() will complain. So
814 * there is nothing for us to say here. Just return failure.
816 if (repo_parse_commit(r, head_commit))
817 return -1;
819 head_tree_oid = get_commit_tree_oid(head_commit);
822 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
823 return -1;
825 return oideq(cache_tree_oid, head_tree_oid);
828 static int write_author_script(const char *message)
830 struct strbuf buf = STRBUF_INIT;
831 const char *eol;
832 int res;
834 for (;;)
835 if (!*message || starts_with(message, "\n")) {
836 missing_author:
837 /* Missing 'author' line? */
838 unlink(rebase_path_author_script());
839 return 0;
840 } else if (skip_prefix(message, "author ", &message))
841 break;
842 else if ((eol = strchr(message, '\n')))
843 message = eol + 1;
844 else
845 goto missing_author;
847 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
848 while (*message && *message != '\n' && *message != '\r')
849 if (skip_prefix(message, " <", &message))
850 break;
851 else if (*message != '\'')
852 strbuf_addch(&buf, *(message++));
853 else
854 strbuf_addf(&buf, "'\\%c'", *(message++));
855 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
856 while (*message && *message != '\n' && *message != '\r')
857 if (skip_prefix(message, "> ", &message))
858 break;
859 else if (*message != '\'')
860 strbuf_addch(&buf, *(message++));
861 else
862 strbuf_addf(&buf, "'\\%c'", *(message++));
863 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
864 while (*message && *message != '\n' && *message != '\r')
865 if (*message != '\'')
866 strbuf_addch(&buf, *(message++));
867 else
868 strbuf_addf(&buf, "'\\%c'", *(message++));
869 strbuf_addch(&buf, '\'');
870 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
871 strbuf_release(&buf);
872 return res;
876 * Take a series of KEY='VALUE' lines where VALUE part is
877 * sq-quoted, and append <KEY, VALUE> at the end of the string list
879 static int parse_key_value_squoted(char *buf, struct string_list *list)
881 while (*buf) {
882 struct string_list_item *item;
883 char *np;
884 char *cp = strchr(buf, '=');
885 if (!cp) {
886 np = strchrnul(buf, '\n');
887 return error(_("no key present in '%.*s'"),
888 (int) (np - buf), buf);
890 np = strchrnul(cp, '\n');
891 *cp++ = '\0';
892 item = string_list_append(list, buf);
894 buf = np + (*np == '\n');
895 *np = '\0';
896 cp = sq_dequote(cp);
897 if (!cp)
898 return error(_("unable to dequote value of '%s'"),
899 item->string);
900 item->util = xstrdup(cp);
902 return 0;
906 * Reads and parses the state directory's "author-script" file, and sets name,
907 * email and date accordingly.
908 * Returns 0 on success, -1 if the file could not be parsed.
910 * The author script is of the format:
912 * GIT_AUTHOR_NAME='$author_name'
913 * GIT_AUTHOR_EMAIL='$author_email'
914 * GIT_AUTHOR_DATE='$author_date'
916 * where $author_name, $author_email and $author_date are quoted. We are strict
917 * with our parsing, as the file was meant to be eval'd in the now-removed
918 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
919 * from what this function expects, it is better to bail out than to do
920 * something that the user does not expect.
922 int read_author_script(const char *path, char **name, char **email, char **date,
923 int allow_missing)
925 struct strbuf buf = STRBUF_INIT;
926 struct string_list kv = STRING_LIST_INIT_DUP;
927 int retval = -1; /* assume failure */
928 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
930 if (strbuf_read_file(&buf, path, 256) <= 0) {
931 strbuf_release(&buf);
932 if (errno == ENOENT && allow_missing)
933 return 0;
934 else
935 return error_errno(_("could not open '%s' for reading"),
936 path);
939 if (parse_key_value_squoted(buf.buf, &kv))
940 goto finish;
942 for (i = 0; i < kv.nr; i++) {
943 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
944 if (name_i != -2)
945 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
946 else
947 name_i = i;
948 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
949 if (email_i != -2)
950 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
951 else
952 email_i = i;
953 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
954 if (date_i != -2)
955 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
956 else
957 date_i = i;
958 } else {
959 err = error(_("unknown variable '%s'"),
960 kv.items[i].string);
963 if (name_i == -2)
964 error(_("missing 'GIT_AUTHOR_NAME'"));
965 if (email_i == -2)
966 error(_("missing 'GIT_AUTHOR_EMAIL'"));
967 if (date_i == -2)
968 error(_("missing 'GIT_AUTHOR_DATE'"));
969 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
970 goto finish;
971 *name = kv.items[name_i].util;
972 *email = kv.items[email_i].util;
973 *date = kv.items[date_i].util;
974 retval = 0;
975 finish:
976 string_list_clear(&kv, !!retval);
977 strbuf_release(&buf);
978 return retval;
982 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
983 * file with shell quoting into struct strvec. Returns -1 on
984 * error, 0 otherwise.
986 static int read_env_script(struct strvec *env)
988 char *name, *email, *date;
990 if (read_author_script(rebase_path_author_script(),
991 &name, &email, &date, 0))
992 return -1;
994 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
995 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
996 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
997 free(name);
998 free(email);
999 free(date);
1001 return 0;
1004 static char *get_author(const char *message)
1006 size_t len;
1007 const char *a;
1009 a = find_commit_header(message, "author", &len);
1010 if (a)
1011 return xmemdupz(a, len);
1013 return NULL;
1016 static const char *author_date_from_env(const struct strvec *env)
1018 int i;
1019 const char *date;
1021 for (i = 0; i < env->nr; i++)
1022 if (skip_prefix(env->v[i],
1023 "GIT_AUTHOR_DATE=", &date))
1024 return date;
1026 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1027 * reading the script
1029 BUG("GIT_AUTHOR_DATE missing from author script");
1032 static const char staged_changes_advice[] =
1033 N_("you have staged changes in your working tree\n"
1034 "If these changes are meant to be squashed into the previous commit, run:\n"
1035 "\n"
1036 " git commit --amend %s\n"
1037 "\n"
1038 "If they are meant to go into a new commit, run:\n"
1039 "\n"
1040 " git commit %s\n"
1041 "\n"
1042 "In both cases, once you're done, continue with:\n"
1043 "\n"
1044 " git rebase --continue\n");
1046 #define ALLOW_EMPTY (1<<0)
1047 #define EDIT_MSG (1<<1)
1048 #define AMEND_MSG (1<<2)
1049 #define CLEANUP_MSG (1<<3)
1050 #define VERIFY_MSG (1<<4)
1051 #define CREATE_ROOT_COMMIT (1<<5)
1052 #define VERBATIM_MSG (1<<6)
1054 static int run_command_silent_on_success(struct child_process *cmd)
1056 struct strbuf buf = STRBUF_INIT;
1057 int rc;
1059 cmd->stdout_to_stderr = 1;
1060 rc = pipe_command(cmd,
1061 NULL, 0,
1062 NULL, 0,
1063 &buf, 0);
1065 if (rc)
1066 fputs(buf.buf, stderr);
1067 strbuf_release(&buf);
1068 return rc;
1072 * If we are cherry-pick, and if the merge did not result in
1073 * hand-editing, we will hit this commit and inherit the original
1074 * author date and name.
1076 * If we are revert, or if our cherry-pick results in a hand merge,
1077 * we had better say that the current user is responsible for that.
1079 * An exception is when run_git_commit() is called during an
1080 * interactive rebase: in that case, we will want to retain the
1081 * author metadata.
1083 static int run_git_commit(const char *defmsg,
1084 struct replay_opts *opts,
1085 unsigned int flags)
1087 struct child_process cmd = CHILD_PROCESS_INIT;
1089 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1090 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1092 cmd.git_cmd = 1;
1094 if (is_rebase_i(opts) &&
1095 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1096 !(!defmsg && (flags & AMEND_MSG))) &&
1097 read_env_script(&cmd.env)) {
1098 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1100 return error(_(staged_changes_advice),
1101 gpg_opt, gpg_opt);
1104 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1106 if (opts->committer_date_is_author_date)
1107 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1108 opts->ignore_date ?
1109 "" :
1110 author_date_from_env(&cmd.env));
1111 if (opts->ignore_date)
1112 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1114 strvec_push(&cmd.args, "commit");
1116 if (!(flags & VERIFY_MSG))
1117 strvec_push(&cmd.args, "-n");
1118 if ((flags & AMEND_MSG))
1119 strvec_push(&cmd.args, "--amend");
1120 if (opts->gpg_sign)
1121 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1122 else
1123 strvec_push(&cmd.args, "--no-gpg-sign");
1124 if (defmsg)
1125 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1126 else if (!(flags & EDIT_MSG))
1127 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1128 if ((flags & CLEANUP_MSG))
1129 strvec_push(&cmd.args, "--cleanup=strip");
1130 if ((flags & VERBATIM_MSG))
1131 strvec_push(&cmd.args, "--cleanup=verbatim");
1132 if ((flags & EDIT_MSG))
1133 strvec_push(&cmd.args, "-e");
1134 else if (!(flags & CLEANUP_MSG) &&
1135 !opts->signoff && !opts->record_origin &&
1136 !opts->explicit_cleanup)
1137 strvec_push(&cmd.args, "--cleanup=verbatim");
1139 if ((flags & ALLOW_EMPTY))
1140 strvec_push(&cmd.args, "--allow-empty");
1142 if (!(flags & EDIT_MSG))
1143 strvec_push(&cmd.args, "--allow-empty-message");
1145 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1146 return run_command_silent_on_success(&cmd);
1147 else
1148 return run_command(&cmd);
1151 static int rest_is_empty(const struct strbuf *sb, int start)
1153 int i, eol;
1154 const char *nl;
1156 /* Check if the rest is just whitespace and Signed-off-by's. */
1157 for (i = start; i < sb->len; i++) {
1158 nl = memchr(sb->buf + i, '\n', sb->len - i);
1159 if (nl)
1160 eol = nl - sb->buf;
1161 else
1162 eol = sb->len;
1164 if (strlen(sign_off_header) <= eol - i &&
1165 starts_with(sb->buf + i, sign_off_header)) {
1166 i = eol;
1167 continue;
1169 while (i < eol)
1170 if (!isspace(sb->buf[i++]))
1171 return 0;
1174 return 1;
1177 void cleanup_message(struct strbuf *msgbuf,
1178 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1180 if (verbose || /* Truncate the message just before the diff, if any. */
1181 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1182 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1183 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1184 strbuf_stripspace(msgbuf,
1185 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1189 * Find out if the message in the strbuf contains only whitespace and
1190 * Signed-off-by lines.
1192 int message_is_empty(const struct strbuf *sb,
1193 enum commit_msg_cleanup_mode cleanup_mode)
1195 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1196 return 0;
1197 return rest_is_empty(sb, 0);
1201 * See if the user edited the message in the editor or left what
1202 * was in the template intact
1204 int template_untouched(const struct strbuf *sb, const char *template_file,
1205 enum commit_msg_cleanup_mode cleanup_mode)
1207 struct strbuf tmpl = STRBUF_INIT;
1208 const char *start;
1210 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1211 return 0;
1213 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1214 return 0;
1216 strbuf_stripspace(&tmpl,
1217 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1218 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1219 start = sb->buf;
1220 strbuf_release(&tmpl);
1221 return rest_is_empty(sb, start - sb->buf);
1224 int update_head_with_reflog(const struct commit *old_head,
1225 const struct object_id *new_head,
1226 const char *action, const struct strbuf *msg,
1227 struct strbuf *err)
1229 struct ref_transaction *transaction;
1230 struct strbuf sb = STRBUF_INIT;
1231 const char *nl;
1232 int ret = 0;
1234 if (action) {
1235 strbuf_addstr(&sb, action);
1236 strbuf_addstr(&sb, ": ");
1239 nl = strchr(msg->buf, '\n');
1240 if (nl) {
1241 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1242 } else {
1243 strbuf_addbuf(&sb, msg);
1244 strbuf_addch(&sb, '\n');
1247 transaction = ref_transaction_begin(err);
1248 if (!transaction ||
1249 ref_transaction_update(transaction, "HEAD", new_head,
1250 old_head ? &old_head->object.oid : null_oid(),
1251 0, sb.buf, err) ||
1252 ref_transaction_commit(transaction, err)) {
1253 ret = -1;
1255 ref_transaction_free(transaction);
1256 strbuf_release(&sb);
1258 return ret;
1261 static int run_rewrite_hook(const struct object_id *oldoid,
1262 const struct object_id *newoid)
1264 struct child_process proc = CHILD_PROCESS_INIT;
1265 int code;
1266 struct strbuf sb = STRBUF_INIT;
1267 const char *hook_path = find_hook("post-rewrite");
1269 if (!hook_path)
1270 return 0;
1272 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1273 proc.in = -1;
1274 proc.stdout_to_stderr = 1;
1275 proc.trace2_hook_name = "post-rewrite";
1277 code = start_command(&proc);
1278 if (code)
1279 return code;
1280 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1281 sigchain_push(SIGPIPE, SIG_IGN);
1282 write_in_full(proc.in, sb.buf, sb.len);
1283 close(proc.in);
1284 strbuf_release(&sb);
1285 sigchain_pop(SIGPIPE);
1286 return finish_command(&proc);
1289 void commit_post_rewrite(struct repository *r,
1290 const struct commit *old_head,
1291 const struct object_id *new_head)
1293 struct notes_rewrite_cfg *cfg;
1295 cfg = init_copy_notes_for_rewrite("amend");
1296 if (cfg) {
1297 /* we are amending, so old_head is not NULL */
1298 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1299 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1301 run_rewrite_hook(&old_head->object.oid, new_head);
1304 static int run_prepare_commit_msg_hook(struct repository *r,
1305 struct strbuf *msg,
1306 const char *commit)
1308 int ret = 0;
1309 const char *name, *arg1 = NULL, *arg2 = NULL;
1311 name = git_path_commit_editmsg();
1312 if (write_message(msg->buf, msg->len, name, 0))
1313 return -1;
1315 if (commit) {
1316 arg1 = "commit";
1317 arg2 = commit;
1318 } else {
1319 arg1 = "message";
1321 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1322 arg1, arg2, NULL))
1323 ret = error(_("'prepare-commit-msg' hook failed"));
1325 return ret;
1328 static const char implicit_ident_advice_noconfig[] =
1329 N_("Your name and email address were configured automatically based\n"
1330 "on your username and hostname. Please check that they are accurate.\n"
1331 "You can suppress this message by setting them explicitly. Run the\n"
1332 "following command and follow the instructions in your editor to edit\n"
1333 "your configuration file:\n"
1334 "\n"
1335 " git config --global --edit\n"
1336 "\n"
1337 "After doing this, you may fix the identity used for this commit with:\n"
1338 "\n"
1339 " git commit --amend --reset-author\n");
1341 static const char implicit_ident_advice_config[] =
1342 N_("Your name and email address were configured automatically based\n"
1343 "on your username and hostname. Please check that they are accurate.\n"
1344 "You can suppress this message by setting them explicitly:\n"
1345 "\n"
1346 " git config --global user.name \"Your Name\"\n"
1347 " git config --global user.email you@example.com\n"
1348 "\n"
1349 "After doing this, you may fix the identity used for this commit with:\n"
1350 "\n"
1351 " git commit --amend --reset-author\n");
1353 static const char *implicit_ident_advice(void)
1355 char *user_config = interpolate_path("~/.gitconfig", 0);
1356 char *xdg_config = xdg_config_home("config");
1357 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1359 free(user_config);
1360 free(xdg_config);
1362 if (config_exists)
1363 return _(implicit_ident_advice_config);
1364 else
1365 return _(implicit_ident_advice_noconfig);
1369 void print_commit_summary(struct repository *r,
1370 const char *prefix,
1371 const struct object_id *oid,
1372 unsigned int flags)
1374 struct rev_info rev;
1375 struct commit *commit;
1376 struct strbuf format = STRBUF_INIT;
1377 const char *head;
1378 struct pretty_print_context pctx = {0};
1379 struct strbuf author_ident = STRBUF_INIT;
1380 struct strbuf committer_ident = STRBUF_INIT;
1381 struct ref_store *refs;
1383 commit = lookup_commit(r, oid);
1384 if (!commit)
1385 die(_("couldn't look up newly created commit"));
1386 if (repo_parse_commit(r, commit))
1387 die(_("could not parse newly created commit"));
1389 strbuf_addstr(&format, "format:%h] %s");
1391 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1392 &pctx);
1393 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1394 &pctx);
1395 if (strbuf_cmp(&author_ident, &committer_ident)) {
1396 strbuf_addstr(&format, "\n Author: ");
1397 strbuf_addbuf_percentquote(&format, &author_ident);
1399 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1400 struct strbuf date = STRBUF_INIT;
1402 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1403 strbuf_addstr(&format, "\n Date: ");
1404 strbuf_addbuf_percentquote(&format, &date);
1405 strbuf_release(&date);
1407 if (!committer_ident_sufficiently_given()) {
1408 strbuf_addstr(&format, "\n Committer: ");
1409 strbuf_addbuf_percentquote(&format, &committer_ident);
1410 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1411 strbuf_addch(&format, '\n');
1412 strbuf_addstr(&format, implicit_ident_advice());
1415 strbuf_release(&author_ident);
1416 strbuf_release(&committer_ident);
1418 repo_init_revisions(r, &rev, prefix);
1419 setup_revisions(0, NULL, &rev, NULL);
1421 rev.diff = 1;
1422 rev.diffopt.output_format =
1423 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1425 rev.verbose_header = 1;
1426 rev.show_root_diff = 1;
1427 get_commit_format(format.buf, &rev);
1428 rev.always_show_header = 0;
1429 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1430 diff_setup_done(&rev.diffopt);
1432 refs = get_main_ref_store(r);
1433 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1434 if (!head)
1435 die(_("unable to resolve HEAD after creating commit"));
1436 if (!strcmp(head, "HEAD"))
1437 head = _("detached HEAD");
1438 else
1439 skip_prefix(head, "refs/heads/", &head);
1440 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1441 _(" (root-commit)") : "");
1443 if (!log_tree_commit(&rev, commit)) {
1444 rev.always_show_header = 1;
1445 rev.use_terminator = 1;
1446 log_tree_commit(&rev, commit);
1449 release_revisions(&rev);
1450 strbuf_release(&format);
1453 static int parse_head(struct repository *r, struct commit **head)
1455 struct commit *current_head;
1456 struct object_id oid;
1458 if (repo_get_oid(r, "HEAD", &oid)) {
1459 current_head = NULL;
1460 } else {
1461 current_head = lookup_commit_reference(r, &oid);
1462 if (!current_head)
1463 return error(_("could not parse HEAD"));
1464 if (!oideq(&oid, &current_head->object.oid)) {
1465 warning(_("HEAD %s is not a commit!"),
1466 oid_to_hex(&oid));
1468 if (repo_parse_commit(r, current_head))
1469 return error(_("could not parse HEAD commit"));
1471 *head = current_head;
1473 return 0;
1477 * Try to commit without forking 'git commit'. In some cases we need
1478 * to run 'git commit' to display an error message
1480 * Returns:
1481 * -1 - error unable to commit
1482 * 0 - success
1483 * 1 - run 'git commit'
1485 static int try_to_commit(struct repository *r,
1486 struct strbuf *msg, const char *author,
1487 struct replay_opts *opts, unsigned int flags,
1488 struct object_id *oid)
1490 struct object_id tree;
1491 struct commit *current_head = NULL;
1492 struct commit_list *parents = NULL;
1493 struct commit_extra_header *extra = NULL;
1494 struct strbuf err = STRBUF_INIT;
1495 struct strbuf commit_msg = STRBUF_INIT;
1496 char *amend_author = NULL;
1497 const char *committer = NULL;
1498 const char *hook_commit = NULL;
1499 enum commit_msg_cleanup_mode cleanup;
1500 int res = 0;
1502 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1503 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1505 if (parse_head(r, &current_head))
1506 return -1;
1508 if (flags & AMEND_MSG) {
1509 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1510 const char *out_enc = get_commit_output_encoding();
1511 const char *message = repo_logmsg_reencode(r, current_head,
1512 NULL, out_enc);
1514 if (!msg) {
1515 const char *orig_message = NULL;
1517 find_commit_subject(message, &orig_message);
1518 msg = &commit_msg;
1519 strbuf_addstr(msg, orig_message);
1520 hook_commit = "HEAD";
1522 author = amend_author = get_author(message);
1523 repo_unuse_commit_buffer(r, current_head,
1524 message);
1525 if (!author) {
1526 res = error(_("unable to parse commit author"));
1527 goto out;
1529 parents = copy_commit_list(current_head->parents);
1530 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1531 } else if (current_head &&
1532 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1533 commit_list_insert(current_head, &parents);
1536 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1537 res = error(_("git write-tree failed to write a tree"));
1538 goto out;
1541 if (!(flags & ALLOW_EMPTY)) {
1542 struct commit *first_parent = current_head;
1544 if (flags & AMEND_MSG) {
1545 if (current_head->parents) {
1546 first_parent = current_head->parents->item;
1547 if (repo_parse_commit(r, first_parent)) {
1548 res = error(_("could not parse HEAD commit"));
1549 goto out;
1551 } else {
1552 first_parent = NULL;
1555 if (oideq(first_parent
1556 ? get_commit_tree_oid(first_parent)
1557 : the_hash_algo->empty_tree,
1558 &tree)) {
1559 res = 1; /* run 'git commit' to display error message */
1560 goto out;
1564 if (hook_exists("prepare-commit-msg")) {
1565 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1566 if (res)
1567 goto out;
1568 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1569 2048) < 0) {
1570 res = error_errno(_("unable to read commit message "
1571 "from '%s'"),
1572 git_path_commit_editmsg());
1573 goto out;
1575 msg = &commit_msg;
1578 if (flags & CLEANUP_MSG)
1579 cleanup = COMMIT_MSG_CLEANUP_ALL;
1580 else if (flags & VERBATIM_MSG)
1581 cleanup = COMMIT_MSG_CLEANUP_NONE;
1582 else if ((opts->signoff || opts->record_origin) &&
1583 !opts->explicit_cleanup)
1584 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1585 else
1586 cleanup = opts->default_msg_cleanup;
1588 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1589 strbuf_stripspace(msg,
1590 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1591 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1592 res = 1; /* run 'git commit' to display error message */
1593 goto out;
1596 if (opts->committer_date_is_author_date) {
1597 struct ident_split id;
1598 struct strbuf date = STRBUF_INIT;
1600 if (!opts->ignore_date) {
1601 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1602 res = error(_("invalid author identity '%s'"),
1603 author);
1604 goto out;
1606 if (!id.date_begin) {
1607 res = error(_(
1608 "corrupt author: missing date information"));
1609 goto out;
1611 strbuf_addf(&date, "@%.*s %.*s",
1612 (int)(id.date_end - id.date_begin),
1613 id.date_begin,
1614 (int)(id.tz_end - id.tz_begin),
1615 id.tz_begin);
1616 } else {
1617 reset_ident_date();
1619 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1620 getenv("GIT_COMMITTER_EMAIL"),
1621 WANT_COMMITTER_IDENT,
1622 opts->ignore_date ? NULL : date.buf,
1623 IDENT_STRICT);
1624 strbuf_release(&date);
1625 } else {
1626 reset_ident_date();
1629 if (opts->ignore_date) {
1630 struct ident_split id;
1631 char *name, *email;
1633 if (split_ident_line(&id, author, strlen(author)) < 0) {
1634 error(_("invalid author identity '%s'"), author);
1635 goto out;
1637 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1638 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1639 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1640 IDENT_STRICT);
1641 free(name);
1642 free(email);
1645 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1646 author, committer, opts->gpg_sign, extra)) {
1647 res = error(_("failed to write commit object"));
1648 goto out;
1651 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1652 msg, &err)) {
1653 res = error("%s", err.buf);
1654 goto out;
1657 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1658 if (flags & AMEND_MSG)
1659 commit_post_rewrite(r, current_head, oid);
1661 out:
1662 free_commit_extra_headers(extra);
1663 strbuf_release(&err);
1664 strbuf_release(&commit_msg);
1665 free(amend_author);
1667 return res;
1670 static int write_rebase_head(struct object_id *oid)
1672 if (update_ref("rebase", "REBASE_HEAD", oid,
1673 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1674 return error(_("could not update %s"), "REBASE_HEAD");
1676 return 0;
1679 static int do_commit(struct repository *r,
1680 const char *msg_file, const char *author,
1681 struct replay_opts *opts, unsigned int flags,
1682 struct object_id *oid)
1684 int res = 1;
1686 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1687 struct object_id oid;
1688 struct strbuf sb = STRBUF_INIT;
1690 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1691 return error_errno(_("unable to read commit message "
1692 "from '%s'"),
1693 msg_file);
1695 res = try_to_commit(r, msg_file ? &sb : NULL,
1696 author, opts, flags, &oid);
1697 strbuf_release(&sb);
1698 if (!res) {
1699 refs_delete_ref(get_main_ref_store(r), "",
1700 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1701 unlink(git_path_merge_msg(r));
1702 if (!is_rebase_i(opts))
1703 print_commit_summary(r, NULL, &oid,
1704 SUMMARY_SHOW_AUTHOR_DATE);
1705 return res;
1708 if (res == 1) {
1709 if (is_rebase_i(opts) && oid)
1710 if (write_rebase_head(oid))
1711 return -1;
1712 return run_git_commit(msg_file, opts, flags);
1715 return res;
1718 static int is_original_commit_empty(struct commit *commit)
1720 const struct object_id *ptree_oid;
1722 if (repo_parse_commit(the_repository, commit))
1723 return error(_("could not parse commit %s"),
1724 oid_to_hex(&commit->object.oid));
1725 if (commit->parents) {
1726 struct commit *parent = commit->parents->item;
1727 if (repo_parse_commit(the_repository, parent))
1728 return error(_("could not parse parent commit %s"),
1729 oid_to_hex(&parent->object.oid));
1730 ptree_oid = get_commit_tree_oid(parent);
1731 } else {
1732 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1735 return oideq(ptree_oid, get_commit_tree_oid(commit));
1739 * Should empty commits be allowed? Return status:
1740 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1741 * 0: Halt on empty commit
1742 * 1: Allow empty commit
1743 * 2: Drop empty commit
1745 static int allow_empty(struct repository *r,
1746 struct replay_opts *opts,
1747 struct commit *commit)
1749 int index_unchanged, originally_empty;
1752 * For a commit that is initially empty, allow_empty determines if it
1753 * should be kept or not
1755 * For a commit that becomes empty, keep_redundant_commits and
1756 * drop_redundant_commits determine whether the commit should be kept or
1757 * dropped. If neither is specified, halt.
1759 index_unchanged = is_index_unchanged(r);
1760 if (index_unchanged < 0)
1761 return index_unchanged;
1762 if (!index_unchanged)
1763 return 0; /* we do not have to say --allow-empty */
1765 originally_empty = is_original_commit_empty(commit);
1766 if (originally_empty < 0)
1767 return originally_empty;
1768 if (originally_empty)
1769 return opts->allow_empty;
1770 else if (opts->keep_redundant_commits)
1771 return 1;
1772 else if (opts->drop_redundant_commits)
1773 return 2;
1774 else
1775 return 0;
1778 static struct {
1779 char c;
1780 const char *str;
1781 } todo_command_info[] = {
1782 [TODO_PICK] = { 'p', "pick" },
1783 [TODO_REVERT] = { 0, "revert" },
1784 [TODO_EDIT] = { 'e', "edit" },
1785 [TODO_REWORD] = { 'r', "reword" },
1786 [TODO_FIXUP] = { 'f', "fixup" },
1787 [TODO_SQUASH] = { 's', "squash" },
1788 [TODO_EXEC] = { 'x', "exec" },
1789 [TODO_BREAK] = { 'b', "break" },
1790 [TODO_LABEL] = { 'l', "label" },
1791 [TODO_RESET] = { 't', "reset" },
1792 [TODO_MERGE] = { 'm', "merge" },
1793 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1794 [TODO_NOOP] = { 0, "noop" },
1795 [TODO_DROP] = { 'd', "drop" },
1796 [TODO_COMMENT] = { 0, NULL },
1799 static const char *command_to_string(const enum todo_command command)
1801 if (command < TODO_COMMENT)
1802 return todo_command_info[command].str;
1803 if (command == TODO_COMMENT)
1804 return comment_line_str;
1805 die(_("unknown command: %d"), command);
1808 static char command_to_char(const enum todo_command command)
1810 if (command < TODO_COMMENT)
1811 return todo_command_info[command].c;
1812 return 0;
1815 static int is_noop(const enum todo_command command)
1817 return TODO_NOOP <= command;
1820 static int is_fixup(enum todo_command command)
1822 return command == TODO_FIXUP || command == TODO_SQUASH;
1825 /* Does this command create a (non-merge) commit? */
1826 static int is_pick_or_similar(enum todo_command command)
1828 switch (command) {
1829 case TODO_PICK:
1830 case TODO_REVERT:
1831 case TODO_EDIT:
1832 case TODO_REWORD:
1833 case TODO_FIXUP:
1834 case TODO_SQUASH:
1835 return 1;
1836 default:
1837 return 0;
1841 enum todo_item_flags {
1842 TODO_EDIT_MERGE_MSG = (1 << 0),
1843 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1844 TODO_EDIT_FIXUP_MSG = (1 << 2),
1847 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1848 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1849 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1850 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1851 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1853 static int is_fixup_flag(enum todo_command command, unsigned flag)
1855 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1856 (flag & TODO_EDIT_FIXUP_MSG));
1860 * Wrapper around strbuf_add_commented_lines() which avoids double
1861 * commenting commit subjects.
1863 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1865 const char *s = str;
1866 while (starts_with_mem(s, len, comment_line_str)) {
1867 size_t count;
1868 const char *n = memchr(s, '\n', len);
1869 if (!n)
1870 count = len;
1871 else
1872 count = n - s + 1;
1873 strbuf_add(buf, s, count);
1874 s += count;
1875 len -= count;
1877 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1880 /* Does the current fixup chain contain a squash command? */
1881 static int seen_squash(struct replay_opts *opts)
1883 return starts_with(opts->current_fixups.buf, "squash") ||
1884 strstr(opts->current_fixups.buf, "\nsquash");
1887 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1889 strbuf_setlen(buf1, 2);
1890 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1891 strbuf_addch(buf1, '\n');
1892 strbuf_setlen(buf2, 2);
1893 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1894 strbuf_addch(buf2, '\n');
1898 * Comment out any un-commented commit messages, updating the message comments
1899 * to say they will be skipped but do not comment out the empty lines that
1900 * surround commit messages and their comments.
1902 static void update_squash_message_for_fixup(struct strbuf *msg)
1904 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1905 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1906 const char *s, *start;
1907 char *orig_msg;
1908 size_t orig_msg_len;
1909 int i = 1;
1911 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1912 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1913 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1914 while (s) {
1915 const char *next;
1916 size_t off;
1917 if (skip_prefix(s, buf1.buf, &next)) {
1919 * Copy the last message, preserving the blank line
1920 * preceding the current line
1922 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1923 copy_lines(msg, start, s - start - off);
1924 if (off)
1925 strbuf_addch(msg, '\n');
1927 * The next message needs to be commented out but the
1928 * message header is already commented out so just copy
1929 * it and the blank line that follows it.
1931 strbuf_addbuf(msg, &buf2);
1932 if (*next == '\n')
1933 strbuf_addch(msg, *next++);
1934 start = s = next;
1935 copy_lines = add_commented_lines;
1936 update_comment_bufs(&buf1, &buf2, ++i);
1937 } else if (skip_prefix(s, buf2.buf, &next)) {
1938 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1939 copy_lines(msg, start, s - start - off);
1940 start = s - off;
1941 s = next;
1942 copy_lines = strbuf_add;
1943 update_comment_bufs(&buf1, &buf2, ++i);
1944 } else {
1945 s = strchr(s, '\n');
1946 if (s)
1947 s++;
1950 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1951 free(orig_msg);
1952 strbuf_release(&buf1);
1953 strbuf_release(&buf2);
1956 static int append_squash_message(struct strbuf *buf, const char *body,
1957 enum todo_command command, struct replay_opts *opts,
1958 unsigned flag)
1960 const char *fixup_msg;
1961 size_t commented_len = 0, fixup_off;
1963 * amend is non-interactive and not normally used with fixup!
1964 * or squash! commits, so only comment out those subjects when
1965 * squashing commit messages.
1967 if (starts_with(body, "amend!") ||
1968 ((command == TODO_SQUASH || seen_squash(opts)) &&
1969 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1970 commented_len = commit_subject_length(body);
1972 strbuf_addf(buf, "\n%s ", comment_line_str);
1973 strbuf_addf(buf, _(nth_commit_msg_fmt),
1974 ++opts->current_fixup_count + 1);
1975 strbuf_addstr(buf, "\n\n");
1976 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
1977 /* buf->buf may be reallocated so store an offset into the buffer */
1978 fixup_off = buf->len;
1979 strbuf_addstr(buf, body + commented_len);
1981 /* fixup -C after squash behaves like squash */
1982 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1984 * We're replacing the commit message so we need to
1985 * append the Signed-off-by: trailer if the user
1986 * requested '--signoff'.
1988 if (opts->signoff)
1989 append_signoff(buf, 0, 0);
1991 if ((command == TODO_FIXUP) &&
1992 (flag & TODO_REPLACE_FIXUP_MSG) &&
1993 (file_exists(rebase_path_fixup_msg()) ||
1994 !file_exists(rebase_path_squash_msg()))) {
1995 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1996 if (write_message(fixup_msg, strlen(fixup_msg),
1997 rebase_path_fixup_msg(), 0) < 0)
1998 return error(_("cannot write '%s'"),
1999 rebase_path_fixup_msg());
2000 } else {
2001 unlink(rebase_path_fixup_msg());
2003 } else {
2004 unlink(rebase_path_fixup_msg());
2007 return 0;
2010 static int update_squash_messages(struct repository *r,
2011 enum todo_command command,
2012 struct commit *commit,
2013 struct replay_opts *opts,
2014 unsigned flag)
2016 struct strbuf buf = STRBUF_INIT;
2017 int res = 0;
2018 const char *message, *body;
2019 const char *encoding = get_commit_output_encoding();
2021 if (opts->current_fixup_count > 0) {
2022 struct strbuf header = STRBUF_INIT;
2023 char *eol;
2025 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2026 return error(_("could not read '%s'"),
2027 rebase_path_squash_msg());
2029 eol = !starts_with(buf.buf, comment_line_str) ?
2030 buf.buf : strchrnul(buf.buf, '\n');
2032 strbuf_addf(&header, "%s ", comment_line_str);
2033 strbuf_addf(&header, _(combined_commit_msg_fmt),
2034 opts->current_fixup_count + 2);
2035 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2036 strbuf_release(&header);
2037 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2038 update_squash_message_for_fixup(&buf);
2039 } else {
2040 struct object_id head;
2041 struct commit *head_commit;
2042 const char *head_message, *body;
2044 if (repo_get_oid(r, "HEAD", &head))
2045 return error(_("need a HEAD to fixup"));
2046 if (!(head_commit = lookup_commit_reference(r, &head)))
2047 return error(_("could not read HEAD"));
2048 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2049 encoding)))
2050 return error(_("could not read HEAD's commit message"));
2052 find_commit_subject(head_message, &body);
2053 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2054 rebase_path_fixup_msg(), 0) < 0) {
2055 repo_unuse_commit_buffer(r, head_commit, head_message);
2056 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2058 strbuf_addf(&buf, "%s ", comment_line_str);
2059 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2060 strbuf_addf(&buf, "\n%s ", comment_line_str);
2061 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2062 _(skip_first_commit_msg_str) :
2063 _(first_commit_msg_str));
2064 strbuf_addstr(&buf, "\n\n");
2065 if (is_fixup_flag(command, flag))
2066 strbuf_add_commented_lines(&buf, body, strlen(body),
2067 comment_line_str);
2068 else
2069 strbuf_addstr(&buf, body);
2071 repo_unuse_commit_buffer(r, head_commit, head_message);
2074 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2075 return error(_("could not read commit message of %s"),
2076 oid_to_hex(&commit->object.oid));
2077 find_commit_subject(message, &body);
2079 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2080 res = append_squash_message(&buf, body, command, opts, flag);
2081 } else if (command == TODO_FIXUP) {
2082 strbuf_addf(&buf, "\n%s ", comment_line_str);
2083 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2084 ++opts->current_fixup_count + 1);
2085 strbuf_addstr(&buf, "\n\n");
2086 strbuf_add_commented_lines(&buf, body, strlen(body),
2087 comment_line_str);
2088 } else
2089 return error(_("unknown command: %d"), command);
2090 repo_unuse_commit_buffer(r, commit, message);
2092 if (!res)
2093 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2095 strbuf_release(&buf);
2097 if (!res) {
2098 strbuf_addf(&opts->current_fixups, "%s%s %s",
2099 opts->current_fixups.len ? "\n" : "",
2100 command_to_string(command),
2101 oid_to_hex(&commit->object.oid));
2102 res = write_message(opts->current_fixups.buf,
2103 opts->current_fixups.len,
2104 rebase_path_current_fixups(), 0);
2107 return res;
2110 static void flush_rewritten_pending(void)
2112 struct strbuf buf = STRBUF_INIT;
2113 struct object_id newoid;
2114 FILE *out;
2116 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2117 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2118 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2119 char *bol = buf.buf, *eol;
2121 while (*bol) {
2122 eol = strchrnul(bol, '\n');
2123 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2124 bol, oid_to_hex(&newoid));
2125 if (!*eol)
2126 break;
2127 bol = eol + 1;
2129 fclose(out);
2130 unlink(rebase_path_rewritten_pending());
2132 strbuf_release(&buf);
2135 static void record_in_rewritten(struct object_id *oid,
2136 enum todo_command next_command)
2138 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2140 if (!out)
2141 return;
2143 fprintf(out, "%s\n", oid_to_hex(oid));
2144 fclose(out);
2146 if (!is_fixup(next_command))
2147 flush_rewritten_pending();
2150 static int should_edit(struct replay_opts *opts) {
2151 if (opts->edit < 0)
2153 * Note that we only handle the case of non-conflicted
2154 * commits; continue_single_pick() handles the conflicted
2155 * commits itself instead of calling this function.
2157 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2158 return opts->edit;
2161 static void refer_to_commit(struct replay_opts *opts,
2162 struct strbuf *msgbuf, struct commit *commit)
2164 if (opts->commit_use_reference) {
2165 struct pretty_print_context ctx = {
2166 .abbrev = DEFAULT_ABBREV,
2167 .date_mode.type = DATE_SHORT,
2169 repo_format_commit_message(the_repository, commit,
2170 "%h (%s, %ad)", msgbuf, &ctx);
2171 } else {
2172 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2176 static int do_pick_commit(struct repository *r,
2177 struct todo_item *item,
2178 struct replay_opts *opts,
2179 int final_fixup, int *check_todo)
2181 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2182 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2183 struct object_id head;
2184 struct commit *base, *next, *parent;
2185 const char *base_label, *next_label;
2186 char *author = NULL;
2187 struct commit_message msg = { NULL, NULL, NULL, NULL };
2188 struct strbuf msgbuf = STRBUF_INIT;
2189 int res, unborn = 0, reword = 0, allow, drop_commit;
2190 enum todo_command command = item->command;
2191 struct commit *commit = item->commit;
2193 if (opts->no_commit) {
2195 * We do not intend to commit immediately. We just want to
2196 * merge the differences in, so let's compute the tree
2197 * that represents the "current" state for the merge machinery
2198 * to work on.
2200 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2201 return error(_("your index file is unmerged."));
2202 } else {
2203 unborn = repo_get_oid(r, "HEAD", &head);
2204 /* Do we want to generate a root commit? */
2205 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2206 oideq(&head, &opts->squash_onto)) {
2207 if (is_fixup(command))
2208 return error(_("cannot fixup root commit"));
2209 flags |= CREATE_ROOT_COMMIT;
2210 unborn = 1;
2211 } else if (unborn)
2212 oidcpy(&head, the_hash_algo->empty_tree);
2213 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2214 NULL, 0))
2215 return error_dirty_index(r, opts);
2217 discard_index(r->index);
2219 if (!commit->parents)
2220 parent = NULL;
2221 else if (commit->parents->next) {
2222 /* Reverting or cherry-picking a merge commit */
2223 int cnt;
2224 struct commit_list *p;
2226 if (!opts->mainline)
2227 return error(_("commit %s is a merge but no -m option was given."),
2228 oid_to_hex(&commit->object.oid));
2230 for (cnt = 1, p = commit->parents;
2231 cnt != opts->mainline && p;
2232 cnt++)
2233 p = p->next;
2234 if (cnt != opts->mainline || !p)
2235 return error(_("commit %s does not have parent %d"),
2236 oid_to_hex(&commit->object.oid), opts->mainline);
2237 parent = p->item;
2238 } else if (1 < opts->mainline)
2240 * Non-first parent explicitly specified as mainline for
2241 * non-merge commit
2243 return error(_("commit %s does not have parent %d"),
2244 oid_to_hex(&commit->object.oid), opts->mainline);
2245 else
2246 parent = commit->parents->item;
2248 if (get_message(commit, &msg) != 0)
2249 return error(_("cannot get commit message for %s"),
2250 oid_to_hex(&commit->object.oid));
2252 if (opts->allow_ff && !is_fixup(command) &&
2253 ((parent && oideq(&parent->object.oid, &head)) ||
2254 (!parent && unborn))) {
2255 if (is_rebase_i(opts))
2256 write_author_script(msg.message);
2257 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2258 opts);
2259 if (res || command != TODO_REWORD)
2260 goto leave;
2261 reword = 1;
2262 msg_file = NULL;
2263 goto fast_forward_edit;
2265 if (parent && repo_parse_commit(r, parent) < 0)
2266 /* TRANSLATORS: The first %s will be a "todo" command like
2267 "revert" or "pick", the second %s a SHA1. */
2268 return error(_("%s: cannot parse parent commit %s"),
2269 command_to_string(command),
2270 oid_to_hex(&parent->object.oid));
2273 * "commit" is an existing commit. We would want to apply
2274 * the difference it introduces since its first parent "prev"
2275 * on top of the current HEAD if we are cherry-pick. Or the
2276 * reverse of it if we are revert.
2279 if (command == TODO_REVERT) {
2280 const char *orig_subject;
2282 base = commit;
2283 base_label = msg.label;
2284 next = parent;
2285 next_label = msg.parent_label;
2286 if (opts->commit_use_reference) {
2287 strbuf_addstr(&msgbuf,
2288 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2289 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2291 * We don't touch pre-existing repeated reverts, because
2292 * theoretically these can be nested arbitrarily deeply,
2293 * thus requiring excessive complexity to deal with.
2295 !starts_with(orig_subject, "Revert \"")) {
2296 strbuf_addstr(&msgbuf, "Reapply \"");
2297 strbuf_addstr(&msgbuf, orig_subject);
2298 } else {
2299 strbuf_addstr(&msgbuf, "Revert \"");
2300 strbuf_addstr(&msgbuf, msg.subject);
2301 strbuf_addstr(&msgbuf, "\"");
2303 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2304 refer_to_commit(opts, &msgbuf, commit);
2306 if (commit->parents && commit->parents->next) {
2307 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2308 refer_to_commit(opts, &msgbuf, parent);
2310 strbuf_addstr(&msgbuf, ".\n");
2311 } else {
2312 const char *p;
2314 base = parent;
2315 base_label = msg.parent_label;
2316 next = commit;
2317 next_label = msg.label;
2319 /* Append the commit log message to msgbuf. */
2320 if (find_commit_subject(msg.message, &p))
2321 strbuf_addstr(&msgbuf, p);
2323 if (opts->record_origin) {
2324 strbuf_complete_line(&msgbuf);
2325 if (!has_conforming_footer(&msgbuf, NULL, 0))
2326 strbuf_addch(&msgbuf, '\n');
2327 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2328 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2329 strbuf_addstr(&msgbuf, ")\n");
2331 if (!is_fixup(command))
2332 author = get_author(msg.message);
2335 if (command == TODO_REWORD)
2336 reword = 1;
2337 else if (is_fixup(command)) {
2338 if (update_squash_messages(r, command, commit,
2339 opts, item->flags)) {
2340 res = -1;
2341 goto leave;
2343 flags |= AMEND_MSG;
2344 if (!final_fixup)
2345 msg_file = rebase_path_squash_msg();
2346 else if (file_exists(rebase_path_fixup_msg())) {
2347 flags |= VERBATIM_MSG;
2348 msg_file = rebase_path_fixup_msg();
2349 } else {
2350 const char *dest = git_path_squash_msg(r);
2351 unlink(dest);
2352 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2353 res = error(_("could not copy '%s' to '%s'"),
2354 rebase_path_squash_msg(), dest);
2355 goto leave;
2357 unlink(git_path_merge_msg(r));
2358 msg_file = dest;
2359 flags |= EDIT_MSG;
2363 if (opts->signoff && !is_fixup(command))
2364 append_signoff(&msgbuf, 0, 0);
2366 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2367 res = -1;
2368 else if (!opts->strategy ||
2369 !strcmp(opts->strategy, "recursive") ||
2370 !strcmp(opts->strategy, "ort") ||
2371 command == TODO_REVERT) {
2372 res = do_recursive_merge(r, base, next, base_label, next_label,
2373 &head, &msgbuf, opts);
2374 if (res < 0)
2375 goto leave;
2377 res |= write_message(msgbuf.buf, msgbuf.len,
2378 git_path_merge_msg(r), 0);
2379 } else {
2380 struct commit_list *common = NULL;
2381 struct commit_list *remotes = NULL;
2383 res = write_message(msgbuf.buf, msgbuf.len,
2384 git_path_merge_msg(r), 0);
2386 commit_list_insert(base, &common);
2387 commit_list_insert(next, &remotes);
2388 res |= try_merge_command(r, opts->strategy,
2389 opts->xopts.nr, opts->xopts.v,
2390 common, oid_to_hex(&head), remotes);
2391 free_commit_list(common);
2392 free_commit_list(remotes);
2396 * If the merge was clean or if it failed due to conflict, we write
2397 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2398 * However, if the merge did not even start, then we don't want to
2399 * write it at all.
2401 if ((command == TODO_PICK || command == TODO_REWORD ||
2402 command == TODO_EDIT) && !opts->no_commit &&
2403 (res == 0 || res == 1) &&
2404 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2405 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2406 res = -1;
2407 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2408 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2409 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2410 res = -1;
2412 if (res) {
2413 error(command == TODO_REVERT
2414 ? _("could not revert %s... %s")
2415 : _("could not apply %s... %s"),
2416 short_commit_name(r, commit), msg.subject);
2417 print_advice(r, res == 1, opts);
2418 repo_rerere(r, opts->allow_rerere_auto);
2419 goto leave;
2422 drop_commit = 0;
2423 allow = allow_empty(r, opts, commit);
2424 if (allow < 0) {
2425 res = allow;
2426 goto leave;
2427 } else if (allow == 1) {
2428 flags |= ALLOW_EMPTY;
2429 } else if (allow == 2) {
2430 drop_commit = 1;
2431 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2432 NULL, REF_NO_DEREF);
2433 unlink(git_path_merge_msg(r));
2434 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2435 NULL, REF_NO_DEREF);
2436 fprintf(stderr,
2437 _("dropping %s %s -- patch contents already upstream\n"),
2438 oid_to_hex(&commit->object.oid), msg.subject);
2439 } /* else allow == 0 and there's nothing special to do */
2440 if (!opts->no_commit && !drop_commit) {
2441 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2442 res = do_commit(r, msg_file, author, opts, flags,
2443 commit? &commit->object.oid : NULL);
2444 else
2445 res = error(_("unable to parse commit author"));
2446 *check_todo = !!(flags & EDIT_MSG);
2447 if (!res && reword) {
2448 fast_forward_edit:
2449 res = run_git_commit(NULL, opts, EDIT_MSG |
2450 VERIFY_MSG | AMEND_MSG |
2451 (flags & ALLOW_EMPTY));
2452 *check_todo = 1;
2457 if (!res && final_fixup) {
2458 unlink(rebase_path_fixup_msg());
2459 unlink(rebase_path_squash_msg());
2460 unlink(rebase_path_current_fixups());
2461 strbuf_reset(&opts->current_fixups);
2462 opts->current_fixup_count = 0;
2465 leave:
2466 free_message(commit, &msg);
2467 free(author);
2468 strbuf_release(&msgbuf);
2469 update_abort_safety_file();
2471 return res;
2474 static int prepare_revs(struct replay_opts *opts)
2477 * picking (but not reverting) ranges (but not individual revisions)
2478 * should be done in reverse
2480 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2481 opts->revs->reverse ^= 1;
2483 if (prepare_revision_walk(opts->revs))
2484 return error(_("revision walk setup failed"));
2486 return 0;
2489 static int read_and_refresh_cache(struct repository *r,
2490 struct replay_opts *opts)
2492 struct lock_file index_lock = LOCK_INIT;
2493 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2494 if (repo_read_index(r) < 0) {
2495 rollback_lock_file(&index_lock);
2496 return error(_("git %s: failed to read the index"),
2497 action_name(opts));
2499 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2501 if (index_fd >= 0) {
2502 if (write_locked_index(r->index, &index_lock,
2503 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2504 return error(_("git %s: failed to refresh the index"),
2505 action_name(opts));
2510 * If we are resolving merges in any way other than "ort", then
2511 * expand the sparse index.
2513 if (opts->strategy && strcmp(opts->strategy, "ort"))
2514 ensure_full_index(r->index);
2515 return 0;
2518 void todo_list_release(struct todo_list *todo_list)
2520 strbuf_release(&todo_list->buf);
2521 FREE_AND_NULL(todo_list->items);
2522 todo_list->nr = todo_list->alloc = 0;
2525 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2527 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2528 return todo_list->items + todo_list->nr++;
2531 const char *todo_item_get_arg(struct todo_list *todo_list,
2532 struct todo_item *item)
2534 return todo_list->buf.buf + item->arg_offset;
2537 static int is_command(enum todo_command command, const char **bol)
2539 const char *str = todo_command_info[command].str;
2540 const char nick = todo_command_info[command].c;
2541 const char *p = *bol;
2543 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2544 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2545 (*bol = p);
2548 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2550 switch (command) {
2551 case TODO_LABEL:
2553 * '#' is not a valid label as the merge command uses it to
2554 * separate merge parents from the commit subject.
2556 if (!strcmp(arg, "#") ||
2557 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2558 return error(_("'%s' is not a valid label"), arg);
2559 break;
2561 case TODO_UPDATE_REF:
2562 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2563 return error(_("'%s' is not a valid refname"), arg);
2564 if (check_refname_format(arg, 0))
2565 return error(_("update-ref requires a fully qualified "
2566 "refname e.g. refs/heads/%s"), arg);
2567 break;
2569 default:
2570 BUG("unexpected todo_command");
2573 return 0;
2576 static int parse_insn_line(struct repository *r, struct todo_item *item,
2577 const char *buf, const char *bol, char *eol)
2579 struct object_id commit_oid;
2580 char *end_of_object_name;
2581 int i, saved, status, padding;
2583 item->flags = 0;
2585 /* left-trim */
2586 bol += strspn(bol, " \t");
2588 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2589 item->command = TODO_COMMENT;
2590 item->commit = NULL;
2591 item->arg_offset = bol - buf;
2592 item->arg_len = eol - bol;
2593 return 0;
2596 for (i = 0; i < TODO_COMMENT; i++)
2597 if (is_command(i, &bol)) {
2598 item->command = i;
2599 break;
2601 if (i >= TODO_COMMENT)
2602 return error(_("invalid command '%.*s'"),
2603 (int)strcspn(bol, " \t\r\n"), bol);
2605 /* Eat up extra spaces/ tabs before object name */
2606 padding = strspn(bol, " \t");
2607 bol += padding;
2609 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2610 if (bol != eol)
2611 return error(_("%s does not accept arguments: '%s'"),
2612 command_to_string(item->command), bol);
2613 item->commit = NULL;
2614 item->arg_offset = bol - buf;
2615 item->arg_len = eol - bol;
2616 return 0;
2619 if (!padding)
2620 return error(_("missing arguments for %s"),
2621 command_to_string(item->command));
2623 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2624 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2625 int ret = 0;
2627 item->commit = NULL;
2628 item->arg_offset = bol - buf;
2629 item->arg_len = (int)(eol - bol);
2630 if (item->command == TODO_LABEL ||
2631 item->command == TODO_UPDATE_REF) {
2632 saved = *eol;
2633 *eol = '\0';
2634 ret = check_label_or_ref_arg(item->command, bol);
2635 *eol = saved;
2637 return ret;
2640 if (item->command == TODO_FIXUP) {
2641 if (skip_prefix(bol, "-C", &bol)) {
2642 bol += strspn(bol, " \t");
2643 item->flags |= TODO_REPLACE_FIXUP_MSG;
2644 } else if (skip_prefix(bol, "-c", &bol)) {
2645 bol += strspn(bol, " \t");
2646 item->flags |= TODO_EDIT_FIXUP_MSG;
2650 if (item->command == TODO_MERGE) {
2651 if (skip_prefix(bol, "-C", &bol))
2652 bol += strspn(bol, " \t");
2653 else if (skip_prefix(bol, "-c", &bol)) {
2654 bol += strspn(bol, " \t");
2655 item->flags |= TODO_EDIT_MERGE_MSG;
2656 } else {
2657 item->flags |= TODO_EDIT_MERGE_MSG;
2658 item->commit = NULL;
2659 item->arg_offset = bol - buf;
2660 item->arg_len = (int)(eol - bol);
2661 return 0;
2665 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2666 saved = *end_of_object_name;
2667 *end_of_object_name = '\0';
2668 status = repo_get_oid(r, bol, &commit_oid);
2669 if (status < 0)
2670 error(_("could not parse '%s'"), bol); /* return later */
2671 *end_of_object_name = saved;
2673 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2674 item->arg_offset = bol - buf;
2675 item->arg_len = (int)(eol - bol);
2677 if (status < 0)
2678 return status;
2680 item->commit = lookup_commit_reference(r, &commit_oid);
2681 return item->commit ? 0 : -1;
2684 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2686 const char *todo_file, *bol;
2687 struct strbuf buf = STRBUF_INIT;
2688 int ret = 0;
2690 todo_file = git_path_todo_file();
2691 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2692 if (errno == ENOENT || errno == ENOTDIR)
2693 return -1;
2694 else
2695 return error_errno("unable to open '%s'", todo_file);
2697 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2698 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2699 *action = REPLAY_PICK;
2700 else if (is_command(TODO_REVERT, &bol) &&
2701 (*bol == ' ' || *bol == '\t'))
2702 *action = REPLAY_REVERT;
2703 else
2704 ret = -1;
2706 strbuf_release(&buf);
2708 return ret;
2711 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2712 struct todo_list *todo_list)
2714 struct todo_item *item;
2715 char *p = buf, *next_p;
2716 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2718 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2720 for (i = 1; *p; i++, p = next_p) {
2721 char *eol = strchrnul(p, '\n');
2723 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2725 if (p != eol && eol[-1] == '\r')
2726 eol--; /* strip Carriage Return */
2728 item = append_new_todo(todo_list);
2729 item->offset_in_buf = p - todo_list->buf.buf;
2730 if (parse_insn_line(r, item, buf, p, eol)) {
2731 res = error(_("invalid line %d: %.*s"),
2732 i, (int)(eol - p), p);
2733 item->command = TODO_COMMENT + 1;
2734 item->arg_offset = p - buf;
2735 item->arg_len = (int)(eol - p);
2736 item->commit = NULL;
2739 if (item->command != TODO_COMMENT)
2740 todo_list->total_nr++;
2742 if (fixup_okay)
2743 ; /* do nothing */
2744 else if (is_fixup(item->command))
2745 res = error(_("cannot '%s' without a previous commit"),
2746 command_to_string(item->command));
2747 else if (!is_noop(item->command))
2748 fixup_okay = 1;
2751 return res;
2754 static int count_commands(struct todo_list *todo_list)
2756 int count = 0, i;
2758 for (i = 0; i < todo_list->nr; i++)
2759 if (todo_list->items[i].command != TODO_COMMENT)
2760 count++;
2762 return count;
2765 static int get_item_line_offset(struct todo_list *todo_list, int index)
2767 return index < todo_list->nr ?
2768 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2771 static const char *get_item_line(struct todo_list *todo_list, int index)
2773 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2776 static int get_item_line_length(struct todo_list *todo_list, int index)
2778 return get_item_line_offset(todo_list, index + 1)
2779 - get_item_line_offset(todo_list, index);
2782 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2784 int fd;
2785 ssize_t len;
2787 fd = open(path, O_RDONLY);
2788 if (fd < 0)
2789 return error_errno(_("could not open '%s'"), path);
2790 len = strbuf_read(sb, fd, 0);
2791 close(fd);
2792 if (len < 0)
2793 return error(_("could not read '%s'."), path);
2794 return len;
2797 static int have_finished_the_last_pick(void)
2799 struct strbuf buf = STRBUF_INIT;
2800 const char *eol;
2801 const char *todo_path = git_path_todo_file();
2802 int ret = 0;
2804 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2805 if (errno == ENOENT) {
2806 return 0;
2807 } else {
2808 error_errno("unable to open '%s'", todo_path);
2809 return 0;
2812 /* If there is only one line then we are done */
2813 eol = strchr(buf.buf, '\n');
2814 if (!eol || !eol[1])
2815 ret = 1;
2817 strbuf_release(&buf);
2819 return ret;
2822 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2824 struct replay_opts opts = REPLAY_OPTS_INIT;
2825 int need_cleanup = 0;
2827 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2828 if (!refs_delete_ref(get_main_ref_store(r), "",
2829 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2830 verbose)
2831 warning(_("cancelling a cherry picking in progress"));
2832 opts.action = REPLAY_PICK;
2833 need_cleanup = 1;
2836 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2837 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2838 NULL, REF_NO_DEREF) &&
2839 verbose)
2840 warning(_("cancelling a revert in progress"));
2841 opts.action = REPLAY_REVERT;
2842 need_cleanup = 1;
2845 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2846 NULL, REF_NO_DEREF);
2848 if (!need_cleanup)
2849 return;
2851 if (!have_finished_the_last_pick())
2852 return;
2854 sequencer_remove_state(&opts);
2857 static void todo_list_write_total_nr(struct todo_list *todo_list)
2859 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2861 if (f) {
2862 fprintf(f, "%d\n", todo_list->total_nr);
2863 fclose(f);
2867 static int read_populate_todo(struct repository *r,
2868 struct todo_list *todo_list,
2869 struct replay_opts *opts)
2871 const char *todo_file = get_todo_path(opts);
2872 int res;
2874 strbuf_reset(&todo_list->buf);
2875 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2876 return -1;
2878 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2879 if (res) {
2880 if (is_rebase_i(opts))
2881 return error(_("please fix this using "
2882 "'git rebase --edit-todo'."));
2883 return error(_("unusable instruction sheet: '%s'"), todo_file);
2886 if (!todo_list->nr &&
2887 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2888 return error(_("no commits parsed."));
2890 if (!is_rebase_i(opts)) {
2891 enum todo_command valid =
2892 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2893 int i;
2895 for (i = 0; i < todo_list->nr; i++)
2896 if (valid == todo_list->items[i].command)
2897 continue;
2898 else if (valid == TODO_PICK)
2899 return error(_("cannot cherry-pick during a revert."));
2900 else
2901 return error(_("cannot revert during a cherry-pick."));
2904 if (is_rebase_i(opts)) {
2905 struct todo_list done = TODO_LIST_INIT;
2907 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2908 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2909 todo_list->done_nr = count_commands(&done);
2910 else
2911 todo_list->done_nr = 0;
2913 todo_list->total_nr = todo_list->done_nr
2914 + count_commands(todo_list);
2915 todo_list_release(&done);
2917 todo_list_write_total_nr(todo_list);
2920 return 0;
2923 static int git_config_string_dup(char **dest,
2924 const char *var, const char *value)
2926 if (!value)
2927 return config_error_nonbool(var);
2928 free(*dest);
2929 *dest = xstrdup(value);
2930 return 0;
2933 static int populate_opts_cb(const char *key, const char *value,
2934 const struct config_context *ctx,
2935 void *data)
2937 struct replay_opts *opts = data;
2938 int error_flag = 1;
2940 if (!value)
2941 error_flag = 0;
2942 else if (!strcmp(key, "options.no-commit"))
2943 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2944 else if (!strcmp(key, "options.edit"))
2945 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2946 else if (!strcmp(key, "options.allow-empty"))
2947 opts->allow_empty =
2948 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2949 else if (!strcmp(key, "options.allow-empty-message"))
2950 opts->allow_empty_message =
2951 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2952 else if (!strcmp(key, "options.drop-redundant-commits"))
2953 opts->drop_redundant_commits =
2954 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2955 else if (!strcmp(key, "options.keep-redundant-commits"))
2956 opts->keep_redundant_commits =
2957 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2958 else if (!strcmp(key, "options.signoff"))
2959 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2960 else if (!strcmp(key, "options.record-origin"))
2961 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2962 else if (!strcmp(key, "options.allow-ff"))
2963 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2964 else if (!strcmp(key, "options.mainline"))
2965 opts->mainline = git_config_int(key, value, ctx->kvi);
2966 else if (!strcmp(key, "options.strategy"))
2967 git_config_string_dup(&opts->strategy, key, value);
2968 else if (!strcmp(key, "options.gpg-sign"))
2969 git_config_string_dup(&opts->gpg_sign, key, value);
2970 else if (!strcmp(key, "options.strategy-option")) {
2971 strvec_push(&opts->xopts, value);
2972 } else if (!strcmp(key, "options.allow-rerere-auto"))
2973 opts->allow_rerere_auto =
2974 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
2975 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2976 else if (!strcmp(key, "options.default-msg-cleanup")) {
2977 opts->explicit_cleanup = 1;
2978 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2979 } else
2980 return error(_("invalid key: %s"), key);
2982 if (!error_flag)
2983 return error(_("invalid value for '%s': '%s'"), key, value);
2985 return 0;
2988 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2990 int i;
2991 int count;
2992 const char **argv;
2993 char *strategy_opts_string = raw_opts;
2995 if (*strategy_opts_string == ' ')
2996 strategy_opts_string++;
2998 count = split_cmdline(strategy_opts_string, &argv);
2999 if (count < 0)
3000 BUG("could not split '%s': %s", strategy_opts_string,
3001 split_cmdline_strerror(count));
3002 for (i = 0; i < count; i++) {
3003 const char *arg = argv[i];
3005 skip_prefix(arg, "--", &arg);
3006 strvec_push(&opts->xopts, arg);
3008 free(argv);
3011 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3013 strbuf_reset(buf);
3014 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3015 return;
3016 opts->strategy = strbuf_detach(buf, NULL);
3017 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3018 return;
3020 parse_strategy_opts(opts, buf->buf);
3023 static int read_populate_opts(struct replay_opts *opts)
3025 if (is_rebase_i(opts)) {
3026 struct strbuf buf = STRBUF_INIT;
3027 int ret = 0;
3029 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3030 READ_ONELINER_SKIP_IF_EMPTY)) {
3031 if (!starts_with(buf.buf, "-S"))
3032 strbuf_reset(&buf);
3033 else {
3034 free(opts->gpg_sign);
3035 opts->gpg_sign = xstrdup(buf.buf + 2);
3037 strbuf_reset(&buf);
3040 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3041 READ_ONELINER_SKIP_IF_EMPTY)) {
3042 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3043 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3044 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3045 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3046 strbuf_reset(&buf);
3049 if (file_exists(rebase_path_verbose()))
3050 opts->verbose = 1;
3052 if (file_exists(rebase_path_quiet()))
3053 opts->quiet = 1;
3055 if (file_exists(rebase_path_signoff())) {
3056 opts->allow_ff = 0;
3057 opts->signoff = 1;
3060 if (file_exists(rebase_path_cdate_is_adate())) {
3061 opts->allow_ff = 0;
3062 opts->committer_date_is_author_date = 1;
3065 if (file_exists(rebase_path_ignore_date())) {
3066 opts->allow_ff = 0;
3067 opts->ignore_date = 1;
3070 if (file_exists(rebase_path_reschedule_failed_exec()))
3071 opts->reschedule_failed_exec = 1;
3072 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3073 opts->reschedule_failed_exec = 0;
3075 if (file_exists(rebase_path_drop_redundant_commits()))
3076 opts->drop_redundant_commits = 1;
3078 if (file_exists(rebase_path_keep_redundant_commits()))
3079 opts->keep_redundant_commits = 1;
3081 read_strategy_opts(opts, &buf);
3082 strbuf_reset(&buf);
3084 if (read_oneliner(&opts->current_fixups,
3085 rebase_path_current_fixups(),
3086 READ_ONELINER_SKIP_IF_EMPTY)) {
3087 const char *p = opts->current_fixups.buf;
3088 opts->current_fixup_count = 1;
3089 while ((p = strchr(p, '\n'))) {
3090 opts->current_fixup_count++;
3091 p++;
3095 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3096 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3097 ret = error(_("unusable squash-onto"));
3098 goto done_rebase_i;
3100 opts->have_squash_onto = 1;
3103 done_rebase_i:
3104 strbuf_release(&buf);
3105 return ret;
3108 if (!file_exists(git_path_opts_file()))
3109 return 0;
3111 * The function git_parse_source(), called from git_config_from_file(),
3112 * may die() in case of a syntactically incorrect file. We do not care
3113 * about this case, though, because we wrote that file ourselves, so we
3114 * are pretty certain that it is syntactically correct.
3116 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3117 return error(_("malformed options sheet: '%s'"),
3118 git_path_opts_file());
3119 return 0;
3122 static void write_strategy_opts(struct replay_opts *opts)
3124 struct strbuf buf = STRBUF_INIT;
3127 * Quote strategy options so that they can be read correctly
3128 * by split_cmdline().
3130 quote_cmdline(&buf, opts->xopts.v);
3131 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3132 strbuf_release(&buf);
3135 int write_basic_state(struct replay_opts *opts, const char *head_name,
3136 struct commit *onto, const struct object_id *orig_head)
3138 if (head_name)
3139 write_file(rebase_path_head_name(), "%s\n", head_name);
3140 if (onto)
3141 write_file(rebase_path_onto(), "%s\n",
3142 oid_to_hex(&onto->object.oid));
3143 if (orig_head)
3144 write_file(rebase_path_orig_head(), "%s\n",
3145 oid_to_hex(orig_head));
3147 if (opts->quiet)
3148 write_file(rebase_path_quiet(), "%s", "");
3149 if (opts->verbose)
3150 write_file(rebase_path_verbose(), "%s", "");
3151 if (opts->strategy)
3152 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3153 if (opts->xopts.nr > 0)
3154 write_strategy_opts(opts);
3156 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3157 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3158 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3159 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3161 if (opts->gpg_sign)
3162 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3163 if (opts->signoff)
3164 write_file(rebase_path_signoff(), "--signoff\n");
3165 if (opts->drop_redundant_commits)
3166 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3167 if (opts->keep_redundant_commits)
3168 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3169 if (opts->committer_date_is_author_date)
3170 write_file(rebase_path_cdate_is_adate(), "%s", "");
3171 if (opts->ignore_date)
3172 write_file(rebase_path_ignore_date(), "%s", "");
3173 if (opts->reschedule_failed_exec)
3174 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3175 else
3176 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3178 return 0;
3181 static int walk_revs_populate_todo(struct todo_list *todo_list,
3182 struct replay_opts *opts)
3184 enum todo_command command = opts->action == REPLAY_PICK ?
3185 TODO_PICK : TODO_REVERT;
3186 const char *command_string = todo_command_info[command].str;
3187 const char *encoding;
3188 struct commit *commit;
3190 if (prepare_revs(opts))
3191 return -1;
3193 encoding = get_log_output_encoding();
3195 while ((commit = get_revision(opts->revs))) {
3196 struct todo_item *item = append_new_todo(todo_list);
3197 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3198 commit, NULL,
3199 encoding);
3200 const char *subject;
3201 int subject_len;
3203 item->command = command;
3204 item->commit = commit;
3205 item->arg_offset = 0;
3206 item->arg_len = 0;
3207 item->offset_in_buf = todo_list->buf.len;
3208 subject_len = find_commit_subject(commit_buffer, &subject);
3209 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3210 short_commit_name(the_repository, commit),
3211 subject_len, subject);
3212 repo_unuse_commit_buffer(the_repository, commit,
3213 commit_buffer);
3216 if (!todo_list->nr)
3217 return error(_("empty commit set passed"));
3219 return 0;
3222 static int create_seq_dir(struct repository *r)
3224 enum replay_action action;
3225 const char *in_progress_error = NULL;
3226 const char *in_progress_advice = NULL;
3227 unsigned int advise_skip =
3228 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3229 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3231 if (!sequencer_get_last_command(r, &action)) {
3232 switch (action) {
3233 case REPLAY_REVERT:
3234 in_progress_error = _("revert is already in progress");
3235 in_progress_advice =
3236 _("try \"git revert (--continue | %s--abort | --quit)\"");
3237 break;
3238 case REPLAY_PICK:
3239 in_progress_error = _("cherry-pick is already in progress");
3240 in_progress_advice =
3241 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3242 break;
3243 default:
3244 BUG("unexpected action in create_seq_dir");
3247 if (in_progress_error) {
3248 error("%s", in_progress_error);
3249 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3250 advise(in_progress_advice,
3251 advise_skip ? "--skip | " : "");
3252 return -1;
3254 if (mkdir(git_path_seq_dir(), 0777) < 0)
3255 return error_errno(_("could not create sequencer directory '%s'"),
3256 git_path_seq_dir());
3258 return 0;
3261 static int save_head(const char *head)
3263 return write_message(head, strlen(head), git_path_head_file(), 1);
3266 static int rollback_is_safe(void)
3268 struct strbuf sb = STRBUF_INIT;
3269 struct object_id expected_head, actual_head;
3271 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3272 strbuf_trim(&sb);
3273 if (get_oid_hex(sb.buf, &expected_head)) {
3274 strbuf_release(&sb);
3275 die(_("could not parse %s"), git_path_abort_safety_file());
3277 strbuf_release(&sb);
3279 else if (errno == ENOENT)
3280 oidclr(&expected_head);
3281 else
3282 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3284 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3285 oidclr(&actual_head);
3287 return oideq(&actual_head, &expected_head);
3290 static int reset_merge(const struct object_id *oid)
3292 struct child_process cmd = CHILD_PROCESS_INIT;
3294 cmd.git_cmd = 1;
3295 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3297 if (!is_null_oid(oid))
3298 strvec_push(&cmd.args, oid_to_hex(oid));
3300 return run_command(&cmd);
3303 static int rollback_single_pick(struct repository *r)
3305 struct object_id head_oid;
3307 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3308 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3309 return error(_("no cherry-pick or revert in progress"));
3310 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3311 return error(_("cannot resolve HEAD"));
3312 if (is_null_oid(&head_oid))
3313 return error(_("cannot abort from a branch yet to be born"));
3314 return reset_merge(&head_oid);
3317 static int skip_single_pick(void)
3319 struct object_id head;
3321 if (read_ref_full("HEAD", 0, &head, NULL))
3322 return error(_("cannot resolve HEAD"));
3323 return reset_merge(&head);
3326 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3328 FILE *f;
3329 struct object_id oid;
3330 struct strbuf buf = STRBUF_INIT;
3331 const char *p;
3333 f = fopen(git_path_head_file(), "r");
3334 if (!f && errno == ENOENT) {
3336 * There is no multiple-cherry-pick in progress.
3337 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3338 * a single-cherry-pick in progress, abort that.
3340 return rollback_single_pick(r);
3342 if (!f)
3343 return error_errno(_("cannot open '%s'"), git_path_head_file());
3344 if (strbuf_getline_lf(&buf, f)) {
3345 error(_("cannot read '%s': %s"), git_path_head_file(),
3346 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3347 fclose(f);
3348 goto fail;
3350 fclose(f);
3351 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3352 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3353 git_path_head_file());
3354 goto fail;
3356 if (is_null_oid(&oid)) {
3357 error(_("cannot abort from a branch yet to be born"));
3358 goto fail;
3361 if (!rollback_is_safe()) {
3362 /* Do not error, just do not rollback */
3363 warning(_("You seem to have moved HEAD. "
3364 "Not rewinding, check your HEAD!"));
3365 } else
3366 if (reset_merge(&oid))
3367 goto fail;
3368 strbuf_release(&buf);
3369 return sequencer_remove_state(opts);
3370 fail:
3371 strbuf_release(&buf);
3372 return -1;
3375 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3377 enum replay_action action = -1;
3378 sequencer_get_last_command(r, &action);
3381 * Check whether the subcommand requested to skip the commit is actually
3382 * in progress and that it's safe to skip the commit.
3384 * opts->action tells us which subcommand requested to skip the commit.
3385 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3386 * action is in progress and we can skip the commit.
3388 * Otherwise we check that the last instruction was related to the
3389 * particular subcommand we're trying to execute and barf if that's not
3390 * the case.
3392 * Finally we check that the rollback is "safe", i.e., has the HEAD
3393 * moved? In this case, it doesn't make sense to "reset the merge" and
3394 * "skip the commit" as the user already handled this by committing. But
3395 * we'd not want to barf here, instead give advice on how to proceed. We
3396 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3397 * it gets removed when the user commits, so if it still exists we're
3398 * sure the user can't have committed before.
3400 switch (opts->action) {
3401 case REPLAY_REVERT:
3402 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3403 if (action != REPLAY_REVERT)
3404 return error(_("no revert in progress"));
3405 if (!rollback_is_safe())
3406 goto give_advice;
3408 break;
3409 case REPLAY_PICK:
3410 if (!refs_ref_exists(get_main_ref_store(r),
3411 "CHERRY_PICK_HEAD")) {
3412 if (action != REPLAY_PICK)
3413 return error(_("no cherry-pick in progress"));
3414 if (!rollback_is_safe())
3415 goto give_advice;
3417 break;
3418 default:
3419 BUG("unexpected action in sequencer_skip");
3422 if (skip_single_pick())
3423 return error(_("failed to skip the commit"));
3424 if (!is_directory(git_path_seq_dir()))
3425 return 0;
3427 return sequencer_continue(r, opts);
3429 give_advice:
3430 error(_("there is nothing to skip"));
3432 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3433 advise(_("have you committed already?\n"
3434 "try \"git %s --continue\""),
3435 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3437 return -1;
3440 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3441 int reschedule)
3443 struct lock_file todo_lock = LOCK_INIT;
3444 const char *todo_path = get_todo_path(opts);
3445 int next = todo_list->current, offset, fd;
3448 * rebase -i writes "git-rebase-todo" without the currently executing
3449 * command, appending it to "done" instead.
3451 if (is_rebase_i(opts) && !reschedule)
3452 next++;
3454 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3455 if (fd < 0)
3456 return error_errno(_("could not lock '%s'"), todo_path);
3457 offset = get_item_line_offset(todo_list, next);
3458 if (write_in_full(fd, todo_list->buf.buf + offset,
3459 todo_list->buf.len - offset) < 0)
3460 return error_errno(_("could not write to '%s'"), todo_path);
3461 if (commit_lock_file(&todo_lock) < 0)
3462 return error(_("failed to finalize '%s'"), todo_path);
3464 if (is_rebase_i(opts) && !reschedule && next > 0) {
3465 const char *done = rebase_path_done();
3466 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3467 int ret = 0;
3469 if (fd < 0)
3470 return 0;
3471 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3472 get_item_line_length(todo_list, next - 1))
3473 < 0)
3474 ret = error_errno(_("could not write to '%s'"), done);
3475 if (close(fd) < 0)
3476 ret = error_errno(_("failed to finalize '%s'"), done);
3477 return ret;
3479 return 0;
3482 static int save_opts(struct replay_opts *opts)
3484 const char *opts_file = git_path_opts_file();
3485 int res = 0;
3487 if (opts->no_commit)
3488 res |= git_config_set_in_file_gently(opts_file,
3489 "options.no-commit", NULL, "true");
3490 if (opts->edit >= 0)
3491 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3492 opts->edit ? "true" : "false");
3493 if (opts->allow_empty)
3494 res |= git_config_set_in_file_gently(opts_file,
3495 "options.allow-empty", NULL, "true");
3496 if (opts->allow_empty_message)
3497 res |= git_config_set_in_file_gently(opts_file,
3498 "options.allow-empty-message", NULL, "true");
3499 if (opts->drop_redundant_commits)
3500 res |= git_config_set_in_file_gently(opts_file,
3501 "options.drop-redundant-commits", NULL, "true");
3502 if (opts->keep_redundant_commits)
3503 res |= git_config_set_in_file_gently(opts_file,
3504 "options.keep-redundant-commits", NULL, "true");
3505 if (opts->signoff)
3506 res |= git_config_set_in_file_gently(opts_file,
3507 "options.signoff", NULL, "true");
3508 if (opts->record_origin)
3509 res |= git_config_set_in_file_gently(opts_file,
3510 "options.record-origin", NULL, "true");
3511 if (opts->allow_ff)
3512 res |= git_config_set_in_file_gently(opts_file,
3513 "options.allow-ff", NULL, "true");
3514 if (opts->mainline) {
3515 struct strbuf buf = STRBUF_INIT;
3516 strbuf_addf(&buf, "%d", opts->mainline);
3517 res |= git_config_set_in_file_gently(opts_file,
3518 "options.mainline", NULL, buf.buf);
3519 strbuf_release(&buf);
3521 if (opts->strategy)
3522 res |= git_config_set_in_file_gently(opts_file,
3523 "options.strategy", NULL, opts->strategy);
3524 if (opts->gpg_sign)
3525 res |= git_config_set_in_file_gently(opts_file,
3526 "options.gpg-sign", NULL, opts->gpg_sign);
3527 for (size_t i = 0; i < opts->xopts.nr; i++)
3528 res |= git_config_set_multivar_in_file_gently(opts_file,
3529 "options.strategy-option",
3530 opts->xopts.v[i], "^$", NULL, 0);
3531 if (opts->allow_rerere_auto)
3532 res |= git_config_set_in_file_gently(opts_file,
3533 "options.allow-rerere-auto", NULL,
3534 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3535 "true" : "false");
3537 if (opts->explicit_cleanup)
3538 res |= git_config_set_in_file_gently(opts_file,
3539 "options.default-msg-cleanup", NULL,
3540 describe_cleanup_mode(opts->default_msg_cleanup));
3541 return res;
3544 static int make_patch(struct repository *r,
3545 struct commit *commit,
3546 struct replay_opts *opts)
3548 struct rev_info log_tree_opt;
3549 const char *subject;
3550 char hex[GIT_MAX_HEXSZ + 1];
3551 int res = 0;
3553 if (!is_rebase_i(opts))
3554 BUG("make_patch should only be called when rebasing");
3556 oid_to_hex_r(hex, &commit->object.oid);
3557 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3558 return -1;
3559 res |= write_rebase_head(&commit->object.oid);
3561 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3562 repo_init_revisions(r, &log_tree_opt, NULL);
3563 log_tree_opt.abbrev = 0;
3564 log_tree_opt.diff = 1;
3565 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3566 log_tree_opt.disable_stdin = 1;
3567 log_tree_opt.no_commit_id = 1;
3568 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3569 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3570 if (!log_tree_opt.diffopt.file)
3571 res |= error_errno(_("could not open '%s'"),
3572 rebase_path_patch());
3573 else {
3574 res |= log_tree_commit(&log_tree_opt, commit);
3575 fclose(log_tree_opt.diffopt.file);
3578 if (!file_exists(rebase_path_message())) {
3579 const char *encoding = get_commit_output_encoding();
3580 const char *commit_buffer = repo_logmsg_reencode(r,
3581 commit, NULL,
3582 encoding);
3583 find_commit_subject(commit_buffer, &subject);
3584 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3585 repo_unuse_commit_buffer(r, commit,
3586 commit_buffer);
3588 release_revisions(&log_tree_opt);
3590 return res;
3593 static int intend_to_amend(void)
3595 struct object_id head;
3596 char *p;
3598 if (repo_get_oid(the_repository, "HEAD", &head))
3599 return error(_("cannot read HEAD"));
3601 p = oid_to_hex(&head);
3602 return write_message(p, strlen(p), rebase_path_amend(), 1);
3605 static int error_with_patch(struct repository *r,
3606 struct commit *commit,
3607 const char *subject, int subject_len,
3608 struct replay_opts *opts,
3609 int exit_code, int to_amend)
3611 if (commit) {
3612 if (make_patch(r, commit, opts))
3613 return -1;
3614 } else if (copy_file(rebase_path_message(),
3615 git_path_merge_msg(r), 0666))
3616 return error(_("unable to copy '%s' to '%s'"),
3617 git_path_merge_msg(r), rebase_path_message());
3619 if (to_amend) {
3620 if (intend_to_amend())
3621 return -1;
3623 fprintf(stderr,
3624 _("You can amend the commit now, with\n"
3625 "\n"
3626 " git commit --amend %s\n"
3627 "\n"
3628 "Once you are satisfied with your changes, run\n"
3629 "\n"
3630 " git rebase --continue\n"),
3631 gpg_sign_opt_quoted(opts));
3632 } else if (exit_code) {
3633 if (commit)
3634 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3635 short_commit_name(r, commit), subject_len, subject);
3636 else
3638 * We don't have the hash of the parent so
3639 * just print the line from the todo file.
3641 fprintf_ln(stderr, _("Could not merge %.*s"),
3642 subject_len, subject);
3645 return exit_code;
3648 static int error_failed_squash(struct repository *r,
3649 struct commit *commit,
3650 struct replay_opts *opts,
3651 int subject_len,
3652 const char *subject)
3654 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3655 return error(_("could not copy '%s' to '%s'"),
3656 rebase_path_squash_msg(), rebase_path_message());
3657 unlink(git_path_merge_msg(r));
3658 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3659 return error(_("could not copy '%s' to '%s'"),
3660 rebase_path_message(),
3661 git_path_merge_msg(r));
3662 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3665 static int do_exec(struct repository *r, const char *command_line)
3667 struct child_process cmd = CHILD_PROCESS_INIT;
3668 int dirty, status;
3670 fprintf(stderr, _("Executing: %s\n"), command_line);
3671 cmd.use_shell = 1;
3672 strvec_push(&cmd.args, command_line);
3673 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3674 status = run_command(&cmd);
3676 /* force re-reading of the cache */
3677 discard_index(r->index);
3678 if (repo_read_index(r) < 0)
3679 return error(_("could not read index"));
3681 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3683 if (status) {
3684 warning(_("execution failed: %s\n%s"
3685 "You can fix the problem, and then run\n"
3686 "\n"
3687 " git rebase --continue\n"
3688 "\n"),
3689 command_line,
3690 dirty ? _("and made changes to the index and/or the "
3691 "working tree.\n") : "");
3692 if (status == 127)
3693 /* command not found */
3694 status = 1;
3695 } else if (dirty) {
3696 warning(_("execution succeeded: %s\nbut "
3697 "left changes to the index and/or the working tree.\n"
3698 "Commit or stash your changes, and then run\n"
3699 "\n"
3700 " git rebase --continue\n"
3701 "\n"), command_line);
3702 status = 1;
3705 return status;
3708 __attribute__((format (printf, 2, 3)))
3709 static int safe_append(const char *filename, const char *fmt, ...)
3711 va_list ap;
3712 struct lock_file lock = LOCK_INIT;
3713 int fd = hold_lock_file_for_update(&lock, filename,
3714 LOCK_REPORT_ON_ERROR);
3715 struct strbuf buf = STRBUF_INIT;
3717 if (fd < 0)
3718 return -1;
3720 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3721 error_errno(_("could not read '%s'"), filename);
3722 rollback_lock_file(&lock);
3723 return -1;
3725 strbuf_complete(&buf, '\n');
3726 va_start(ap, fmt);
3727 strbuf_vaddf(&buf, fmt, ap);
3728 va_end(ap);
3730 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3731 error_errno(_("could not write to '%s'"), filename);
3732 strbuf_release(&buf);
3733 rollback_lock_file(&lock);
3734 return -1;
3736 if (commit_lock_file(&lock) < 0) {
3737 strbuf_release(&buf);
3738 return error(_("failed to finalize '%s'"), filename);
3741 strbuf_release(&buf);
3742 return 0;
3745 static int do_label(struct repository *r, const char *name, int len)
3747 struct ref_store *refs = get_main_ref_store(r);
3748 struct ref_transaction *transaction;
3749 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3750 struct strbuf msg = STRBUF_INIT;
3751 int ret = 0;
3752 struct object_id head_oid;
3754 if (len == 1 && *name == '#')
3755 return error(_("illegal label name: '%.*s'"), len, name);
3757 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3758 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3760 transaction = ref_store_transaction_begin(refs, &err);
3761 if (!transaction) {
3762 error("%s", err.buf);
3763 ret = -1;
3764 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3765 error(_("could not read HEAD"));
3766 ret = -1;
3767 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3768 NULL, 0, msg.buf, &err) < 0 ||
3769 ref_transaction_commit(transaction, &err)) {
3770 error("%s", err.buf);
3771 ret = -1;
3773 ref_transaction_free(transaction);
3774 strbuf_release(&err);
3775 strbuf_release(&msg);
3777 if (!ret)
3778 ret = safe_append(rebase_path_refs_to_delete(),
3779 "%s\n", ref_name.buf);
3780 strbuf_release(&ref_name);
3782 return ret;
3785 static const char *sequencer_reflog_action(struct replay_opts *opts)
3787 if (!opts->reflog_action) {
3788 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3789 opts->reflog_action =
3790 xstrdup(opts->reflog_action ? opts->reflog_action
3791 : action_name(opts));
3794 return opts->reflog_action;
3797 __attribute__((format (printf, 3, 4)))
3798 static const char *reflog_message(struct replay_opts *opts,
3799 const char *sub_action, const char *fmt, ...)
3801 va_list ap;
3802 static struct strbuf buf = STRBUF_INIT;
3804 va_start(ap, fmt);
3805 strbuf_reset(&buf);
3806 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3807 if (sub_action)
3808 strbuf_addf(&buf, " (%s)", sub_action);
3809 if (fmt) {
3810 strbuf_addstr(&buf, ": ");
3811 strbuf_vaddf(&buf, fmt, ap);
3813 va_end(ap);
3815 return buf.buf;
3818 static struct commit *lookup_label(struct repository *r, const char *label,
3819 int len, struct strbuf *buf)
3821 struct commit *commit;
3822 struct object_id oid;
3824 strbuf_reset(buf);
3825 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3826 if (!read_ref(buf->buf, &oid)) {
3827 commit = lookup_commit_object(r, &oid);
3828 } else {
3829 /* fall back to non-rewritten ref or commit */
3830 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3831 commit = lookup_commit_reference_by_name(buf->buf);
3834 if (!commit)
3835 error(_("could not resolve '%s'"), buf->buf);
3837 return commit;
3840 static int do_reset(struct repository *r,
3841 const char *name, int len,
3842 struct replay_opts *opts)
3844 struct strbuf ref_name = STRBUF_INIT;
3845 struct object_id oid;
3846 struct lock_file lock = LOCK_INIT;
3847 struct tree_desc desc = { 0 };
3848 struct tree *tree;
3849 struct unpack_trees_options unpack_tree_opts = { 0 };
3850 int ret = 0;
3852 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3853 return -1;
3855 if (len == 10 && !strncmp("[new root]", name, len)) {
3856 if (!opts->have_squash_onto) {
3857 const char *hex;
3858 if (commit_tree("", 0, the_hash_algo->empty_tree,
3859 NULL, &opts->squash_onto,
3860 NULL, NULL))
3861 return error(_("writing fake root commit"));
3862 opts->have_squash_onto = 1;
3863 hex = oid_to_hex(&opts->squash_onto);
3864 if (write_message(hex, strlen(hex),
3865 rebase_path_squash_onto(), 0))
3866 return error(_("writing squash-onto"));
3868 oidcpy(&oid, &opts->squash_onto);
3869 } else {
3870 int i;
3871 struct commit *commit;
3873 /* Determine the length of the label */
3874 for (i = 0; i < len; i++)
3875 if (isspace(name[i]))
3876 break;
3877 len = i;
3879 commit = lookup_label(r, name, len, &ref_name);
3880 if (!commit) {
3881 ret = -1;
3882 goto cleanup;
3884 oid = commit->object.oid;
3887 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3888 unpack_tree_opts.head_idx = 1;
3889 unpack_tree_opts.src_index = r->index;
3890 unpack_tree_opts.dst_index = r->index;
3891 unpack_tree_opts.fn = oneway_merge;
3892 unpack_tree_opts.merge = 1;
3893 unpack_tree_opts.update = 1;
3894 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3895 unpack_tree_opts.skip_cache_tree_update = 1;
3896 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3898 if (repo_read_index_unmerged(r)) {
3899 ret = error_resolve_conflict(action_name(opts));
3900 goto cleanup;
3903 if (!fill_tree_descriptor(r, &desc, &oid)) {
3904 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3905 goto cleanup;
3908 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3909 ret = -1;
3910 goto cleanup;
3913 tree = parse_tree_indirect(&oid);
3914 if (!tree)
3915 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
3916 prime_cache_tree(r, r->index, tree);
3918 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3919 ret = error(_("could not write index"));
3921 if (!ret)
3922 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3923 len, name), "HEAD", &oid,
3924 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3925 cleanup:
3926 free((void *)desc.buffer);
3927 if (ret < 0)
3928 rollback_lock_file(&lock);
3929 strbuf_release(&ref_name);
3930 clear_unpack_trees_porcelain(&unpack_tree_opts);
3931 return ret;
3934 static int do_merge(struct repository *r,
3935 struct commit *commit,
3936 const char *arg, int arg_len,
3937 int flags, int *check_todo, struct replay_opts *opts)
3939 int run_commit_flags = 0;
3940 struct strbuf ref_name = STRBUF_INIT;
3941 struct commit *head_commit, *merge_commit, *i;
3942 struct commit_list *bases = NULL, *j;
3943 struct commit_list *to_merge = NULL, **tail = &to_merge;
3944 const char *strategy = !opts->xopts.nr &&
3945 (!opts->strategy ||
3946 !strcmp(opts->strategy, "recursive") ||
3947 !strcmp(opts->strategy, "ort")) ?
3948 NULL : opts->strategy;
3949 struct merge_options o;
3950 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3951 static struct lock_file lock;
3952 const char *p;
3954 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3955 ret = -1;
3956 goto leave_merge;
3959 head_commit = lookup_commit_reference_by_name("HEAD");
3960 if (!head_commit) {
3961 ret = error(_("cannot merge without a current revision"));
3962 goto leave_merge;
3966 * For octopus merges, the arg starts with the list of revisions to be
3967 * merged. The list is optionally followed by '#' and the oneline.
3969 merge_arg_len = oneline_offset = arg_len;
3970 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3971 if (!*p)
3972 break;
3973 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3974 p += 1 + strspn(p + 1, " \t\n");
3975 oneline_offset = p - arg;
3976 break;
3978 k = strcspn(p, " \t\n");
3979 if (!k)
3980 continue;
3981 merge_commit = lookup_label(r, p, k, &ref_name);
3982 if (!merge_commit) {
3983 ret = error(_("unable to parse '%.*s'"), k, p);
3984 goto leave_merge;
3986 tail = &commit_list_insert(merge_commit, tail)->next;
3987 p += k;
3988 merge_arg_len = p - arg;
3991 if (!to_merge) {
3992 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3993 goto leave_merge;
3996 if (opts->have_squash_onto &&
3997 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3999 * When the user tells us to "merge" something into a
4000 * "[new root]", let's simply fast-forward to the merge head.
4002 rollback_lock_file(&lock);
4003 if (to_merge->next)
4004 ret = error(_("octopus merge cannot be executed on "
4005 "top of a [new root]"));
4006 else
4007 ret = fast_forward_to(r, &to_merge->item->object.oid,
4008 &head_commit->object.oid, 0,
4009 opts);
4010 goto leave_merge;
4014 * If HEAD is not identical to the first parent of the original merge
4015 * commit, we cannot fast-forward.
4017 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4018 oideq(&commit->parents->item->object.oid,
4019 &head_commit->object.oid);
4022 * If any merge head is different from the original one, we cannot
4023 * fast-forward.
4025 if (can_fast_forward) {
4026 struct commit_list *p = commit->parents->next;
4028 for (j = to_merge; j && p; j = j->next, p = p->next)
4029 if (!oideq(&j->item->object.oid,
4030 &p->item->object.oid)) {
4031 can_fast_forward = 0;
4032 break;
4035 * If the number of merge heads differs from the original merge
4036 * commit, we cannot fast-forward.
4038 if (j || p)
4039 can_fast_forward = 0;
4042 if (can_fast_forward) {
4043 rollback_lock_file(&lock);
4044 ret = fast_forward_to(r, &commit->object.oid,
4045 &head_commit->object.oid, 0, opts);
4046 if (flags & TODO_EDIT_MERGE_MSG)
4047 goto fast_forward_edit;
4049 goto leave_merge;
4052 if (commit) {
4053 const char *encoding = get_commit_output_encoding();
4054 const char *message = repo_logmsg_reencode(r, commit, NULL,
4055 encoding);
4056 const char *body;
4057 int len;
4059 if (!message) {
4060 ret = error(_("could not get commit message of '%s'"),
4061 oid_to_hex(&commit->object.oid));
4062 goto leave_merge;
4064 write_author_script(message);
4065 find_commit_subject(message, &body);
4066 len = strlen(body);
4067 ret = write_message(body, len, git_path_merge_msg(r), 0);
4068 repo_unuse_commit_buffer(r, commit, message);
4069 if (ret) {
4070 error_errno(_("could not write '%s'"),
4071 git_path_merge_msg(r));
4072 goto leave_merge;
4074 } else {
4075 struct strbuf buf = STRBUF_INIT;
4076 int len;
4078 strbuf_addf(&buf, "author %s", git_author_info(0));
4079 write_author_script(buf.buf);
4080 strbuf_reset(&buf);
4082 if (oneline_offset < arg_len) {
4083 p = arg + oneline_offset;
4084 len = arg_len - oneline_offset;
4085 } else {
4086 strbuf_addf(&buf, "Merge %s '%.*s'",
4087 to_merge->next ? "branches" : "branch",
4088 merge_arg_len, arg);
4089 p = buf.buf;
4090 len = buf.len;
4093 ret = write_message(p, len, git_path_merge_msg(r), 0);
4094 strbuf_release(&buf);
4095 if (ret) {
4096 error_errno(_("could not write '%s'"),
4097 git_path_merge_msg(r));
4098 goto leave_merge;
4102 if (strategy || to_merge->next) {
4103 /* Octopus merge */
4104 struct child_process cmd = CHILD_PROCESS_INIT;
4106 if (read_env_script(&cmd.env)) {
4107 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4109 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4110 goto leave_merge;
4113 if (opts->committer_date_is_author_date)
4114 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4115 opts->ignore_date ?
4116 "" :
4117 author_date_from_env(&cmd.env));
4118 if (opts->ignore_date)
4119 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4121 cmd.git_cmd = 1;
4122 strvec_push(&cmd.args, "merge");
4123 strvec_push(&cmd.args, "-s");
4124 if (!strategy)
4125 strvec_push(&cmd.args, "octopus");
4126 else {
4127 strvec_push(&cmd.args, strategy);
4128 for (k = 0; k < opts->xopts.nr; k++)
4129 strvec_pushf(&cmd.args,
4130 "-X%s", opts->xopts.v[k]);
4132 if (!(flags & TODO_EDIT_MERGE_MSG))
4133 strvec_push(&cmd.args, "--no-edit");
4134 else
4135 strvec_push(&cmd.args, "--edit");
4136 strvec_push(&cmd.args, "--no-ff");
4137 strvec_push(&cmd.args, "--no-log");
4138 strvec_push(&cmd.args, "--no-stat");
4139 strvec_push(&cmd.args, "-F");
4140 strvec_push(&cmd.args, git_path_merge_msg(r));
4141 if (opts->gpg_sign)
4142 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4143 else
4144 strvec_push(&cmd.args, "--no-gpg-sign");
4146 /* Add the tips to be merged */
4147 for (j = to_merge; j; j = j->next)
4148 strvec_push(&cmd.args,
4149 oid_to_hex(&j->item->object.oid));
4151 strbuf_release(&ref_name);
4152 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4153 NULL, REF_NO_DEREF);
4154 rollback_lock_file(&lock);
4156 ret = run_command(&cmd);
4158 /* force re-reading of the cache */
4159 if (!ret) {
4160 discard_index(r->index);
4161 if (repo_read_index(r) < 0)
4162 ret = error(_("could not read index"));
4164 goto leave_merge;
4167 merge_commit = to_merge->item;
4168 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4169 ret = -1;
4170 goto leave_merge;
4173 if (bases && oideq(&merge_commit->object.oid,
4174 &bases->item->object.oid)) {
4175 ret = 0;
4176 /* skip merging an ancestor of HEAD */
4177 goto leave_merge;
4180 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4181 git_path_merge_head(r), 0);
4182 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4184 bases = reverse_commit_list(bases);
4186 repo_read_index(r);
4187 init_merge_options(&o, r);
4188 o.branch1 = "HEAD";
4189 o.branch2 = ref_name.buf;
4190 o.buffer_output = 2;
4192 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4194 * TODO: Should use merge_incore_recursive() and
4195 * merge_switch_to_result(), skipping the call to
4196 * merge_switch_to_result() when we don't actually need to
4197 * update the index and working copy immediately.
4199 ret = merge_ort_recursive(&o,
4200 head_commit, merge_commit, bases,
4201 &i);
4202 } else {
4203 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4204 &i);
4206 if (ret <= 0)
4207 fputs(o.obuf.buf, stdout);
4208 strbuf_release(&o.obuf);
4209 if (ret < 0) {
4210 error(_("could not even attempt to merge '%.*s'"),
4211 merge_arg_len, arg);
4212 unlink(git_path_merge_msg(r));
4213 goto leave_merge;
4216 * The return value of merge_recursive() is 1 on clean, and 0 on
4217 * unclean merge.
4219 * Let's reverse that, so that do_merge() returns 0 upon success and
4220 * 1 upon failed merge (keeping the return value -1 for the cases where
4221 * we will want to reschedule the `merge` command).
4223 ret = !ret;
4225 if (r->index->cache_changed &&
4226 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4227 ret = error(_("merge: Unable to write new index file"));
4228 goto leave_merge;
4231 rollback_lock_file(&lock);
4232 if (ret)
4233 repo_rerere(r, opts->allow_rerere_auto);
4234 else
4236 * In case of problems, we now want to return a positive
4237 * value (a negative one would indicate that the `merge`
4238 * command needs to be rescheduled).
4240 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4241 run_commit_flags);
4243 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4244 fast_forward_edit:
4245 *check_todo = 1;
4246 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4247 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4251 leave_merge:
4252 strbuf_release(&ref_name);
4253 rollback_lock_file(&lock);
4254 free_commit_list(to_merge);
4255 return ret;
4258 static int write_update_refs_state(struct string_list *refs_to_oids)
4260 int result = 0;
4261 struct lock_file lock = LOCK_INIT;
4262 FILE *fp = NULL;
4263 struct string_list_item *item;
4264 char *path;
4266 path = rebase_path_update_refs(the_repository->gitdir);
4268 if (!refs_to_oids->nr) {
4269 if (unlink(path) && errno != ENOENT)
4270 result = error_errno(_("could not unlink: %s"), path);
4271 goto cleanup;
4274 if (safe_create_leading_directories(path)) {
4275 result = error(_("unable to create leading directories of %s"),
4276 path);
4277 goto cleanup;
4280 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4281 result = error(_("another 'rebase' process appears to be running; "
4282 "'%s.lock' already exists"),
4283 path);
4284 goto cleanup;
4287 fp = fdopen_lock_file(&lock, "w");
4288 if (!fp) {
4289 result = error_errno(_("could not open '%s' for writing"), path);
4290 rollback_lock_file(&lock);
4291 goto cleanup;
4294 for_each_string_list_item(item, refs_to_oids) {
4295 struct update_ref_record *rec = item->util;
4296 fprintf(fp, "%s\n%s\n%s\n", item->string,
4297 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4300 result = commit_lock_file(&lock);
4302 cleanup:
4303 free(path);
4304 return result;
4308 * Parse the update-refs file for the current rebase, then remove the
4309 * refs that do not appear in the todo_list (and have not had updated
4310 * values stored) and add refs that are in the todo_list but not
4311 * represented in the update-refs file.
4313 * If there are changes to the update-refs list, then write the new state
4314 * to disk.
4316 void todo_list_filter_update_refs(struct repository *r,
4317 struct todo_list *todo_list)
4319 int i;
4320 int updated = 0;
4321 struct string_list update_refs = STRING_LIST_INIT_DUP;
4323 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4326 * For each item in the update_refs list, if it has no updated
4327 * value and does not appear in the todo_list, then remove it
4328 * from the update_refs list.
4330 for (i = 0; i < update_refs.nr; i++) {
4331 int j;
4332 int found = 0;
4333 const char *ref = update_refs.items[i].string;
4334 size_t reflen = strlen(ref);
4335 struct update_ref_record *rec = update_refs.items[i].util;
4337 /* OID already stored as updated. */
4338 if (!is_null_oid(&rec->after))
4339 continue;
4341 for (j = 0; !found && j < todo_list->nr; j++) {
4342 struct todo_item *item = &todo_list->items[j];
4343 const char *arg = todo_list->buf.buf + item->arg_offset;
4345 if (item->command != TODO_UPDATE_REF)
4346 continue;
4348 if (item->arg_len != reflen ||
4349 strncmp(arg, ref, reflen))
4350 continue;
4352 found = 1;
4355 if (!found) {
4356 free(update_refs.items[i].string);
4357 free(update_refs.items[i].util);
4359 update_refs.nr--;
4360 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4362 updated = 1;
4363 i--;
4368 * For each todo_item, check if its ref is in the update_refs list.
4369 * If not, then add it as an un-updated ref.
4371 for (i = 0; i < todo_list->nr; i++) {
4372 struct todo_item *item = &todo_list->items[i];
4373 const char *arg = todo_list->buf.buf + item->arg_offset;
4374 int j, found = 0;
4376 if (item->command != TODO_UPDATE_REF)
4377 continue;
4379 for (j = 0; !found && j < update_refs.nr; j++) {
4380 const char *ref = update_refs.items[j].string;
4382 found = strlen(ref) == item->arg_len &&
4383 !strncmp(ref, arg, item->arg_len);
4386 if (!found) {
4387 struct string_list_item *inserted;
4388 struct strbuf argref = STRBUF_INIT;
4390 strbuf_add(&argref, arg, item->arg_len);
4391 inserted = string_list_insert(&update_refs, argref.buf);
4392 inserted->util = init_update_ref_record(argref.buf);
4393 strbuf_release(&argref);
4394 updated = 1;
4398 if (updated)
4399 write_update_refs_state(&update_refs);
4400 string_list_clear(&update_refs, 1);
4403 static int do_update_ref(struct repository *r, const char *refname)
4405 struct string_list_item *item;
4406 struct string_list list = STRING_LIST_INIT_DUP;
4408 if (sequencer_get_update_refs_state(r->gitdir, &list))
4409 return -1;
4411 for_each_string_list_item(item, &list) {
4412 if (!strcmp(item->string, refname)) {
4413 struct update_ref_record *rec = item->util;
4414 if (read_ref("HEAD", &rec->after))
4415 return -1;
4416 break;
4420 write_update_refs_state(&list);
4421 string_list_clear(&list, 1);
4422 return 0;
4425 static int do_update_refs(struct repository *r, int quiet)
4427 int res = 0;
4428 struct string_list_item *item;
4429 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4430 struct ref_store *refs = get_main_ref_store(r);
4431 struct strbuf update_msg = STRBUF_INIT;
4432 struct strbuf error_msg = STRBUF_INIT;
4434 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4435 return res;
4437 for_each_string_list_item(item, &refs_to_oids) {
4438 struct update_ref_record *rec = item->util;
4439 int loop_res;
4441 loop_res = refs_update_ref(refs, "rewritten during rebase",
4442 item->string,
4443 &rec->after, &rec->before,
4444 0, UPDATE_REFS_MSG_ON_ERR);
4445 res |= loop_res;
4447 if (quiet)
4448 continue;
4450 if (loop_res)
4451 strbuf_addf(&error_msg, "\t%s\n", item->string);
4452 else
4453 strbuf_addf(&update_msg, "\t%s\n", item->string);
4456 if (!quiet &&
4457 (update_msg.len || error_msg.len)) {
4458 fprintf(stderr,
4459 _("Updated the following refs with %s:\n%s"),
4460 "--update-refs",
4461 update_msg.buf);
4463 if (res)
4464 fprintf(stderr,
4465 _("Failed to update the following refs with %s:\n%s"),
4466 "--update-refs",
4467 error_msg.buf);
4470 string_list_clear(&refs_to_oids, 1);
4471 strbuf_release(&update_msg);
4472 strbuf_release(&error_msg);
4473 return res;
4476 static int is_final_fixup(struct todo_list *todo_list)
4478 int i = todo_list->current;
4480 if (!is_fixup(todo_list->items[i].command))
4481 return 0;
4483 while (++i < todo_list->nr)
4484 if (is_fixup(todo_list->items[i].command))
4485 return 0;
4486 else if (!is_noop(todo_list->items[i].command))
4487 break;
4488 return 1;
4491 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4493 int i;
4495 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4496 if (!is_noop(todo_list->items[i].command))
4497 return todo_list->items[i].command;
4499 return -1;
4502 static void create_autostash_internal(struct repository *r,
4503 const char *path,
4504 const char *refname)
4506 struct strbuf buf = STRBUF_INIT;
4507 struct lock_file lock_file = LOCK_INIT;
4508 int fd;
4510 if (path && refname)
4511 BUG("can only pass path or refname");
4513 fd = repo_hold_locked_index(r, &lock_file, 0);
4514 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4515 if (0 <= fd)
4516 repo_update_index_if_able(r, &lock_file);
4517 rollback_lock_file(&lock_file);
4519 if (has_unstaged_changes(r, 1) ||
4520 has_uncommitted_changes(r, 1)) {
4521 struct child_process stash = CHILD_PROCESS_INIT;
4522 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4523 struct object_id oid;
4525 strvec_pushl(&stash.args,
4526 "stash", "create", "autostash", NULL);
4527 stash.git_cmd = 1;
4528 stash.no_stdin = 1;
4529 strbuf_reset(&buf);
4530 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4531 die(_("Cannot autostash"));
4532 strbuf_trim_trailing_newline(&buf);
4533 if (repo_get_oid(r, buf.buf, &oid))
4534 die(_("Unexpected stash response: '%s'"),
4535 buf.buf);
4536 strbuf_reset(&buf);
4537 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4539 if (path) {
4540 if (safe_create_leading_directories_const(path))
4541 die(_("Could not create directory for '%s'"),
4542 path);
4543 write_file(path, "%s", oid_to_hex(&oid));
4544 } else {
4545 refs_update_ref(get_main_ref_store(r), "", refname,
4546 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4549 printf(_("Created autostash: %s\n"), buf.buf);
4550 if (reset_head(r, &ropts) < 0)
4551 die(_("could not reset --hard"));
4552 discard_index(r->index);
4553 if (repo_read_index(r) < 0)
4554 die(_("could not read index"));
4556 strbuf_release(&buf);
4559 void create_autostash(struct repository *r, const char *path)
4561 create_autostash_internal(r, path, NULL);
4564 void create_autostash_ref(struct repository *r, const char *refname)
4566 create_autostash_internal(r, NULL, refname);
4569 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4571 struct child_process child = CHILD_PROCESS_INIT;
4572 int ret = 0;
4574 if (attempt_apply) {
4575 child.git_cmd = 1;
4576 child.no_stdout = 1;
4577 child.no_stderr = 1;
4578 strvec_push(&child.args, "stash");
4579 strvec_push(&child.args, "apply");
4580 strvec_push(&child.args, stash_oid);
4581 ret = run_command(&child);
4584 if (attempt_apply && !ret)
4585 fprintf(stderr, _("Applied autostash.\n"));
4586 else {
4587 struct child_process store = CHILD_PROCESS_INIT;
4589 store.git_cmd = 1;
4590 strvec_push(&store.args, "stash");
4591 strvec_push(&store.args, "store");
4592 strvec_push(&store.args, "-m");
4593 strvec_push(&store.args, "autostash");
4594 strvec_push(&store.args, "-q");
4595 strvec_push(&store.args, stash_oid);
4596 if (run_command(&store))
4597 ret = error(_("cannot store %s"), stash_oid);
4598 else
4599 fprintf(stderr,
4600 _("%s\n"
4601 "Your changes are safe in the stash.\n"
4602 "You can run \"git stash pop\" or"
4603 " \"git stash drop\" at any time.\n"),
4604 attempt_apply ?
4605 _("Applying autostash resulted in conflicts.") :
4606 _("Autostash exists; creating a new stash entry."));
4609 return ret;
4612 static int apply_save_autostash(const char *path, int attempt_apply)
4614 struct strbuf stash_oid = STRBUF_INIT;
4615 int ret = 0;
4617 if (!read_oneliner(&stash_oid, path,
4618 READ_ONELINER_SKIP_IF_EMPTY)) {
4619 strbuf_release(&stash_oid);
4620 return 0;
4622 strbuf_trim(&stash_oid);
4624 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4626 unlink(path);
4627 strbuf_release(&stash_oid);
4628 return ret;
4631 int save_autostash(const char *path)
4633 return apply_save_autostash(path, 0);
4636 int apply_autostash(const char *path)
4638 return apply_save_autostash(path, 1);
4641 int apply_autostash_oid(const char *stash_oid)
4643 return apply_save_autostash_oid(stash_oid, 1);
4646 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4647 int attempt_apply)
4649 struct object_id stash_oid;
4650 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4651 int flag, ret;
4653 if (!refs_ref_exists(get_main_ref_store(r), refname))
4654 return 0;
4656 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4657 RESOLVE_REF_READING, &stash_oid, &flag))
4658 return -1;
4659 if (flag & REF_ISSYMREF)
4660 return error(_("autostash reference is a symref"));
4662 oid_to_hex_r(stash_oid_hex, &stash_oid);
4663 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4665 refs_delete_ref(get_main_ref_store(r), "", refname,
4666 &stash_oid, REF_NO_DEREF);
4668 return ret;
4671 int save_autostash_ref(struct repository *r, const char *refname)
4673 return apply_save_autostash_ref(r, refname, 0);
4676 int apply_autostash_ref(struct repository *r, const char *refname)
4678 return apply_save_autostash_ref(r, refname, 1);
4681 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4682 const char *onto_name, const struct object_id *onto,
4683 const struct object_id *orig_head)
4685 struct reset_head_opts ropts = {
4686 .oid = onto,
4687 .orig_head = orig_head,
4688 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4689 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4690 .head_msg = reflog_message(opts, "start", "checkout %s",
4691 onto_name),
4692 .default_reflog_action = sequencer_reflog_action(opts)
4694 if (reset_head(r, &ropts)) {
4695 apply_autostash(rebase_path_autostash());
4696 sequencer_remove_state(opts);
4697 return error(_("could not detach HEAD"));
4700 return 0;
4703 static int stopped_at_head(struct repository *r)
4705 struct object_id head;
4706 struct commit *commit;
4707 struct commit_message message;
4709 if (repo_get_oid(r, "HEAD", &head) ||
4710 !(commit = lookup_commit(r, &head)) ||
4711 repo_parse_commit(r, commit) || get_message(commit, &message))
4712 fprintf(stderr, _("Stopped at HEAD\n"));
4713 else {
4714 fprintf(stderr, _("Stopped at %s\n"), message.label);
4715 free_message(commit, &message);
4717 return 0;
4721 static int reread_todo_if_changed(struct repository *r,
4722 struct todo_list *todo_list,
4723 struct replay_opts *opts)
4725 int offset;
4726 struct strbuf buf = STRBUF_INIT;
4728 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4729 return -1;
4730 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4731 if (buf.len != todo_list->buf.len - offset ||
4732 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4733 /* Reread the todo file if it has changed. */
4734 todo_list_release(todo_list);
4735 if (read_populate_todo(r, todo_list, opts))
4736 return -1; /* message was printed */
4737 /* `current` will be incremented on return */
4738 todo_list->current = -1;
4740 strbuf_release(&buf);
4742 return 0;
4745 static const char rescheduled_advice[] =
4746 N_("Could not execute the todo command\n"
4747 "\n"
4748 " %.*s"
4749 "\n"
4750 "It has been rescheduled; To edit the command before continuing, please\n"
4751 "edit the todo list first:\n"
4752 "\n"
4753 " git rebase --edit-todo\n"
4754 " git rebase --continue\n");
4756 static int pick_one_commit(struct repository *r,
4757 struct todo_list *todo_list,
4758 struct replay_opts *opts,
4759 int *check_todo, int* reschedule)
4761 int res;
4762 struct todo_item *item = todo_list->items + todo_list->current;
4763 const char *arg = todo_item_get_arg(todo_list, item);
4764 if (is_rebase_i(opts))
4765 opts->reflog_message = reflog_message(
4766 opts, command_to_string(item->command), NULL);
4768 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4769 check_todo);
4770 if (is_rebase_i(opts) && res < 0) {
4771 /* Reschedule */
4772 *reschedule = 1;
4773 return -1;
4775 if (item->command == TODO_EDIT) {
4776 struct commit *commit = item->commit;
4777 if (!res) {
4778 if (!opts->verbose)
4779 term_clear_line();
4780 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4781 short_commit_name(r, commit), item->arg_len, arg);
4783 return error_with_patch(r, commit,
4784 arg, item->arg_len, opts, res, !res);
4786 if (is_rebase_i(opts) && !res)
4787 record_in_rewritten(&item->commit->object.oid,
4788 peek_command(todo_list, 1));
4789 if (res && is_fixup(item->command)) {
4790 if (res == 1)
4791 intend_to_amend();
4792 return error_failed_squash(r, item->commit, opts,
4793 item->arg_len, arg);
4794 } else if (res && is_rebase_i(opts) && item->commit) {
4795 int to_amend = 0;
4796 struct object_id oid;
4799 * If we are rewording and have either
4800 * fast-forwarded already, or are about to
4801 * create a new root commit, we want to amend,
4802 * otherwise we do not.
4804 if (item->command == TODO_REWORD &&
4805 !repo_get_oid(r, "HEAD", &oid) &&
4806 (oideq(&item->commit->object.oid, &oid) ||
4807 (opts->have_squash_onto &&
4808 oideq(&opts->squash_onto, &oid))))
4809 to_amend = 1;
4811 return res | error_with_patch(r, item->commit,
4812 arg, item->arg_len, opts,
4813 res, to_amend);
4815 return res;
4818 static int pick_commits(struct repository *r,
4819 struct todo_list *todo_list,
4820 struct replay_opts *opts)
4822 int res = 0, reschedule = 0;
4824 opts->reflog_message = sequencer_reflog_action(opts);
4825 if (opts->allow_ff)
4826 assert(!(opts->signoff || opts->no_commit ||
4827 opts->record_origin || should_edit(opts) ||
4828 opts->committer_date_is_author_date ||
4829 opts->ignore_date));
4830 if (read_and_refresh_cache(r, opts))
4831 return -1;
4833 unlink(rebase_path_message());
4834 unlink(rebase_path_stopped_sha());
4835 unlink(rebase_path_amend());
4836 unlink(rebase_path_patch());
4838 while (todo_list->current < todo_list->nr) {
4839 struct todo_item *item = todo_list->items + todo_list->current;
4840 const char *arg = todo_item_get_arg(todo_list, item);
4841 int check_todo = 0;
4843 if (save_todo(todo_list, opts, reschedule))
4844 return -1;
4845 if (is_rebase_i(opts)) {
4846 if (item->command != TODO_COMMENT) {
4847 FILE *f = fopen(rebase_path_msgnum(), "w");
4849 todo_list->done_nr++;
4851 if (f) {
4852 fprintf(f, "%d\n", todo_list->done_nr);
4853 fclose(f);
4855 if (!opts->quiet)
4856 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4857 todo_list->done_nr,
4858 todo_list->total_nr,
4859 opts->verbose ? "\n" : "\r");
4861 unlink(rebase_path_author_script());
4862 unlink(git_path_merge_head(r));
4863 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4864 NULL, REF_NO_DEREF);
4865 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4866 NULL, REF_NO_DEREF);
4868 if (item->command == TODO_BREAK) {
4869 if (!opts->verbose)
4870 term_clear_line();
4871 return stopped_at_head(r);
4874 if (item->command <= TODO_SQUASH) {
4875 res = pick_one_commit(r, todo_list, opts, &check_todo,
4876 &reschedule);
4877 if (!res && item->command == TODO_EDIT)
4878 return 0;
4879 } else if (item->command == TODO_EXEC) {
4880 char *end_of_arg = (char *)(arg + item->arg_len);
4881 int saved = *end_of_arg;
4883 if (!opts->verbose)
4884 term_clear_line();
4885 *end_of_arg = '\0';
4886 res = do_exec(r, arg);
4887 *end_of_arg = saved;
4889 if (res) {
4890 if (opts->reschedule_failed_exec)
4891 reschedule = 1;
4893 check_todo = 1;
4894 } else if (item->command == TODO_LABEL) {
4895 if ((res = do_label(r, arg, item->arg_len)))
4896 reschedule = 1;
4897 } else if (item->command == TODO_RESET) {
4898 if ((res = do_reset(r, arg, item->arg_len, opts)))
4899 reschedule = 1;
4900 } else if (item->command == TODO_MERGE) {
4901 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4902 item->flags, &check_todo, opts)) < 0)
4903 reschedule = 1;
4904 else if (item->commit)
4905 record_in_rewritten(&item->commit->object.oid,
4906 peek_command(todo_list, 1));
4907 if (res > 0)
4908 /* failed with merge conflicts */
4909 return error_with_patch(r, item->commit,
4910 arg, item->arg_len,
4911 opts, res, 0);
4912 } else if (item->command == TODO_UPDATE_REF) {
4913 struct strbuf ref = STRBUF_INIT;
4914 strbuf_add(&ref, arg, item->arg_len);
4915 if ((res = do_update_ref(r, ref.buf)))
4916 reschedule = 1;
4917 strbuf_release(&ref);
4918 } else if (!is_noop(item->command))
4919 return error(_("unknown command %d"), item->command);
4921 if (reschedule) {
4922 advise(_(rescheduled_advice),
4923 get_item_line_length(todo_list,
4924 todo_list->current),
4925 get_item_line(todo_list, todo_list->current));
4926 if (save_todo(todo_list, opts, reschedule))
4927 return -1;
4928 if (item->commit)
4929 write_rebase_head(&item->commit->object.oid);
4930 } else if (is_rebase_i(opts) && check_todo && !res &&
4931 reread_todo_if_changed(r, todo_list, opts)) {
4932 return -1;
4935 if (res)
4936 return res;
4938 todo_list->current++;
4941 if (is_rebase_i(opts)) {
4942 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4943 struct stat st;
4945 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4946 starts_with(head_ref.buf, "refs/")) {
4947 const char *msg;
4948 struct object_id head, orig;
4949 int res;
4951 if (repo_get_oid(r, "HEAD", &head)) {
4952 res = error(_("cannot read HEAD"));
4953 cleanup_head_ref:
4954 strbuf_release(&head_ref);
4955 strbuf_release(&buf);
4956 return res;
4958 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4959 get_oid_hex(buf.buf, &orig)) {
4960 res = error(_("could not read orig-head"));
4961 goto cleanup_head_ref;
4963 strbuf_reset(&buf);
4964 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4965 res = error(_("could not read 'onto'"));
4966 goto cleanup_head_ref;
4968 msg = reflog_message(opts, "finish", "%s onto %s",
4969 head_ref.buf, buf.buf);
4970 if (update_ref(msg, head_ref.buf, &head, &orig,
4971 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4972 res = error(_("could not update %s"),
4973 head_ref.buf);
4974 goto cleanup_head_ref;
4976 msg = reflog_message(opts, "finish", "returning to %s",
4977 head_ref.buf);
4978 if (create_symref("HEAD", head_ref.buf, msg)) {
4979 res = error(_("could not update HEAD to %s"),
4980 head_ref.buf);
4981 goto cleanup_head_ref;
4983 strbuf_reset(&buf);
4986 if (opts->verbose) {
4987 struct rev_info log_tree_opt;
4988 struct object_id orig, head;
4990 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4991 repo_init_revisions(r, &log_tree_opt, NULL);
4992 log_tree_opt.diff = 1;
4993 log_tree_opt.diffopt.output_format =
4994 DIFF_FORMAT_DIFFSTAT;
4995 log_tree_opt.disable_stdin = 1;
4997 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4998 !repo_get_oid(r, buf.buf, &orig) &&
4999 !repo_get_oid(r, "HEAD", &head)) {
5000 diff_tree_oid(&orig, &head, "",
5001 &log_tree_opt.diffopt);
5002 log_tree_diff_flush(&log_tree_opt);
5004 release_revisions(&log_tree_opt);
5006 flush_rewritten_pending();
5007 if (!stat(rebase_path_rewritten_list(), &st) &&
5008 st.st_size > 0) {
5009 struct child_process child = CHILD_PROCESS_INIT;
5010 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5012 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5013 child.git_cmd = 1;
5014 strvec_push(&child.args, "notes");
5015 strvec_push(&child.args, "copy");
5016 strvec_push(&child.args, "--for-rewrite=rebase");
5017 /* we don't care if this copying failed */
5018 run_command(&child);
5020 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5021 strvec_push(&hook_opt.args, "rebase");
5022 run_hooks_opt("post-rewrite", &hook_opt);
5024 apply_autostash(rebase_path_autostash());
5026 if (!opts->quiet) {
5027 if (!opts->verbose)
5028 term_clear_line();
5029 fprintf(stderr,
5030 _("Successfully rebased and updated %s.\n"),
5031 head_ref.buf);
5034 strbuf_release(&buf);
5035 strbuf_release(&head_ref);
5037 if (do_update_refs(r, opts->quiet))
5038 return -1;
5042 * Sequence of picks finished successfully; cleanup by
5043 * removing the .git/sequencer directory
5045 return sequencer_remove_state(opts);
5048 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5050 struct child_process cmd = CHILD_PROCESS_INIT;
5052 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5053 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5054 return error(_("no cherry-pick or revert in progress"));
5056 cmd.git_cmd = 1;
5057 strvec_push(&cmd.args, "commit");
5060 * continue_single_pick() handles the case of recovering from a
5061 * conflict. should_edit() doesn't handle that case; for a conflict,
5062 * we want to edit if the user asked for it, or if they didn't specify
5063 * and stdin is a tty.
5065 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5067 * Include --cleanup=strip as well because we don't want the
5068 * "# Conflicts:" messages.
5070 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5072 return run_command(&cmd);
5075 static int commit_staged_changes(struct repository *r,
5076 struct replay_opts *opts,
5077 struct todo_list *todo_list)
5079 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5080 unsigned int final_fixup = 0, is_clean;
5082 if (has_unstaged_changes(r, 1))
5083 return error(_("cannot rebase: You have unstaged changes."));
5085 is_clean = !has_uncommitted_changes(r, 0);
5087 if (!is_clean && !file_exists(rebase_path_message())) {
5088 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5090 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5092 if (file_exists(rebase_path_amend())) {
5093 struct strbuf rev = STRBUF_INIT;
5094 struct object_id head, to_amend;
5096 if (repo_get_oid(r, "HEAD", &head))
5097 return error(_("cannot amend non-existing commit"));
5098 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5099 return error(_("invalid file: '%s'"), rebase_path_amend());
5100 if (get_oid_hex(rev.buf, &to_amend))
5101 return error(_("invalid contents: '%s'"),
5102 rebase_path_amend());
5103 if (!is_clean && !oideq(&head, &to_amend))
5104 return error(_("\nYou have uncommitted changes in your "
5105 "working tree. Please, commit them\n"
5106 "first and then run 'git rebase "
5107 "--continue' again."));
5109 * When skipping a failed fixup/squash, we need to edit the
5110 * commit message, the current fixup list and count, and if it
5111 * was the last fixup/squash in the chain, we need to clean up
5112 * the commit message and if there was a squash, let the user
5113 * edit it.
5115 if (!is_clean || !opts->current_fixup_count)
5116 ; /* this is not the final fixup */
5117 else if (!oideq(&head, &to_amend) ||
5118 !file_exists(rebase_path_stopped_sha())) {
5119 /* was a final fixup or squash done manually? */
5120 if (!is_fixup(peek_command(todo_list, 0))) {
5121 unlink(rebase_path_fixup_msg());
5122 unlink(rebase_path_squash_msg());
5123 unlink(rebase_path_current_fixups());
5124 strbuf_reset(&opts->current_fixups);
5125 opts->current_fixup_count = 0;
5127 } else {
5128 /* we are in a fixup/squash chain */
5129 const char *p = opts->current_fixups.buf;
5130 int len = opts->current_fixups.len;
5132 opts->current_fixup_count--;
5133 if (!len)
5134 BUG("Incorrect current_fixups:\n%s", p);
5135 while (len && p[len - 1] != '\n')
5136 len--;
5137 strbuf_setlen(&opts->current_fixups, len);
5138 if (write_message(p, len, rebase_path_current_fixups(),
5139 0) < 0)
5140 return error(_("could not write file: '%s'"),
5141 rebase_path_current_fixups());
5144 * If a fixup/squash in a fixup/squash chain failed, the
5145 * commit message is already correct, no need to commit
5146 * it again.
5148 * Only if it is the final command in the fixup/squash
5149 * chain, and only if the chain is longer than a single
5150 * fixup/squash command (which was just skipped), do we
5151 * actually need to re-commit with a cleaned up commit
5152 * message.
5154 if (opts->current_fixup_count > 0 &&
5155 !is_fixup(peek_command(todo_list, 0))) {
5156 final_fixup = 1;
5158 * If there was not a single "squash" in the
5159 * chain, we only need to clean up the commit
5160 * message, no need to bother the user with
5161 * opening the commit message in the editor.
5163 if (!starts_with(p, "squash ") &&
5164 !strstr(p, "\nsquash "))
5165 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5166 } else if (is_fixup(peek_command(todo_list, 0))) {
5168 * We need to update the squash message to skip
5169 * the latest commit message.
5171 int res = 0;
5172 struct commit *commit;
5173 const char *msg;
5174 const char *path = rebase_path_squash_msg();
5175 const char *encoding = get_commit_output_encoding();
5177 if (parse_head(r, &commit))
5178 return error(_("could not parse HEAD"));
5180 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5181 if (!p) {
5182 res = error(_("could not parse commit %s"),
5183 oid_to_hex(&commit->object.oid));
5184 goto unuse_commit_buffer;
5186 find_commit_subject(p, &msg);
5187 if (write_message(msg, strlen(msg), path, 0)) {
5188 res = error(_("could not write file: "
5189 "'%s'"), path);
5190 goto unuse_commit_buffer;
5192 unuse_commit_buffer:
5193 repo_unuse_commit_buffer(r, commit, p);
5194 if (res)
5195 return res;
5199 strbuf_release(&rev);
5200 flags |= AMEND_MSG;
5203 if (is_clean) {
5204 if (refs_ref_exists(get_main_ref_store(r),
5205 "CHERRY_PICK_HEAD") &&
5206 refs_delete_ref(get_main_ref_store(r), "",
5207 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5208 return error(_("could not remove CHERRY_PICK_HEAD"));
5209 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5210 return error_errno(_("could not remove '%s'"),
5211 git_path_merge_msg(r));
5212 if (!final_fixup)
5213 return 0;
5216 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5217 opts, flags))
5218 return error(_("could not commit staged changes."));
5219 unlink(rebase_path_amend());
5220 unlink(git_path_merge_head(r));
5221 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5222 NULL, REF_NO_DEREF);
5223 if (final_fixup) {
5224 unlink(rebase_path_fixup_msg());
5225 unlink(rebase_path_squash_msg());
5227 if (opts->current_fixup_count > 0) {
5229 * Whether final fixup or not, we just cleaned up the commit
5230 * message...
5232 unlink(rebase_path_current_fixups());
5233 strbuf_reset(&opts->current_fixups);
5234 opts->current_fixup_count = 0;
5236 return 0;
5239 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5241 struct todo_list todo_list = TODO_LIST_INIT;
5242 int res;
5244 if (read_and_refresh_cache(r, opts))
5245 return -1;
5247 if (read_populate_opts(opts))
5248 return -1;
5249 if (is_rebase_i(opts)) {
5250 if ((res = read_populate_todo(r, &todo_list, opts)))
5251 goto release_todo_list;
5253 if (file_exists(rebase_path_dropped())) {
5254 if ((res = todo_list_check_against_backup(r, &todo_list)))
5255 goto release_todo_list;
5257 unlink(rebase_path_dropped());
5260 opts->reflog_message = reflog_message(opts, "continue", NULL);
5261 if (commit_staged_changes(r, opts, &todo_list)) {
5262 res = -1;
5263 goto release_todo_list;
5265 } else if (!file_exists(get_todo_path(opts)))
5266 return continue_single_pick(r, opts);
5267 else if ((res = read_populate_todo(r, &todo_list, opts)))
5268 goto release_todo_list;
5270 if (!is_rebase_i(opts)) {
5271 /* Verify that the conflict has been resolved */
5272 if (refs_ref_exists(get_main_ref_store(r),
5273 "CHERRY_PICK_HEAD") ||
5274 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5275 res = continue_single_pick(r, opts);
5276 if (res)
5277 goto release_todo_list;
5279 if (index_differs_from(r, "HEAD", NULL, 0)) {
5280 res = error_dirty_index(r, opts);
5281 goto release_todo_list;
5283 todo_list.current++;
5284 } else if (file_exists(rebase_path_stopped_sha())) {
5285 struct strbuf buf = STRBUF_INIT;
5286 struct object_id oid;
5288 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5289 READ_ONELINER_SKIP_IF_EMPTY) &&
5290 !get_oid_hex(buf.buf, &oid))
5291 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5292 strbuf_release(&buf);
5295 res = pick_commits(r, &todo_list, opts);
5296 release_todo_list:
5297 todo_list_release(&todo_list);
5298 return res;
5301 static int single_pick(struct repository *r,
5302 struct commit *cmit,
5303 struct replay_opts *opts)
5305 int check_todo;
5306 struct todo_item item;
5308 item.command = opts->action == REPLAY_PICK ?
5309 TODO_PICK : TODO_REVERT;
5310 item.commit = cmit;
5312 opts->reflog_message = sequencer_reflog_action(opts);
5313 return do_pick_commit(r, &item, opts, 0, &check_todo);
5316 int sequencer_pick_revisions(struct repository *r,
5317 struct replay_opts *opts)
5319 struct todo_list todo_list = TODO_LIST_INIT;
5320 struct object_id oid;
5321 int i, res;
5323 assert(opts->revs);
5324 if (read_and_refresh_cache(r, opts))
5325 return -1;
5327 for (i = 0; i < opts->revs->pending.nr; i++) {
5328 struct object_id oid;
5329 const char *name = opts->revs->pending.objects[i].name;
5331 /* This happens when using --stdin. */
5332 if (!strlen(name))
5333 continue;
5335 if (!repo_get_oid(r, name, &oid)) {
5336 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5337 enum object_type type = oid_object_info(r,
5338 &oid,
5339 NULL);
5340 return error(_("%s: can't cherry-pick a %s"),
5341 name, type_name(type));
5343 } else
5344 return error(_("%s: bad revision"), name);
5348 * If we were called as "git cherry-pick <commit>", just
5349 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5350 * REVERT_HEAD, and don't touch the sequencer state.
5351 * This means it is possible to cherry-pick in the middle
5352 * of a cherry-pick sequence.
5354 if (opts->revs->cmdline.nr == 1 &&
5355 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5356 opts->revs->no_walk &&
5357 !opts->revs->cmdline.rev->flags) {
5358 struct commit *cmit;
5359 if (prepare_revision_walk(opts->revs))
5360 return error(_("revision walk setup failed"));
5361 cmit = get_revision(opts->revs);
5362 if (!cmit)
5363 return error(_("empty commit set passed"));
5364 if (get_revision(opts->revs))
5365 BUG("unexpected extra commit from walk");
5366 return single_pick(r, cmit, opts);
5370 * Start a new cherry-pick/ revert sequence; but
5371 * first, make sure that an existing one isn't in
5372 * progress
5375 if (walk_revs_populate_todo(&todo_list, opts) ||
5376 create_seq_dir(r) < 0)
5377 return -1;
5378 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5379 return error(_("can't revert as initial commit"));
5380 if (save_head(oid_to_hex(&oid)))
5381 return -1;
5382 if (save_opts(opts))
5383 return -1;
5384 update_abort_safety_file();
5385 res = pick_commits(r, &todo_list, opts);
5386 todo_list_release(&todo_list);
5387 return res;
5390 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5392 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5393 struct strbuf sob = STRBUF_INIT;
5394 int has_footer;
5396 strbuf_addstr(&sob, sign_off_header);
5397 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5398 strbuf_addch(&sob, '\n');
5400 if (!ignore_footer)
5401 strbuf_complete_line(msgbuf);
5404 * If the whole message buffer is equal to the sob, pretend that we
5405 * found a conforming footer with a matching sob
5407 if (msgbuf->len - ignore_footer == sob.len &&
5408 !strncmp(msgbuf->buf, sob.buf, sob.len))
5409 has_footer = 3;
5410 else
5411 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5413 if (!has_footer) {
5414 const char *append_newlines = NULL;
5415 size_t len = msgbuf->len - ignore_footer;
5417 if (!len) {
5419 * The buffer is completely empty. Leave foom for
5420 * the title and body to be filled in by the user.
5422 append_newlines = "\n\n";
5423 } else if (len == 1) {
5425 * Buffer contains a single newline. Add another
5426 * so that we leave room for the title and body.
5428 append_newlines = "\n";
5429 } else if (msgbuf->buf[len - 2] != '\n') {
5431 * Buffer ends with a single newline. Add another
5432 * so that there is an empty line between the message
5433 * body and the sob.
5435 append_newlines = "\n";
5436 } /* else, the buffer already ends with two newlines. */
5438 if (append_newlines)
5439 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5440 append_newlines, strlen(append_newlines));
5443 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5444 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5445 sob.buf, sob.len);
5447 strbuf_release(&sob);
5450 struct labels_entry {
5451 struct hashmap_entry entry;
5452 char label[FLEX_ARRAY];
5455 static int labels_cmp(const void *fndata UNUSED,
5456 const struct hashmap_entry *eptr,
5457 const struct hashmap_entry *entry_or_key, const void *key)
5459 const struct labels_entry *a, *b;
5461 a = container_of(eptr, const struct labels_entry, entry);
5462 b = container_of(entry_or_key, const struct labels_entry, entry);
5464 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5467 struct string_entry {
5468 struct oidmap_entry entry;
5469 char string[FLEX_ARRAY];
5472 struct label_state {
5473 struct oidmap commit2label;
5474 struct hashmap labels;
5475 struct strbuf buf;
5476 int max_label_length;
5479 static const char *label_oid(struct object_id *oid, const char *label,
5480 struct label_state *state)
5482 struct labels_entry *labels_entry;
5483 struct string_entry *string_entry;
5484 struct object_id dummy;
5485 int i;
5487 string_entry = oidmap_get(&state->commit2label, oid);
5488 if (string_entry)
5489 return string_entry->string;
5492 * For "uninteresting" commits, i.e. commits that are not to be
5493 * rebased, and which can therefore not be labeled, we use a unique
5494 * abbreviation of the commit name. This is slightly more complicated
5495 * than calling repo_find_unique_abbrev() because we also need to make
5496 * sure that the abbreviation does not conflict with any other
5497 * label.
5499 * We disallow "interesting" commits to be labeled by a string that
5500 * is a valid full-length hash, to ensure that we always can find an
5501 * abbreviation for any uninteresting commit's names that does not
5502 * clash with any other label.
5504 strbuf_reset(&state->buf);
5505 if (!label) {
5506 char *p;
5508 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5509 label = p = state->buf.buf;
5511 repo_find_unique_abbrev_r(the_repository, p, oid,
5512 default_abbrev);
5515 * We may need to extend the abbreviated hash so that there is
5516 * no conflicting label.
5518 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5519 size_t i = strlen(p) + 1;
5521 oid_to_hex_r(p, oid);
5522 for (; i < the_hash_algo->hexsz; i++) {
5523 char save = p[i];
5524 p[i] = '\0';
5525 if (!hashmap_get_from_hash(&state->labels,
5526 strihash(p), p))
5527 break;
5528 p[i] = save;
5531 } else {
5532 struct strbuf *buf = &state->buf;
5533 int label_is_utf8 = 1; /* start with this assumption */
5534 size_t max_len = buf->len + state->max_label_length;
5537 * Sanitize labels by replacing non-alpha-numeric characters
5538 * (including white-space ones) by dashes, as they might be
5539 * illegal in file names (and hence in ref names).
5541 * Note that we retain non-ASCII UTF-8 characters (identified
5542 * via the most significant bit). They should be all acceptable
5543 * in file names.
5545 * As we will use the labels as names of (loose) refs, it is
5546 * vital that the name not be longer than the maximum component
5547 * size of the file system (`NAME_MAX`). We are careful to
5548 * truncate the label accordingly, allowing for the `.lock`
5549 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5550 * truncating in the middle of a character).
5552 for (; *label && buf->len + 1 < max_len; label++)
5553 if (isalnum(*label) ||
5554 (!label_is_utf8 && (*label & 0x80)))
5555 strbuf_addch(buf, *label);
5556 else if (*label & 0x80) {
5557 const char *p = label;
5559 utf8_width(&p, NULL);
5560 if (p) {
5561 if (buf->len + (p - label) > max_len)
5562 break;
5563 strbuf_add(buf, label, p - label);
5564 label = p - 1;
5565 } else {
5566 label_is_utf8 = 0;
5567 strbuf_addch(buf, *label);
5569 /* avoid leading dash and double-dashes */
5570 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5571 strbuf_addch(buf, '-');
5572 if (!buf->len) {
5573 strbuf_addstr(buf, "rev-");
5574 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5576 label = buf->buf;
5578 if ((buf->len == the_hash_algo->hexsz &&
5579 !get_oid_hex(label, &dummy)) ||
5580 (buf->len == 1 && *label == '#') ||
5581 hashmap_get_from_hash(&state->labels,
5582 strihash(label), label)) {
5584 * If the label already exists, or if the label is a
5585 * valid full OID, or the label is a '#' (which we use
5586 * as a separator between merge heads and oneline), we
5587 * append a dash and a number to make it unique.
5589 size_t len = buf->len;
5591 for (i = 2; ; i++) {
5592 strbuf_setlen(buf, len);
5593 strbuf_addf(buf, "-%d", i);
5594 if (!hashmap_get_from_hash(&state->labels,
5595 strihash(buf->buf),
5596 buf->buf))
5597 break;
5600 label = buf->buf;
5604 FLEX_ALLOC_STR(labels_entry, label, label);
5605 hashmap_entry_init(&labels_entry->entry, strihash(label));
5606 hashmap_add(&state->labels, &labels_entry->entry);
5608 FLEX_ALLOC_STR(string_entry, string, label);
5609 oidcpy(&string_entry->entry.oid, oid);
5610 oidmap_put(&state->commit2label, string_entry);
5612 return string_entry->string;
5615 static int make_script_with_merges(struct pretty_print_context *pp,
5616 struct rev_info *revs, struct strbuf *out,
5617 unsigned flags)
5619 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5620 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5621 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5622 int skipped_commit = 0;
5623 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5624 struct strbuf label = STRBUF_INIT;
5625 struct commit_list *commits = NULL, **tail = &commits, *iter;
5626 struct commit_list *tips = NULL, **tips_tail = &tips;
5627 struct commit *commit;
5628 struct oidmap commit2todo = OIDMAP_INIT;
5629 struct string_entry *entry;
5630 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5631 shown = OIDSET_INIT;
5632 struct label_state state =
5633 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5635 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5636 const char *cmd_pick = abbr ? "p" : "pick",
5637 *cmd_label = abbr ? "l" : "label",
5638 *cmd_reset = abbr ? "t" : "reset",
5639 *cmd_merge = abbr ? "m" : "merge";
5641 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5643 oidmap_init(&commit2todo, 0);
5644 oidmap_init(&state.commit2label, 0);
5645 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5646 strbuf_init(&state.buf, 32);
5648 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5649 struct labels_entry *onto_label_entry;
5650 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5651 FLEX_ALLOC_STR(entry, string, "onto");
5652 oidcpy(&entry->entry.oid, oid);
5653 oidmap_put(&state.commit2label, entry);
5655 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5656 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5657 hashmap_add(&state.labels, &onto_label_entry->entry);
5661 * First phase:
5662 * - get onelines for all commits
5663 * - gather all branch tips (i.e. 2nd or later parents of merges)
5664 * - label all branch tips
5666 while ((commit = get_revision(revs))) {
5667 struct commit_list *to_merge;
5668 const char *p1, *p2;
5669 struct object_id *oid;
5670 int is_empty;
5672 tail = &commit_list_insert(commit, tail)->next;
5673 oidset_insert(&interesting, &commit->object.oid);
5675 is_empty = is_original_commit_empty(commit);
5676 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5677 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5678 warning(_("skipped previously applied commit %s"),
5679 short_commit_name(the_repository, commit));
5680 skipped_commit = 1;
5681 continue;
5683 if (is_empty && !keep_empty)
5684 continue;
5686 strbuf_reset(&oneline);
5687 pretty_print_commit(pp, commit, &oneline);
5689 to_merge = commit->parents ? commit->parents->next : NULL;
5690 if (!to_merge) {
5691 /* non-merge commit: easy case */
5692 strbuf_reset(&buf);
5693 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5694 oid_to_hex(&commit->object.oid),
5695 oneline.buf);
5696 if (is_empty)
5697 strbuf_addf(&buf, " %s empty",
5698 comment_line_str);
5700 FLEX_ALLOC_STR(entry, string, buf.buf);
5701 oidcpy(&entry->entry.oid, &commit->object.oid);
5702 oidmap_put(&commit2todo, entry);
5704 continue;
5707 /* Create a label */
5708 strbuf_reset(&label);
5709 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5710 (p1 = strchr(p1, '\'')) &&
5711 (p2 = strchr(++p1, '\'')))
5712 strbuf_add(&label, p1, p2 - p1);
5713 else if (skip_prefix(oneline.buf, "Merge pull request ",
5714 &p1) &&
5715 (p1 = strstr(p1, " from ")))
5716 strbuf_addstr(&label, p1 + strlen(" from "));
5717 else
5718 strbuf_addbuf(&label, &oneline);
5720 strbuf_reset(&buf);
5721 strbuf_addf(&buf, "%s -C %s",
5722 cmd_merge, oid_to_hex(&commit->object.oid));
5724 /* label the tips of merged branches */
5725 for (; to_merge; to_merge = to_merge->next) {
5726 oid = &to_merge->item->object.oid;
5727 strbuf_addch(&buf, ' ');
5729 if (!oidset_contains(&interesting, oid)) {
5730 strbuf_addstr(&buf, label_oid(oid, NULL,
5731 &state));
5732 continue;
5735 tips_tail = &commit_list_insert(to_merge->item,
5736 tips_tail)->next;
5738 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5740 strbuf_addf(&buf, " # %s", oneline.buf);
5742 FLEX_ALLOC_STR(entry, string, buf.buf);
5743 oidcpy(&entry->entry.oid, &commit->object.oid);
5744 oidmap_put(&commit2todo, entry);
5746 if (skipped_commit)
5747 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5748 _("use --reapply-cherry-picks to include skipped commits"));
5751 * Second phase:
5752 * - label branch points
5753 * - add HEAD to the branch tips
5755 for (iter = commits; iter; iter = iter->next) {
5756 struct commit_list *parent = iter->item->parents;
5757 for (; parent; parent = parent->next) {
5758 struct object_id *oid = &parent->item->object.oid;
5759 if (!oidset_contains(&interesting, oid))
5760 continue;
5761 if (oidset_insert(&child_seen, oid))
5762 label_oid(oid, "branch-point", &state);
5765 /* Add HEAD as implicit "tip of branch" */
5766 if (!iter->next)
5767 tips_tail = &commit_list_insert(iter->item,
5768 tips_tail)->next;
5772 * Third phase: output the todo list. This is a bit tricky, as we
5773 * want to avoid jumping back and forth between revisions. To
5774 * accomplish that goal, we walk backwards from the branch tips,
5775 * gathering commits not yet shown, reversing the list on the fly,
5776 * then outputting that list (labeling revisions as needed).
5778 strbuf_addf(out, "%s onto\n", cmd_label);
5779 for (iter = tips; iter; iter = iter->next) {
5780 struct commit_list *list = NULL, *iter2;
5782 commit = iter->item;
5783 if (oidset_contains(&shown, &commit->object.oid))
5784 continue;
5785 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5787 if (entry)
5788 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
5789 else
5790 strbuf_addch(out, '\n');
5792 while (oidset_contains(&interesting, &commit->object.oid) &&
5793 !oidset_contains(&shown, &commit->object.oid)) {
5794 commit_list_insert(commit, &list);
5795 if (!commit->parents) {
5796 commit = NULL;
5797 break;
5799 commit = commit->parents->item;
5802 if (!commit)
5803 strbuf_addf(out, "%s %s\n", cmd_reset,
5804 rebase_cousins || root_with_onto ?
5805 "onto" : "[new root]");
5806 else {
5807 const char *to = NULL;
5809 entry = oidmap_get(&state.commit2label,
5810 &commit->object.oid);
5811 if (entry)
5812 to = entry->string;
5813 else if (!rebase_cousins)
5814 to = label_oid(&commit->object.oid, NULL,
5815 &state);
5817 if (!to || !strcmp(to, "onto"))
5818 strbuf_addf(out, "%s onto\n", cmd_reset);
5819 else {
5820 strbuf_reset(&oneline);
5821 pretty_print_commit(pp, commit, &oneline);
5822 strbuf_addf(out, "%s %s # %s\n",
5823 cmd_reset, to, oneline.buf);
5827 for (iter2 = list; iter2; iter2 = iter2->next) {
5828 struct object_id *oid = &iter2->item->object.oid;
5829 entry = oidmap_get(&commit2todo, oid);
5830 /* only show if not already upstream */
5831 if (entry)
5832 strbuf_addf(out, "%s\n", entry->string);
5833 entry = oidmap_get(&state.commit2label, oid);
5834 if (entry)
5835 strbuf_addf(out, "%s %s\n",
5836 cmd_label, entry->string);
5837 oidset_insert(&shown, oid);
5840 free_commit_list(list);
5843 free_commit_list(commits);
5844 free_commit_list(tips);
5846 strbuf_release(&label);
5847 strbuf_release(&oneline);
5848 strbuf_release(&buf);
5850 oidmap_free(&commit2todo, 1);
5851 oidmap_free(&state.commit2label, 1);
5852 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5853 strbuf_release(&state.buf);
5855 return 0;
5858 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5859 const char **argv, unsigned flags)
5861 char *format = NULL;
5862 struct pretty_print_context pp = {0};
5863 struct rev_info revs;
5864 struct commit *commit;
5865 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5866 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5867 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5868 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5869 int skipped_commit = 0;
5870 int ret = 0;
5872 repo_init_revisions(r, &revs, NULL);
5873 revs.verbose_header = 1;
5874 if (!rebase_merges)
5875 revs.max_parents = 1;
5876 revs.cherry_mark = !reapply_cherry_picks;
5877 revs.limited = 1;
5878 revs.reverse = 1;
5879 revs.right_only = 1;
5880 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5881 revs.topo_order = 1;
5883 revs.pretty_given = 1;
5884 git_config_get_string("rebase.instructionFormat", &format);
5885 if (!format || !*format) {
5886 free(format);
5887 format = xstrdup("%s");
5889 get_commit_format(format, &revs);
5890 free(format);
5891 pp.fmt = revs.commit_format;
5892 pp.output_encoding = get_log_output_encoding();
5894 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5895 ret = error(_("make_script: unhandled options"));
5896 goto cleanup;
5899 if (prepare_revision_walk(&revs) < 0) {
5900 ret = error(_("make_script: error preparing revisions"));
5901 goto cleanup;
5904 if (rebase_merges) {
5905 ret = make_script_with_merges(&pp, &revs, out, flags);
5906 goto cleanup;
5909 while ((commit = get_revision(&revs))) {
5910 int is_empty = is_original_commit_empty(commit);
5912 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5913 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5914 warning(_("skipped previously applied commit %s"),
5915 short_commit_name(r, commit));
5916 skipped_commit = 1;
5917 continue;
5919 if (is_empty && !keep_empty)
5920 continue;
5921 strbuf_addf(out, "%s %s ", insn,
5922 oid_to_hex(&commit->object.oid));
5923 pretty_print_commit(&pp, commit, out);
5924 if (is_empty)
5925 strbuf_addf(out, " %s empty", comment_line_str);
5926 strbuf_addch(out, '\n');
5928 if (skipped_commit)
5929 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5930 _("use --reapply-cherry-picks to include skipped commits"));
5931 cleanup:
5932 release_revisions(&revs);
5933 return ret;
5937 * Add commands after pick and (series of) squash/fixup commands
5938 * in the todo list.
5940 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5941 struct string_list *commands)
5943 struct strbuf *buf = &todo_list->buf;
5944 size_t base_offset = buf->len;
5945 int i, insert, nr = 0, alloc = 0;
5946 struct todo_item *items = NULL, *base_items = NULL;
5948 CALLOC_ARRAY(base_items, commands->nr);
5949 for (i = 0; i < commands->nr; i++) {
5950 size_t command_len = strlen(commands->items[i].string);
5952 strbuf_addstr(buf, commands->items[i].string);
5953 strbuf_addch(buf, '\n');
5955 base_items[i].command = TODO_EXEC;
5956 base_items[i].offset_in_buf = base_offset;
5957 base_items[i].arg_offset = base_offset;
5958 base_items[i].arg_len = command_len;
5960 base_offset += command_len + 1;
5964 * Insert <commands> after every pick. Here, fixup/squash chains
5965 * are considered part of the pick, so we insert the commands *after*
5966 * those chains if there are any.
5968 * As we insert the exec commands immediately after rearranging
5969 * any fixups and before the user edits the list, a fixup chain
5970 * can never contain comments (any comments are empty picks that
5971 * have been commented out because the user did not specify
5972 * --keep-empty). So, it is safe to insert an exec command
5973 * without looking at the command following a comment.
5975 insert = 0;
5976 for (i = 0; i < todo_list->nr; i++) {
5977 enum todo_command command = todo_list->items[i].command;
5978 if (insert && !is_fixup(command)) {
5979 ALLOC_GROW(items, nr + commands->nr, alloc);
5980 COPY_ARRAY(items + nr, base_items, commands->nr);
5981 nr += commands->nr;
5983 insert = 0;
5986 ALLOC_GROW(items, nr + 1, alloc);
5987 items[nr++] = todo_list->items[i];
5989 if (command == TODO_PICK || command == TODO_MERGE)
5990 insert = 1;
5993 /* insert or append final <commands> */
5994 if (insert) {
5995 ALLOC_GROW(items, nr + commands->nr, alloc);
5996 COPY_ARRAY(items + nr, base_items, commands->nr);
5997 nr += commands->nr;
6000 free(base_items);
6001 FREE_AND_NULL(todo_list->items);
6002 todo_list->items = items;
6003 todo_list->nr = nr;
6004 todo_list->alloc = alloc;
6007 static void todo_list_to_strbuf(struct repository *r,
6008 struct todo_list *todo_list,
6009 struct strbuf *buf, int num, unsigned flags)
6011 struct todo_item *item;
6012 int i, max = todo_list->nr;
6014 if (num > 0 && num < max)
6015 max = num;
6017 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6018 char cmd;
6020 /* if the item is not a command write it and continue */
6021 if (item->command >= TODO_COMMENT) {
6022 strbuf_addf(buf, "%.*s\n", item->arg_len,
6023 todo_item_get_arg(todo_list, item));
6024 continue;
6027 /* add command to the buffer */
6028 cmd = command_to_char(item->command);
6029 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6030 strbuf_addch(buf, cmd);
6031 else
6032 strbuf_addstr(buf, command_to_string(item->command));
6034 /* add commit id */
6035 if (item->commit) {
6036 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6037 short_commit_name(r, item->commit) :
6038 oid_to_hex(&item->commit->object.oid);
6040 if (item->command == TODO_FIXUP) {
6041 if (item->flags & TODO_EDIT_FIXUP_MSG)
6042 strbuf_addstr(buf, " -c");
6043 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6044 strbuf_addstr(buf, " -C");
6048 if (item->command == TODO_MERGE) {
6049 if (item->flags & TODO_EDIT_MERGE_MSG)
6050 strbuf_addstr(buf, " -c");
6051 else
6052 strbuf_addstr(buf, " -C");
6055 strbuf_addf(buf, " %s", oid);
6058 /* add all the rest */
6059 if (!item->arg_len)
6060 strbuf_addch(buf, '\n');
6061 else
6062 strbuf_addf(buf, " %.*s\n", item->arg_len,
6063 todo_item_get_arg(todo_list, item));
6067 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6068 const char *file, const char *shortrevisions,
6069 const char *shortonto, int num, unsigned flags)
6071 int res;
6072 struct strbuf buf = STRBUF_INIT;
6074 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6075 if (flags & TODO_LIST_APPEND_TODO_HELP)
6076 append_todo_help(count_commands(todo_list),
6077 shortrevisions, shortonto, &buf);
6079 res = write_message(buf.buf, buf.len, file, 0);
6080 strbuf_release(&buf);
6082 return res;
6085 /* skip picking commits whose parents are unchanged */
6086 static int skip_unnecessary_picks(struct repository *r,
6087 struct todo_list *todo_list,
6088 struct object_id *base_oid)
6090 struct object_id *parent_oid;
6091 int i;
6093 for (i = 0; i < todo_list->nr; i++) {
6094 struct todo_item *item = todo_list->items + i;
6096 if (item->command >= TODO_NOOP)
6097 continue;
6098 if (item->command != TODO_PICK)
6099 break;
6100 if (repo_parse_commit(r, item->commit)) {
6101 return error(_("could not parse commit '%s'"),
6102 oid_to_hex(&item->commit->object.oid));
6104 if (!item->commit->parents)
6105 break; /* root commit */
6106 if (item->commit->parents->next)
6107 break; /* merge commit */
6108 parent_oid = &item->commit->parents->item->object.oid;
6109 if (!oideq(parent_oid, base_oid))
6110 break;
6111 oidcpy(base_oid, &item->commit->object.oid);
6113 if (i > 0) {
6114 const char *done_path = rebase_path_done();
6116 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6117 error_errno(_("could not write to '%s'"), done_path);
6118 return -1;
6121 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6122 todo_list->nr -= i;
6123 todo_list->current = 0;
6124 todo_list->done_nr += i;
6126 if (is_fixup(peek_command(todo_list, 0)))
6127 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6130 return 0;
6133 struct todo_add_branch_context {
6134 struct todo_item *items;
6135 size_t items_nr;
6136 size_t items_alloc;
6137 struct strbuf *buf;
6138 struct commit *commit;
6139 struct string_list refs_to_oids;
6142 static int add_decorations_to_list(const struct commit *commit,
6143 struct todo_add_branch_context *ctx)
6145 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6146 const char *head_ref = resolve_ref_unsafe("HEAD",
6147 RESOLVE_REF_READING,
6148 NULL,
6149 NULL);
6151 while (decoration) {
6152 struct todo_item *item;
6153 const char *path;
6154 size_t base_offset = ctx->buf->len;
6157 * If the branch is the current HEAD, then it will be
6158 * updated by the default rebase behavior.
6160 if (head_ref && !strcmp(head_ref, decoration->name)) {
6161 decoration = decoration->next;
6162 continue;
6165 ALLOC_GROW(ctx->items,
6166 ctx->items_nr + 1,
6167 ctx->items_alloc);
6168 item = &ctx->items[ctx->items_nr];
6169 memset(item, 0, sizeof(*item));
6171 /* If the branch is checked out, then leave a comment instead. */
6172 if ((path = branch_checked_out(decoration->name))) {
6173 item->command = TODO_COMMENT;
6174 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6175 decoration->name, path);
6176 } else {
6177 struct string_list_item *sti;
6178 item->command = TODO_UPDATE_REF;
6179 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6181 sti = string_list_insert(&ctx->refs_to_oids,
6182 decoration->name);
6183 sti->util = init_update_ref_record(decoration->name);
6186 item->offset_in_buf = base_offset;
6187 item->arg_offset = base_offset;
6188 item->arg_len = ctx->buf->len - base_offset;
6189 ctx->items_nr++;
6191 decoration = decoration->next;
6194 return 0;
6198 * For each 'pick' command, find out if the commit has a decoration in
6199 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6201 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6203 int i, res;
6204 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6205 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6206 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6207 struct decoration_filter decoration_filter = {
6208 .include_ref_pattern = &decorate_refs_include,
6209 .exclude_ref_pattern = &decorate_refs_exclude,
6210 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6212 struct todo_add_branch_context ctx = {
6213 .buf = &todo_list->buf,
6214 .refs_to_oids = STRING_LIST_INIT_DUP,
6217 ctx.items_alloc = 2 * todo_list->nr + 1;
6218 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6220 string_list_append(&decorate_refs_include, "refs/heads/");
6221 load_ref_decorations(&decoration_filter, 0);
6223 for (i = 0; i < todo_list->nr; ) {
6224 struct todo_item *item = &todo_list->items[i];
6226 /* insert ith item into new list */
6227 ALLOC_GROW(ctx.items,
6228 ctx.items_nr + 1,
6229 ctx.items_alloc);
6231 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6233 if (item->commit) {
6234 ctx.commit = item->commit;
6235 add_decorations_to_list(item->commit, &ctx);
6239 res = write_update_refs_state(&ctx.refs_to_oids);
6241 string_list_clear(&ctx.refs_to_oids, 1);
6243 if (res) {
6244 /* we failed, so clean up the new list. */
6245 free(ctx.items);
6246 return res;
6249 free(todo_list->items);
6250 todo_list->items = ctx.items;
6251 todo_list->nr = ctx.items_nr;
6252 todo_list->alloc = ctx.items_alloc;
6254 return 0;
6257 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6258 const char *shortrevisions, const char *onto_name,
6259 struct commit *onto, const struct object_id *orig_head,
6260 struct string_list *commands, unsigned autosquash,
6261 unsigned update_refs,
6262 struct todo_list *todo_list)
6264 char shortonto[GIT_MAX_HEXSZ + 1];
6265 const char *todo_file = rebase_path_todo();
6266 struct todo_list new_todo = TODO_LIST_INIT;
6267 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6268 struct object_id oid = onto->object.oid;
6269 int res;
6271 repo_find_unique_abbrev_r(r, shortonto, &oid,
6272 DEFAULT_ABBREV);
6274 if (buf->len == 0) {
6275 struct todo_item *item = append_new_todo(todo_list);
6276 item->command = TODO_NOOP;
6277 item->commit = NULL;
6278 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6281 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6282 return -1;
6284 if (autosquash && todo_list_rearrange_squash(todo_list))
6285 return -1;
6287 if (commands->nr)
6288 todo_list_add_exec_commands(todo_list, commands);
6290 if (count_commands(todo_list) == 0) {
6291 apply_autostash(rebase_path_autostash());
6292 sequencer_remove_state(opts);
6294 return error(_("nothing to do"));
6297 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6298 shortonto, flags);
6299 if (res == -1)
6300 return -1;
6301 else if (res == -2) {
6302 apply_autostash(rebase_path_autostash());
6303 sequencer_remove_state(opts);
6305 return -1;
6306 } else if (res == -3) {
6307 apply_autostash(rebase_path_autostash());
6308 sequencer_remove_state(opts);
6309 todo_list_release(&new_todo);
6311 return error(_("nothing to do"));
6312 } else if (res == -4) {
6313 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6314 todo_list_release(&new_todo);
6316 return -1;
6319 /* Expand the commit IDs */
6320 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6321 strbuf_swap(&new_todo.buf, &buf2);
6322 strbuf_release(&buf2);
6323 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6324 new_todo.total_nr = 0;
6325 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6326 BUG("invalid todo list after expanding IDs:\n%s",
6327 new_todo.buf.buf);
6329 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6330 todo_list_release(&new_todo);
6331 return error(_("could not skip unnecessary pick commands"));
6334 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6335 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6336 todo_list_release(&new_todo);
6337 return error_errno(_("could not write '%s'"), todo_file);
6340 res = -1;
6342 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6343 goto cleanup;
6345 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6346 goto cleanup;
6348 todo_list_write_total_nr(&new_todo);
6349 res = pick_commits(r, &new_todo, opts);
6351 cleanup:
6352 todo_list_release(&new_todo);
6354 return res;
6357 struct subject2item_entry {
6358 struct hashmap_entry entry;
6359 int i;
6360 char subject[FLEX_ARRAY];
6363 static int subject2item_cmp(const void *fndata UNUSED,
6364 const struct hashmap_entry *eptr,
6365 const struct hashmap_entry *entry_or_key,
6366 const void *key)
6368 const struct subject2item_entry *a, *b;
6370 a = container_of(eptr, const struct subject2item_entry, entry);
6371 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6373 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6376 define_commit_slab(commit_todo_item, struct todo_item *);
6378 static int skip_fixupish(const char *subject, const char **p) {
6379 return skip_prefix(subject, "fixup! ", p) ||
6380 skip_prefix(subject, "amend! ", p) ||
6381 skip_prefix(subject, "squash! ", p);
6385 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6386 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6387 * after the former, and change "pick" to "fixup"/"squash".
6389 * Note that if the config has specified a custom instruction format, each log
6390 * message will have to be retrieved from the commit (as the oneline in the
6391 * script cannot be trusted) in order to normalize the autosquash arrangement.
6393 int todo_list_rearrange_squash(struct todo_list *todo_list)
6395 struct hashmap subject2item;
6396 int rearranged = 0, *next, *tail, i, nr = 0;
6397 char **subjects;
6398 struct commit_todo_item commit_todo;
6399 struct todo_item *items = NULL;
6401 init_commit_todo_item(&commit_todo);
6403 * The hashmap maps onelines to the respective todo list index.
6405 * If any items need to be rearranged, the next[i] value will indicate
6406 * which item was moved directly after the i'th.
6408 * In that case, last[i] will indicate the index of the latest item to
6409 * be moved to appear after the i'th.
6411 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6412 ALLOC_ARRAY(next, todo_list->nr);
6413 ALLOC_ARRAY(tail, todo_list->nr);
6414 ALLOC_ARRAY(subjects, todo_list->nr);
6415 for (i = 0; i < todo_list->nr; i++) {
6416 struct strbuf buf = STRBUF_INIT;
6417 struct todo_item *item = todo_list->items + i;
6418 const char *commit_buffer, *subject, *p;
6419 size_t subject_len;
6420 int i2 = -1;
6421 struct subject2item_entry *entry;
6423 next[i] = tail[i] = -1;
6424 if (!item->commit || item->command == TODO_DROP) {
6425 subjects[i] = NULL;
6426 continue;
6429 if (is_fixup(item->command)) {
6430 clear_commit_todo_item(&commit_todo);
6431 return error(_("the script was already rearranged."));
6434 repo_parse_commit(the_repository, item->commit);
6435 commit_buffer = repo_logmsg_reencode(the_repository,
6436 item->commit, NULL,
6437 "UTF-8");
6438 find_commit_subject(commit_buffer, &subject);
6439 format_subject(&buf, subject, " ");
6440 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6441 repo_unuse_commit_buffer(the_repository, item->commit,
6442 commit_buffer);
6443 if (skip_fixupish(subject, &p)) {
6444 struct commit *commit2;
6446 for (;;) {
6447 while (isspace(*p))
6448 p++;
6449 if (!skip_fixupish(p, &p))
6450 break;
6453 entry = hashmap_get_entry_from_hash(&subject2item,
6454 strhash(p), p,
6455 struct subject2item_entry,
6456 entry);
6457 if (entry)
6458 /* found by title */
6459 i2 = entry->i;
6460 else if (!strchr(p, ' ') &&
6461 (commit2 =
6462 lookup_commit_reference_by_name(p)) &&
6463 *commit_todo_item_at(&commit_todo, commit2))
6464 /* found by commit name */
6465 i2 = *commit_todo_item_at(&commit_todo, commit2)
6466 - todo_list->items;
6467 else {
6468 /* copy can be a prefix of the commit subject */
6469 for (i2 = 0; i2 < i; i2++)
6470 if (subjects[i2] &&
6471 starts_with(subjects[i2], p))
6472 break;
6473 if (i2 == i)
6474 i2 = -1;
6477 if (i2 >= 0) {
6478 rearranged = 1;
6479 if (starts_with(subject, "fixup!")) {
6480 todo_list->items[i].command = TODO_FIXUP;
6481 } else if (starts_with(subject, "amend!")) {
6482 todo_list->items[i].command = TODO_FIXUP;
6483 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6484 } else {
6485 todo_list->items[i].command = TODO_SQUASH;
6487 if (tail[i2] < 0) {
6488 next[i] = next[i2];
6489 next[i2] = i;
6490 } else {
6491 next[i] = next[tail[i2]];
6492 next[tail[i2]] = i;
6494 tail[i2] = i;
6495 } else if (!hashmap_get_from_hash(&subject2item,
6496 strhash(subject), subject)) {
6497 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6498 entry->i = i;
6499 hashmap_entry_init(&entry->entry,
6500 strhash(entry->subject));
6501 hashmap_put(&subject2item, &entry->entry);
6504 *commit_todo_item_at(&commit_todo, item->commit) = item;
6507 if (rearranged) {
6508 ALLOC_ARRAY(items, todo_list->nr);
6510 for (i = 0; i < todo_list->nr; i++) {
6511 enum todo_command command = todo_list->items[i].command;
6512 int cur = i;
6515 * Initially, all commands are 'pick's. If it is a
6516 * fixup or a squash now, we have rearranged it.
6518 if (is_fixup(command))
6519 continue;
6521 while (cur >= 0) {
6522 items[nr++] = todo_list->items[cur];
6523 cur = next[cur];
6527 assert(nr == todo_list->nr);
6528 todo_list->alloc = nr;
6529 FREE_AND_NULL(todo_list->items);
6530 todo_list->items = items;
6533 free(next);
6534 free(tail);
6535 for (i = 0; i < todo_list->nr; i++)
6536 free(subjects[i]);
6537 free(subjects);
6538 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6540 clear_commit_todo_item(&commit_todo);
6542 return 0;
6545 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6547 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6548 struct object_id cherry_pick_head, rebase_head;
6550 if (file_exists(git_path_seq_dir()))
6551 *whence = FROM_CHERRY_PICK_MULTI;
6552 if (file_exists(rebase_path()) &&
6553 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6554 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6555 oideq(&rebase_head, &cherry_pick_head))
6556 *whence = FROM_REBASE_PICK;
6557 else
6558 *whence = FROM_CHERRY_PICK_SINGLE;
6560 return 1;
6563 return 0;
6566 int sequencer_get_update_refs_state(const char *wt_dir,
6567 struct string_list *refs)
6569 int result = 0;
6570 FILE *fp = NULL;
6571 struct strbuf ref = STRBUF_INIT;
6572 struct strbuf hash = STRBUF_INIT;
6573 struct update_ref_record *rec = NULL;
6575 char *path = rebase_path_update_refs(wt_dir);
6577 fp = fopen(path, "r");
6578 if (!fp)
6579 goto cleanup;
6581 while (strbuf_getline(&ref, fp) != EOF) {
6582 struct string_list_item *item;
6584 CALLOC_ARRAY(rec, 1);
6586 if (strbuf_getline(&hash, fp) == EOF ||
6587 get_oid_hex(hash.buf, &rec->before)) {
6588 warning(_("update-refs file at '%s' is invalid"),
6589 path);
6590 result = -1;
6591 goto cleanup;
6594 if (strbuf_getline(&hash, fp) == EOF ||
6595 get_oid_hex(hash.buf, &rec->after)) {
6596 warning(_("update-refs file at '%s' is invalid"),
6597 path);
6598 result = -1;
6599 goto cleanup;
6602 item = string_list_insert(refs, ref.buf);
6603 item->util = rec;
6604 rec = NULL;
6607 cleanup:
6608 if (fp)
6609 fclose(fp);
6610 free(path);
6611 free(rec);
6612 strbuf_release(&ref);
6613 strbuf_release(&hash);
6614 return result;