cherry-pick: enforce `--keep-redundant-commits` incompatibility
[alt-git.git] / sequencer.c
blob1964977545391c55c28879258429b1f9e2d44772
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(&info, sb->buf, &opts);
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 static void print_advice(struct repository *r, int show_hint,
465 struct replay_opts *opts)
467 char *msg = getenv("GIT_CHERRY_PICK_HELP");
469 if (msg) {
470 advise("%s\n", msg);
472 * A conflict has occurred but the porcelain
473 * (typically rebase --interactive) wants to take care
474 * of the commit itself so remove CHERRY_PICK_HEAD
476 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
477 NULL, REF_NO_DEREF);
478 return;
481 if (show_hint) {
482 if (opts->no_commit)
483 advise(_("after resolving the conflicts, mark the corrected paths\n"
484 "with 'git add <paths>' or 'git rm <paths>'"));
485 else if (opts->action == REPLAY_PICK)
486 advise(_("After resolving the conflicts, mark them with\n"
487 "\"git add/rm <pathspec>\", then run\n"
488 "\"git cherry-pick --continue\".\n"
489 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
490 "To abort and get back to the state before \"git cherry-pick\",\n"
491 "run \"git cherry-pick --abort\"."));
492 else if (opts->action == REPLAY_REVERT)
493 advise(_("After resolving the conflicts, mark them with\n"
494 "\"git add/rm <pathspec>\", then run\n"
495 "\"git revert --continue\".\n"
496 "You can instead skip this commit with \"git revert --skip\".\n"
497 "To abort and get back to the state before \"git revert\",\n"
498 "run \"git revert --abort\"."));
499 else
500 BUG("unexpected pick action in print_advice()");
504 static int write_message(const void *buf, size_t len, const char *filename,
505 int append_eol)
507 struct lock_file msg_file = LOCK_INIT;
509 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
510 if (msg_fd < 0)
511 return error_errno(_("could not lock '%s'"), filename);
512 if (write_in_full(msg_fd, buf, len) < 0) {
513 error_errno(_("could not write to '%s'"), filename);
514 rollback_lock_file(&msg_file);
515 return -1;
517 if (append_eol && write(msg_fd, "\n", 1) < 0) {
518 error_errno(_("could not write eol to '%s'"), filename);
519 rollback_lock_file(&msg_file);
520 return -1;
522 if (commit_lock_file(&msg_file) < 0)
523 return error(_("failed to finalize '%s'"), filename);
525 return 0;
528 int read_oneliner(struct strbuf *buf,
529 const char *path, unsigned flags)
531 int orig_len = buf->len;
533 if (strbuf_read_file(buf, path, 0) < 0) {
534 if ((flags & READ_ONELINER_WARN_MISSING) ||
535 (errno != ENOENT && errno != ENOTDIR))
536 warning_errno(_("could not read '%s'"), path);
537 return 0;
540 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
541 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
542 --buf->len;
543 buf->buf[buf->len] = '\0';
546 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
547 return 0;
549 return 1;
552 static struct tree *empty_tree(struct repository *r)
554 return lookup_tree(r, the_hash_algo->empty_tree);
557 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
559 if (repo_read_index_unmerged(repo))
560 return error_resolve_conflict(action_name(opts));
562 error(_("your local changes would be overwritten by %s."),
563 _(action_name(opts)));
565 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
566 advise(_("commit your changes or stash them to proceed."));
567 return -1;
570 static void update_abort_safety_file(void)
572 struct object_id head;
574 /* Do nothing on a single-pick */
575 if (!file_exists(git_path_seq_dir()))
576 return;
578 if (!repo_get_oid(the_repository, "HEAD", &head))
579 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
580 else
581 write_file(git_path_abort_safety_file(), "%s", "");
584 static int fast_forward_to(struct repository *r,
585 const struct object_id *to,
586 const struct object_id *from,
587 int unborn,
588 struct replay_opts *opts)
590 struct ref_transaction *transaction;
591 struct strbuf sb = STRBUF_INIT;
592 struct strbuf err = STRBUF_INIT;
594 repo_read_index(r);
595 if (checkout_fast_forward(r, from, to, 1))
596 return -1; /* the callee should have complained already */
598 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
600 transaction = ref_transaction_begin(&err);
601 if (!transaction ||
602 ref_transaction_update(transaction, "HEAD",
603 to, unborn && !is_rebase_i(opts) ?
604 null_oid() : from,
605 0, sb.buf, &err) ||
606 ref_transaction_commit(transaction, &err)) {
607 ref_transaction_free(transaction);
608 error("%s", err.buf);
609 strbuf_release(&sb);
610 strbuf_release(&err);
611 return -1;
614 strbuf_release(&sb);
615 strbuf_release(&err);
616 ref_transaction_free(transaction);
617 update_abort_safety_file();
618 return 0;
621 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
622 int use_editor)
624 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
625 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
626 COMMIT_MSG_CLEANUP_SPACE;
627 else if (!strcmp(cleanup_arg, "verbatim"))
628 return COMMIT_MSG_CLEANUP_NONE;
629 else if (!strcmp(cleanup_arg, "whitespace"))
630 return COMMIT_MSG_CLEANUP_SPACE;
631 else if (!strcmp(cleanup_arg, "strip"))
632 return COMMIT_MSG_CLEANUP_ALL;
633 else if (!strcmp(cleanup_arg, "scissors"))
634 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
635 COMMIT_MSG_CLEANUP_SPACE;
636 else
637 die(_("Invalid cleanup mode %s"), cleanup_arg);
641 * NB using int rather than enum cleanup_mode to stop clang's
642 * -Wtautological-constant-out-of-range-compare complaining that the comparison
643 * is always true.
645 static const char *describe_cleanup_mode(int cleanup_mode)
647 static const char *modes[] = { "whitespace",
648 "verbatim",
649 "scissors",
650 "strip" };
652 if (cleanup_mode < ARRAY_SIZE(modes))
653 return modes[cleanup_mode];
655 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
658 void append_conflicts_hint(struct index_state *istate,
659 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
661 int i;
663 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
664 strbuf_addch(msgbuf, '\n');
665 wt_status_append_cut_line(msgbuf);
666 strbuf_addch(msgbuf, comment_line_char);
669 strbuf_addch(msgbuf, '\n');
670 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
671 for (i = 0; i < istate->cache_nr;) {
672 const struct cache_entry *ce = istate->cache[i++];
673 if (ce_stage(ce)) {
674 strbuf_commented_addf(msgbuf, comment_line_char,
675 "\t%s\n", ce->name);
676 while (i < istate->cache_nr &&
677 !strcmp(ce->name, istate->cache[i]->name))
678 i++;
683 static int do_recursive_merge(struct repository *r,
684 struct commit *base, struct commit *next,
685 const char *base_label, const char *next_label,
686 struct object_id *head, struct strbuf *msgbuf,
687 struct replay_opts *opts)
689 struct merge_options o;
690 struct merge_result result;
691 struct tree *next_tree, *base_tree, *head_tree;
692 int clean, show_output;
693 int i;
694 struct lock_file index_lock = LOCK_INIT;
696 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
697 return -1;
699 repo_read_index(r);
701 init_merge_options(&o, r);
702 o.ancestor = base ? base_label : "(empty tree)";
703 o.branch1 = "HEAD";
704 o.branch2 = next ? next_label : "(empty tree)";
705 if (is_rebase_i(opts))
706 o.buffer_output = 2;
707 o.show_rename_progress = 1;
709 head_tree = parse_tree_indirect(head);
710 if (!head_tree)
711 return error(_("unable to read tree (%s)"), oid_to_hex(head));
712 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
713 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
715 for (i = 0; i < opts->xopts.nr; i++)
716 parse_merge_opt(&o, opts->xopts.v[i]);
718 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
719 memset(&result, 0, sizeof(result));
720 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
721 &result);
722 show_output = !is_rebase_i(opts) || !result.clean;
724 * TODO: merge_switch_to_result will update index/working tree;
725 * we only really want to do that if !result.clean || this is
726 * the final patch to be picked. But determining this is the
727 * final patch would take some work, and "head_tree" would need
728 * to be replace with the tree the index matched before we
729 * started doing any picks.
731 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
732 clean = result.clean;
733 } else {
734 ensure_full_index(r->index);
735 clean = merge_trees(&o, head_tree, next_tree, base_tree);
736 if (is_rebase_i(opts) && clean <= 0)
737 fputs(o.obuf.buf, stdout);
738 strbuf_release(&o.obuf);
740 if (clean < 0) {
741 rollback_lock_file(&index_lock);
742 return clean;
745 if (write_locked_index(r->index, &index_lock,
746 COMMIT_LOCK | SKIP_IF_UNCHANGED))
748 * TRANSLATORS: %s will be "revert", "cherry-pick" or
749 * "rebase".
751 return error(_("%s: Unable to write new index file"),
752 _(action_name(opts)));
754 if (!clean)
755 append_conflicts_hint(r->index, msgbuf,
756 opts->default_msg_cleanup);
758 return !clean;
761 static struct object_id *get_cache_tree_oid(struct index_state *istate)
763 if (!cache_tree_fully_valid(istate->cache_tree))
764 if (cache_tree_update(istate, 0)) {
765 error(_("unable to update cache tree"));
766 return NULL;
769 return &istate->cache_tree->oid;
772 static int is_index_unchanged(struct repository *r)
774 struct object_id head_oid, *cache_tree_oid;
775 const struct object_id *head_tree_oid;
776 struct commit *head_commit;
777 struct index_state *istate = r->index;
778 const char *head_name;
780 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
781 /* Check to see if this is an unborn branch */
782 head_name = resolve_ref_unsafe("HEAD",
783 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
784 &head_oid, NULL);
785 if (!head_name ||
786 !starts_with(head_name, "refs/heads/") ||
787 !is_null_oid(&head_oid))
788 return error(_("could not resolve HEAD commit"));
789 head_tree_oid = the_hash_algo->empty_tree;
790 } else {
791 head_commit = lookup_commit(r, &head_oid);
794 * If head_commit is NULL, check_commit, called from
795 * lookup_commit, would have indicated that head_commit is not
796 * a commit object already. repo_parse_commit() will return failure
797 * without further complaints in such a case. Otherwise, if
798 * the commit is invalid, repo_parse_commit() will complain. So
799 * there is nothing for us to say here. Just return failure.
801 if (repo_parse_commit(r, head_commit))
802 return -1;
804 head_tree_oid = get_commit_tree_oid(head_commit);
807 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
808 return -1;
810 return oideq(cache_tree_oid, head_tree_oid);
813 static int write_author_script(const char *message)
815 struct strbuf buf = STRBUF_INIT;
816 const char *eol;
817 int res;
819 for (;;)
820 if (!*message || starts_with(message, "\n")) {
821 missing_author:
822 /* Missing 'author' line? */
823 unlink(rebase_path_author_script());
824 return 0;
825 } else if (skip_prefix(message, "author ", &message))
826 break;
827 else if ((eol = strchr(message, '\n')))
828 message = eol + 1;
829 else
830 goto missing_author;
832 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
833 while (*message && *message != '\n' && *message != '\r')
834 if (skip_prefix(message, " <", &message))
835 break;
836 else if (*message != '\'')
837 strbuf_addch(&buf, *(message++));
838 else
839 strbuf_addf(&buf, "'\\%c'", *(message++));
840 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
841 while (*message && *message != '\n' && *message != '\r')
842 if (skip_prefix(message, "> ", &message))
843 break;
844 else if (*message != '\'')
845 strbuf_addch(&buf, *(message++));
846 else
847 strbuf_addf(&buf, "'\\%c'", *(message++));
848 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
849 while (*message && *message != '\n' && *message != '\r')
850 if (*message != '\'')
851 strbuf_addch(&buf, *(message++));
852 else
853 strbuf_addf(&buf, "'\\%c'", *(message++));
854 strbuf_addch(&buf, '\'');
855 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
856 strbuf_release(&buf);
857 return res;
861 * Take a series of KEY='VALUE' lines where VALUE part is
862 * sq-quoted, and append <KEY, VALUE> at the end of the string list
864 static int parse_key_value_squoted(char *buf, struct string_list *list)
866 while (*buf) {
867 struct string_list_item *item;
868 char *np;
869 char *cp = strchr(buf, '=');
870 if (!cp) {
871 np = strchrnul(buf, '\n');
872 return error(_("no key present in '%.*s'"),
873 (int) (np - buf), buf);
875 np = strchrnul(cp, '\n');
876 *cp++ = '\0';
877 item = string_list_append(list, buf);
879 buf = np + (*np == '\n');
880 *np = '\0';
881 cp = sq_dequote(cp);
882 if (!cp)
883 return error(_("unable to dequote value of '%s'"),
884 item->string);
885 item->util = xstrdup(cp);
887 return 0;
891 * Reads and parses the state directory's "author-script" file, and sets name,
892 * email and date accordingly.
893 * Returns 0 on success, -1 if the file could not be parsed.
895 * The author script is of the format:
897 * GIT_AUTHOR_NAME='$author_name'
898 * GIT_AUTHOR_EMAIL='$author_email'
899 * GIT_AUTHOR_DATE='$author_date'
901 * where $author_name, $author_email and $author_date are quoted. We are strict
902 * with our parsing, as the file was meant to be eval'd in the now-removed
903 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
904 * from what this function expects, it is better to bail out than to do
905 * something that the user does not expect.
907 int read_author_script(const char *path, char **name, char **email, char **date,
908 int allow_missing)
910 struct strbuf buf = STRBUF_INIT;
911 struct string_list kv = STRING_LIST_INIT_DUP;
912 int retval = -1; /* assume failure */
913 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
915 if (strbuf_read_file(&buf, path, 256) <= 0) {
916 strbuf_release(&buf);
917 if (errno == ENOENT && allow_missing)
918 return 0;
919 else
920 return error_errno(_("could not open '%s' for reading"),
921 path);
924 if (parse_key_value_squoted(buf.buf, &kv))
925 goto finish;
927 for (i = 0; i < kv.nr; i++) {
928 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
929 if (name_i != -2)
930 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
931 else
932 name_i = i;
933 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
934 if (email_i != -2)
935 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
936 else
937 email_i = i;
938 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
939 if (date_i != -2)
940 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
941 else
942 date_i = i;
943 } else {
944 err = error(_("unknown variable '%s'"),
945 kv.items[i].string);
948 if (name_i == -2)
949 error(_("missing 'GIT_AUTHOR_NAME'"));
950 if (email_i == -2)
951 error(_("missing 'GIT_AUTHOR_EMAIL'"));
952 if (date_i == -2)
953 error(_("missing 'GIT_AUTHOR_DATE'"));
954 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
955 goto finish;
956 *name = kv.items[name_i].util;
957 *email = kv.items[email_i].util;
958 *date = kv.items[date_i].util;
959 retval = 0;
960 finish:
961 string_list_clear(&kv, !!retval);
962 strbuf_release(&buf);
963 return retval;
967 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
968 * file with shell quoting into struct strvec. Returns -1 on
969 * error, 0 otherwise.
971 static int read_env_script(struct strvec *env)
973 char *name, *email, *date;
975 if (read_author_script(rebase_path_author_script(),
976 &name, &email, &date, 0))
977 return -1;
979 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
980 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
981 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
982 free(name);
983 free(email);
984 free(date);
986 return 0;
989 static char *get_author(const char *message)
991 size_t len;
992 const char *a;
994 a = find_commit_header(message, "author", &len);
995 if (a)
996 return xmemdupz(a, len);
998 return NULL;
1001 static const char *author_date_from_env(const struct strvec *env)
1003 int i;
1004 const char *date;
1006 for (i = 0; i < env->nr; i++)
1007 if (skip_prefix(env->v[i],
1008 "GIT_AUTHOR_DATE=", &date))
1009 return date;
1011 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1012 * reading the script
1014 BUG("GIT_AUTHOR_DATE missing from author script");
1017 static const char staged_changes_advice[] =
1018 N_("you have staged changes in your working tree\n"
1019 "If these changes are meant to be squashed into the previous commit, run:\n"
1020 "\n"
1021 " git commit --amend %s\n"
1022 "\n"
1023 "If they are meant to go into a new commit, run:\n"
1024 "\n"
1025 " git commit %s\n"
1026 "\n"
1027 "In both cases, once you're done, continue with:\n"
1028 "\n"
1029 " git rebase --continue\n");
1031 #define ALLOW_EMPTY (1<<0)
1032 #define EDIT_MSG (1<<1)
1033 #define AMEND_MSG (1<<2)
1034 #define CLEANUP_MSG (1<<3)
1035 #define VERIFY_MSG (1<<4)
1036 #define CREATE_ROOT_COMMIT (1<<5)
1037 #define VERBATIM_MSG (1<<6)
1039 static int run_command_silent_on_success(struct child_process *cmd)
1041 struct strbuf buf = STRBUF_INIT;
1042 int rc;
1044 cmd->stdout_to_stderr = 1;
1045 rc = pipe_command(cmd,
1046 NULL, 0,
1047 NULL, 0,
1048 &buf, 0);
1050 if (rc)
1051 fputs(buf.buf, stderr);
1052 strbuf_release(&buf);
1053 return rc;
1057 * If we are cherry-pick, and if the merge did not result in
1058 * hand-editing, we will hit this commit and inherit the original
1059 * author date and name.
1061 * If we are revert, or if our cherry-pick results in a hand merge,
1062 * we had better say that the current user is responsible for that.
1064 * An exception is when run_git_commit() is called during an
1065 * interactive rebase: in that case, we will want to retain the
1066 * author metadata.
1068 static int run_git_commit(const char *defmsg,
1069 struct replay_opts *opts,
1070 unsigned int flags)
1072 struct child_process cmd = CHILD_PROCESS_INIT;
1074 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1075 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1077 cmd.git_cmd = 1;
1079 if (is_rebase_i(opts) &&
1080 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1081 !(!defmsg && (flags & AMEND_MSG))) &&
1082 read_env_script(&cmd.env)) {
1083 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1085 return error(_(staged_changes_advice),
1086 gpg_opt, gpg_opt);
1089 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1091 if (opts->committer_date_is_author_date)
1092 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1093 opts->ignore_date ?
1094 "" :
1095 author_date_from_env(&cmd.env));
1096 if (opts->ignore_date)
1097 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1099 strvec_push(&cmd.args, "commit");
1101 if (!(flags & VERIFY_MSG))
1102 strvec_push(&cmd.args, "-n");
1103 if ((flags & AMEND_MSG))
1104 strvec_push(&cmd.args, "--amend");
1105 if (opts->gpg_sign)
1106 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1107 else
1108 strvec_push(&cmd.args, "--no-gpg-sign");
1109 if (defmsg)
1110 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1111 else if (!(flags & EDIT_MSG))
1112 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1113 if ((flags & CLEANUP_MSG))
1114 strvec_push(&cmd.args, "--cleanup=strip");
1115 if ((flags & VERBATIM_MSG))
1116 strvec_push(&cmd.args, "--cleanup=verbatim");
1117 if ((flags & EDIT_MSG))
1118 strvec_push(&cmd.args, "-e");
1119 else if (!(flags & CLEANUP_MSG) &&
1120 !opts->signoff && !opts->record_origin &&
1121 !opts->explicit_cleanup)
1122 strvec_push(&cmd.args, "--cleanup=verbatim");
1124 if ((flags & ALLOW_EMPTY))
1125 strvec_push(&cmd.args, "--allow-empty");
1127 if (!(flags & EDIT_MSG))
1128 strvec_push(&cmd.args, "--allow-empty-message");
1130 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1131 return run_command_silent_on_success(&cmd);
1132 else
1133 return run_command(&cmd);
1136 static int rest_is_empty(const struct strbuf *sb, int start)
1138 int i, eol;
1139 const char *nl;
1141 /* Check if the rest is just whitespace and Signed-off-by's. */
1142 for (i = start; i < sb->len; i++) {
1143 nl = memchr(sb->buf + i, '\n', sb->len - i);
1144 if (nl)
1145 eol = nl - sb->buf;
1146 else
1147 eol = sb->len;
1149 if (strlen(sign_off_header) <= eol - i &&
1150 starts_with(sb->buf + i, sign_off_header)) {
1151 i = eol;
1152 continue;
1154 while (i < eol)
1155 if (!isspace(sb->buf[i++]))
1156 return 0;
1159 return 1;
1162 void cleanup_message(struct strbuf *msgbuf,
1163 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1165 if (verbose || /* Truncate the message just before the diff, if any. */
1166 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1167 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1168 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1169 strbuf_stripspace(msgbuf,
1170 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1174 * Find out if the message in the strbuf contains only whitespace and
1175 * Signed-off-by lines.
1177 int message_is_empty(const struct strbuf *sb,
1178 enum commit_msg_cleanup_mode cleanup_mode)
1180 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1181 return 0;
1182 return rest_is_empty(sb, 0);
1186 * See if the user edited the message in the editor or left what
1187 * was in the template intact
1189 int template_untouched(const struct strbuf *sb, const char *template_file,
1190 enum commit_msg_cleanup_mode cleanup_mode)
1192 struct strbuf tmpl = STRBUF_INIT;
1193 const char *start;
1195 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1196 return 0;
1198 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1199 return 0;
1201 strbuf_stripspace(&tmpl,
1202 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1203 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1204 start = sb->buf;
1205 strbuf_release(&tmpl);
1206 return rest_is_empty(sb, start - sb->buf);
1209 int update_head_with_reflog(const struct commit *old_head,
1210 const struct object_id *new_head,
1211 const char *action, const struct strbuf *msg,
1212 struct strbuf *err)
1214 struct ref_transaction *transaction;
1215 struct strbuf sb = STRBUF_INIT;
1216 const char *nl;
1217 int ret = 0;
1219 if (action) {
1220 strbuf_addstr(&sb, action);
1221 strbuf_addstr(&sb, ": ");
1224 nl = strchr(msg->buf, '\n');
1225 if (nl) {
1226 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1227 } else {
1228 strbuf_addbuf(&sb, msg);
1229 strbuf_addch(&sb, '\n');
1232 transaction = ref_transaction_begin(err);
1233 if (!transaction ||
1234 ref_transaction_update(transaction, "HEAD", new_head,
1235 old_head ? &old_head->object.oid : null_oid(),
1236 0, sb.buf, err) ||
1237 ref_transaction_commit(transaction, err)) {
1238 ret = -1;
1240 ref_transaction_free(transaction);
1241 strbuf_release(&sb);
1243 return ret;
1246 static int run_rewrite_hook(const struct object_id *oldoid,
1247 const struct object_id *newoid)
1249 struct child_process proc = CHILD_PROCESS_INIT;
1250 int code;
1251 struct strbuf sb = STRBUF_INIT;
1252 const char *hook_path = find_hook("post-rewrite");
1254 if (!hook_path)
1255 return 0;
1257 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1258 proc.in = -1;
1259 proc.stdout_to_stderr = 1;
1260 proc.trace2_hook_name = "post-rewrite";
1262 code = start_command(&proc);
1263 if (code)
1264 return code;
1265 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1266 sigchain_push(SIGPIPE, SIG_IGN);
1267 write_in_full(proc.in, sb.buf, sb.len);
1268 close(proc.in);
1269 strbuf_release(&sb);
1270 sigchain_pop(SIGPIPE);
1271 return finish_command(&proc);
1274 void commit_post_rewrite(struct repository *r,
1275 const struct commit *old_head,
1276 const struct object_id *new_head)
1278 struct notes_rewrite_cfg *cfg;
1280 cfg = init_copy_notes_for_rewrite("amend");
1281 if (cfg) {
1282 /* we are amending, so old_head is not NULL */
1283 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1284 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1286 run_rewrite_hook(&old_head->object.oid, new_head);
1289 static int run_prepare_commit_msg_hook(struct repository *r,
1290 struct strbuf *msg,
1291 const char *commit)
1293 int ret = 0;
1294 const char *name, *arg1 = NULL, *arg2 = NULL;
1296 name = git_path_commit_editmsg();
1297 if (write_message(msg->buf, msg->len, name, 0))
1298 return -1;
1300 if (commit) {
1301 arg1 = "commit";
1302 arg2 = commit;
1303 } else {
1304 arg1 = "message";
1306 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1307 arg1, arg2, NULL))
1308 ret = error(_("'prepare-commit-msg' hook failed"));
1310 return ret;
1313 static const char implicit_ident_advice_noconfig[] =
1314 N_("Your name and email address were configured automatically based\n"
1315 "on your username and hostname. Please check that they are accurate.\n"
1316 "You can suppress this message by setting them explicitly. Run the\n"
1317 "following command and follow the instructions in your editor to edit\n"
1318 "your configuration file:\n"
1319 "\n"
1320 " git config --global --edit\n"
1321 "\n"
1322 "After doing this, you may fix the identity used for this commit with:\n"
1323 "\n"
1324 " git commit --amend --reset-author\n");
1326 static const char implicit_ident_advice_config[] =
1327 N_("Your name and email address were configured automatically based\n"
1328 "on your username and hostname. Please check that they are accurate.\n"
1329 "You can suppress this message by setting them explicitly:\n"
1330 "\n"
1331 " git config --global user.name \"Your Name\"\n"
1332 " git config --global user.email you@example.com\n"
1333 "\n"
1334 "After doing this, you may fix the identity used for this commit with:\n"
1335 "\n"
1336 " git commit --amend --reset-author\n");
1338 static const char *implicit_ident_advice(void)
1340 char *user_config = interpolate_path("~/.gitconfig", 0);
1341 char *xdg_config = xdg_config_home("config");
1342 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1344 free(user_config);
1345 free(xdg_config);
1347 if (config_exists)
1348 return _(implicit_ident_advice_config);
1349 else
1350 return _(implicit_ident_advice_noconfig);
1354 void print_commit_summary(struct repository *r,
1355 const char *prefix,
1356 const struct object_id *oid,
1357 unsigned int flags)
1359 struct rev_info rev;
1360 struct commit *commit;
1361 struct strbuf format = STRBUF_INIT;
1362 const char *head;
1363 struct pretty_print_context pctx = {0};
1364 struct strbuf author_ident = STRBUF_INIT;
1365 struct strbuf committer_ident = STRBUF_INIT;
1366 struct ref_store *refs;
1368 commit = lookup_commit(r, oid);
1369 if (!commit)
1370 die(_("couldn't look up newly created commit"));
1371 if (repo_parse_commit(r, commit))
1372 die(_("could not parse newly created commit"));
1374 strbuf_addstr(&format, "format:%h] %s");
1376 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1377 &pctx);
1378 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1379 &pctx);
1380 if (strbuf_cmp(&author_ident, &committer_ident)) {
1381 strbuf_addstr(&format, "\n Author: ");
1382 strbuf_addbuf_percentquote(&format, &author_ident);
1384 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1385 struct strbuf date = STRBUF_INIT;
1387 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1388 strbuf_addstr(&format, "\n Date: ");
1389 strbuf_addbuf_percentquote(&format, &date);
1390 strbuf_release(&date);
1392 if (!committer_ident_sufficiently_given()) {
1393 strbuf_addstr(&format, "\n Committer: ");
1394 strbuf_addbuf_percentquote(&format, &committer_ident);
1395 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1396 strbuf_addch(&format, '\n');
1397 strbuf_addstr(&format, implicit_ident_advice());
1400 strbuf_release(&author_ident);
1401 strbuf_release(&committer_ident);
1403 repo_init_revisions(r, &rev, prefix);
1404 setup_revisions(0, NULL, &rev, NULL);
1406 rev.diff = 1;
1407 rev.diffopt.output_format =
1408 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1410 rev.verbose_header = 1;
1411 rev.show_root_diff = 1;
1412 get_commit_format(format.buf, &rev);
1413 rev.always_show_header = 0;
1414 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1415 diff_setup_done(&rev.diffopt);
1417 refs = get_main_ref_store(r);
1418 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1419 if (!head)
1420 die(_("unable to resolve HEAD after creating commit"));
1421 if (!strcmp(head, "HEAD"))
1422 head = _("detached HEAD");
1423 else
1424 skip_prefix(head, "refs/heads/", &head);
1425 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1426 _(" (root-commit)") : "");
1428 if (!log_tree_commit(&rev, commit)) {
1429 rev.always_show_header = 1;
1430 rev.use_terminator = 1;
1431 log_tree_commit(&rev, commit);
1434 release_revisions(&rev);
1435 strbuf_release(&format);
1438 static int parse_head(struct repository *r, struct commit **head)
1440 struct commit *current_head;
1441 struct object_id oid;
1443 if (repo_get_oid(r, "HEAD", &oid)) {
1444 current_head = NULL;
1445 } else {
1446 current_head = lookup_commit_reference(r, &oid);
1447 if (!current_head)
1448 return error(_("could not parse HEAD"));
1449 if (!oideq(&oid, &current_head->object.oid)) {
1450 warning(_("HEAD %s is not a commit!"),
1451 oid_to_hex(&oid));
1453 if (repo_parse_commit(r, current_head))
1454 return error(_("could not parse HEAD commit"));
1456 *head = current_head;
1458 return 0;
1462 * Try to commit without forking 'git commit'. In some cases we need
1463 * to run 'git commit' to display an error message
1465 * Returns:
1466 * -1 - error unable to commit
1467 * 0 - success
1468 * 1 - run 'git commit'
1470 static int try_to_commit(struct repository *r,
1471 struct strbuf *msg, const char *author,
1472 struct replay_opts *opts, unsigned int flags,
1473 struct object_id *oid)
1475 struct object_id tree;
1476 struct commit *current_head = NULL;
1477 struct commit_list *parents = NULL;
1478 struct commit_extra_header *extra = NULL;
1479 struct strbuf err = STRBUF_INIT;
1480 struct strbuf commit_msg = STRBUF_INIT;
1481 char *amend_author = NULL;
1482 const char *committer = NULL;
1483 const char *hook_commit = NULL;
1484 enum commit_msg_cleanup_mode cleanup;
1485 int res = 0;
1487 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1488 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1490 if (parse_head(r, &current_head))
1491 return -1;
1493 if (flags & AMEND_MSG) {
1494 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1495 const char *out_enc = get_commit_output_encoding();
1496 const char *message = repo_logmsg_reencode(r, current_head,
1497 NULL, out_enc);
1499 if (!msg) {
1500 const char *orig_message = NULL;
1502 find_commit_subject(message, &orig_message);
1503 msg = &commit_msg;
1504 strbuf_addstr(msg, orig_message);
1505 hook_commit = "HEAD";
1507 author = amend_author = get_author(message);
1508 repo_unuse_commit_buffer(r, current_head,
1509 message);
1510 if (!author) {
1511 res = error(_("unable to parse commit author"));
1512 goto out;
1514 parents = copy_commit_list(current_head->parents);
1515 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1516 } else if (current_head &&
1517 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1518 commit_list_insert(current_head, &parents);
1521 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1522 res = error(_("git write-tree failed to write a tree"));
1523 goto out;
1526 if (!(flags & ALLOW_EMPTY)) {
1527 struct commit *first_parent = current_head;
1529 if (flags & AMEND_MSG) {
1530 if (current_head->parents) {
1531 first_parent = current_head->parents->item;
1532 if (repo_parse_commit(r, first_parent)) {
1533 res = error(_("could not parse HEAD commit"));
1534 goto out;
1536 } else {
1537 first_parent = NULL;
1540 if (oideq(first_parent
1541 ? get_commit_tree_oid(first_parent)
1542 : the_hash_algo->empty_tree,
1543 &tree)) {
1544 res = 1; /* run 'git commit' to display error message */
1545 goto out;
1549 if (hook_exists("prepare-commit-msg")) {
1550 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1551 if (res)
1552 goto out;
1553 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1554 2048) < 0) {
1555 res = error_errno(_("unable to read commit message "
1556 "from '%s'"),
1557 git_path_commit_editmsg());
1558 goto out;
1560 msg = &commit_msg;
1563 if (flags & CLEANUP_MSG)
1564 cleanup = COMMIT_MSG_CLEANUP_ALL;
1565 else if (flags & VERBATIM_MSG)
1566 cleanup = COMMIT_MSG_CLEANUP_NONE;
1567 else if ((opts->signoff || opts->record_origin) &&
1568 !opts->explicit_cleanup)
1569 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1570 else
1571 cleanup = opts->default_msg_cleanup;
1573 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1574 strbuf_stripspace(msg,
1575 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1576 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1577 res = 1; /* run 'git commit' to display error message */
1578 goto out;
1581 if (opts->committer_date_is_author_date) {
1582 struct ident_split id;
1583 struct strbuf date = STRBUF_INIT;
1585 if (!opts->ignore_date) {
1586 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1587 res = error(_("invalid author identity '%s'"),
1588 author);
1589 goto out;
1591 if (!id.date_begin) {
1592 res = error(_(
1593 "corrupt author: missing date information"));
1594 goto out;
1596 strbuf_addf(&date, "@%.*s %.*s",
1597 (int)(id.date_end - id.date_begin),
1598 id.date_begin,
1599 (int)(id.tz_end - id.tz_begin),
1600 id.tz_begin);
1601 } else {
1602 reset_ident_date();
1604 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1605 getenv("GIT_COMMITTER_EMAIL"),
1606 WANT_COMMITTER_IDENT,
1607 opts->ignore_date ? NULL : date.buf,
1608 IDENT_STRICT);
1609 strbuf_release(&date);
1610 } else {
1611 reset_ident_date();
1614 if (opts->ignore_date) {
1615 struct ident_split id;
1616 char *name, *email;
1618 if (split_ident_line(&id, author, strlen(author)) < 0) {
1619 error(_("invalid author identity '%s'"), author);
1620 goto out;
1622 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1623 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1624 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1625 IDENT_STRICT);
1626 free(name);
1627 free(email);
1630 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1631 author, committer, opts->gpg_sign, extra)) {
1632 res = error(_("failed to write commit object"));
1633 goto out;
1636 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1637 msg, &err)) {
1638 res = error("%s", err.buf);
1639 goto out;
1642 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1643 if (flags & AMEND_MSG)
1644 commit_post_rewrite(r, current_head, oid);
1646 out:
1647 free_commit_extra_headers(extra);
1648 strbuf_release(&err);
1649 strbuf_release(&commit_msg);
1650 free(amend_author);
1652 return res;
1655 static int write_rebase_head(struct object_id *oid)
1657 if (update_ref("rebase", "REBASE_HEAD", oid,
1658 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1659 return error(_("could not update %s"), "REBASE_HEAD");
1661 return 0;
1664 static int do_commit(struct repository *r,
1665 const char *msg_file, const char *author,
1666 struct replay_opts *opts, unsigned int flags,
1667 struct object_id *oid)
1669 int res = 1;
1671 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1672 struct object_id oid;
1673 struct strbuf sb = STRBUF_INIT;
1675 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1676 return error_errno(_("unable to read commit message "
1677 "from '%s'"),
1678 msg_file);
1680 res = try_to_commit(r, msg_file ? &sb : NULL,
1681 author, opts, flags, &oid);
1682 strbuf_release(&sb);
1683 if (!res) {
1684 refs_delete_ref(get_main_ref_store(r), "",
1685 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1686 unlink(git_path_merge_msg(r));
1687 if (!is_rebase_i(opts))
1688 print_commit_summary(r, NULL, &oid,
1689 SUMMARY_SHOW_AUTHOR_DATE);
1690 return res;
1693 if (res == 1) {
1694 if (is_rebase_i(opts) && oid)
1695 if (write_rebase_head(oid))
1696 return -1;
1697 return run_git_commit(msg_file, opts, flags);
1700 return res;
1703 static int is_original_commit_empty(struct commit *commit)
1705 const struct object_id *ptree_oid;
1707 if (repo_parse_commit(the_repository, commit))
1708 return error(_("could not parse commit %s"),
1709 oid_to_hex(&commit->object.oid));
1710 if (commit->parents) {
1711 struct commit *parent = commit->parents->item;
1712 if (repo_parse_commit(the_repository, parent))
1713 return error(_("could not parse parent commit %s"),
1714 oid_to_hex(&parent->object.oid));
1715 ptree_oid = get_commit_tree_oid(parent);
1716 } else {
1717 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1720 return oideq(ptree_oid, get_commit_tree_oid(commit));
1724 * Should empty commits be allowed? Return status:
1725 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1726 * 0: Halt on empty commit
1727 * 1: Allow empty commit
1728 * 2: Drop empty commit
1730 static int allow_empty(struct repository *r,
1731 struct replay_opts *opts,
1732 struct commit *commit)
1734 int index_unchanged, originally_empty;
1737 * For a commit that is initially empty, allow_empty determines if it
1738 * should be kept or not
1740 * For a commit that becomes empty, keep_redundant_commits and
1741 * drop_redundant_commits determine whether the commit should be kept or
1742 * dropped. If neither is specified, halt.
1744 index_unchanged = is_index_unchanged(r);
1745 if (index_unchanged < 0)
1746 return index_unchanged;
1747 if (!index_unchanged)
1748 return 0; /* we do not have to say --allow-empty */
1750 originally_empty = is_original_commit_empty(commit);
1751 if (originally_empty < 0)
1752 return originally_empty;
1753 if (originally_empty)
1754 return opts->allow_empty;
1755 else if (opts->keep_redundant_commits)
1756 return 1;
1757 else if (opts->drop_redundant_commits)
1758 return 2;
1759 else
1760 return 0;
1763 static struct {
1764 char c;
1765 const char *str;
1766 } todo_command_info[] = {
1767 [TODO_PICK] = { 'p', "pick" },
1768 [TODO_REVERT] = { 0, "revert" },
1769 [TODO_EDIT] = { 'e', "edit" },
1770 [TODO_REWORD] = { 'r', "reword" },
1771 [TODO_FIXUP] = { 'f', "fixup" },
1772 [TODO_SQUASH] = { 's', "squash" },
1773 [TODO_EXEC] = { 'x', "exec" },
1774 [TODO_BREAK] = { 'b', "break" },
1775 [TODO_LABEL] = { 'l', "label" },
1776 [TODO_RESET] = { 't', "reset" },
1777 [TODO_MERGE] = { 'm', "merge" },
1778 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1779 [TODO_NOOP] = { 0, "noop" },
1780 [TODO_DROP] = { 'd', "drop" },
1781 [TODO_COMMENT] = { 0, NULL },
1784 static const char *command_to_string(const enum todo_command command)
1786 if (command < TODO_COMMENT)
1787 return todo_command_info[command].str;
1788 die(_("unknown command: %d"), command);
1791 static char command_to_char(const enum todo_command command)
1793 if (command < TODO_COMMENT)
1794 return todo_command_info[command].c;
1795 return comment_line_char;
1798 static int is_noop(const enum todo_command command)
1800 return TODO_NOOP <= command;
1803 static int is_fixup(enum todo_command command)
1805 return command == TODO_FIXUP || command == TODO_SQUASH;
1808 /* Does this command create a (non-merge) commit? */
1809 static int is_pick_or_similar(enum todo_command command)
1811 switch (command) {
1812 case TODO_PICK:
1813 case TODO_REVERT:
1814 case TODO_EDIT:
1815 case TODO_REWORD:
1816 case TODO_FIXUP:
1817 case TODO_SQUASH:
1818 return 1;
1819 default:
1820 return 0;
1824 enum todo_item_flags {
1825 TODO_EDIT_MERGE_MSG = (1 << 0),
1826 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1827 TODO_EDIT_FIXUP_MSG = (1 << 2),
1830 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1831 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1832 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1833 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1834 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1836 static int is_fixup_flag(enum todo_command command, unsigned flag)
1838 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1839 (flag & TODO_EDIT_FIXUP_MSG));
1843 * Wrapper around strbuf_add_commented_lines() which avoids double
1844 * commenting commit subjects.
1846 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1848 const char *s = str;
1849 while (len > 0 && s[0] == comment_line_char) {
1850 size_t count;
1851 const char *n = memchr(s, '\n', len);
1852 if (!n)
1853 count = len;
1854 else
1855 count = n - s + 1;
1856 strbuf_add(buf, s, count);
1857 s += count;
1858 len -= count;
1860 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1863 /* Does the current fixup chain contain a squash command? */
1864 static int seen_squash(struct replay_opts *opts)
1866 return starts_with(opts->current_fixups.buf, "squash") ||
1867 strstr(opts->current_fixups.buf, "\nsquash");
1870 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1872 strbuf_setlen(buf1, 2);
1873 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1874 strbuf_addch(buf1, '\n');
1875 strbuf_setlen(buf2, 2);
1876 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1877 strbuf_addch(buf2, '\n');
1881 * Comment out any un-commented commit messages, updating the message comments
1882 * to say they will be skipped but do not comment out the empty lines that
1883 * surround commit messages and their comments.
1885 static void update_squash_message_for_fixup(struct strbuf *msg)
1887 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1888 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1889 const char *s, *start;
1890 char *orig_msg;
1891 size_t orig_msg_len;
1892 int i = 1;
1894 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1895 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1896 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1897 while (s) {
1898 const char *next;
1899 size_t off;
1900 if (skip_prefix(s, buf1.buf, &next)) {
1902 * Copy the last message, preserving the blank line
1903 * preceding the current line
1905 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1906 copy_lines(msg, start, s - start - off);
1907 if (off)
1908 strbuf_addch(msg, '\n');
1910 * The next message needs to be commented out but the
1911 * message header is already commented out so just copy
1912 * it and the blank line that follows it.
1914 strbuf_addbuf(msg, &buf2);
1915 if (*next == '\n')
1916 strbuf_addch(msg, *next++);
1917 start = s = next;
1918 copy_lines = add_commented_lines;
1919 update_comment_bufs(&buf1, &buf2, ++i);
1920 } else if (skip_prefix(s, buf2.buf, &next)) {
1921 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1922 copy_lines(msg, start, s - start - off);
1923 start = s - off;
1924 s = next;
1925 copy_lines = strbuf_add;
1926 update_comment_bufs(&buf1, &buf2, ++i);
1927 } else {
1928 s = strchr(s, '\n');
1929 if (s)
1930 s++;
1933 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1934 free(orig_msg);
1935 strbuf_release(&buf1);
1936 strbuf_release(&buf2);
1939 static int append_squash_message(struct strbuf *buf, const char *body,
1940 enum todo_command command, struct replay_opts *opts,
1941 unsigned flag)
1943 const char *fixup_msg;
1944 size_t commented_len = 0, fixup_off;
1946 * amend is non-interactive and not normally used with fixup!
1947 * or squash! commits, so only comment out those subjects when
1948 * squashing commit messages.
1950 if (starts_with(body, "amend!") ||
1951 ((command == TODO_SQUASH || seen_squash(opts)) &&
1952 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1953 commented_len = commit_subject_length(body);
1955 strbuf_addf(buf, "\n%c ", comment_line_char);
1956 strbuf_addf(buf, _(nth_commit_msg_fmt),
1957 ++opts->current_fixup_count + 1);
1958 strbuf_addstr(buf, "\n\n");
1959 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1960 /* buf->buf may be reallocated so store an offset into the buffer */
1961 fixup_off = buf->len;
1962 strbuf_addstr(buf, body + commented_len);
1964 /* fixup -C after squash behaves like squash */
1965 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1967 * We're replacing the commit message so we need to
1968 * append the Signed-off-by: trailer if the user
1969 * requested '--signoff'.
1971 if (opts->signoff)
1972 append_signoff(buf, 0, 0);
1974 if ((command == TODO_FIXUP) &&
1975 (flag & TODO_REPLACE_FIXUP_MSG) &&
1976 (file_exists(rebase_path_fixup_msg()) ||
1977 !file_exists(rebase_path_squash_msg()))) {
1978 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1979 if (write_message(fixup_msg, strlen(fixup_msg),
1980 rebase_path_fixup_msg(), 0) < 0)
1981 return error(_("cannot write '%s'"),
1982 rebase_path_fixup_msg());
1983 } else {
1984 unlink(rebase_path_fixup_msg());
1986 } else {
1987 unlink(rebase_path_fixup_msg());
1990 return 0;
1993 static int update_squash_messages(struct repository *r,
1994 enum todo_command command,
1995 struct commit *commit,
1996 struct replay_opts *opts,
1997 unsigned flag)
1999 struct strbuf buf = STRBUF_INIT;
2000 int res = 0;
2001 const char *message, *body;
2002 const char *encoding = get_commit_output_encoding();
2004 if (opts->current_fixup_count > 0) {
2005 struct strbuf header = STRBUF_INIT;
2006 char *eol;
2008 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2009 return error(_("could not read '%s'"),
2010 rebase_path_squash_msg());
2012 eol = buf.buf[0] != comment_line_char ?
2013 buf.buf : strchrnul(buf.buf, '\n');
2015 strbuf_addf(&header, "%c ", comment_line_char);
2016 strbuf_addf(&header, _(combined_commit_msg_fmt),
2017 opts->current_fixup_count + 2);
2018 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2019 strbuf_release(&header);
2020 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2021 update_squash_message_for_fixup(&buf);
2022 } else {
2023 struct object_id head;
2024 struct commit *head_commit;
2025 const char *head_message, *body;
2027 if (repo_get_oid(r, "HEAD", &head))
2028 return error(_("need a HEAD to fixup"));
2029 if (!(head_commit = lookup_commit_reference(r, &head)))
2030 return error(_("could not read HEAD"));
2031 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2032 encoding)))
2033 return error(_("could not read HEAD's commit message"));
2035 find_commit_subject(head_message, &body);
2036 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2037 rebase_path_fixup_msg(), 0) < 0) {
2038 repo_unuse_commit_buffer(r, head_commit, head_message);
2039 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2041 strbuf_addf(&buf, "%c ", comment_line_char);
2042 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2043 strbuf_addf(&buf, "\n%c ", comment_line_char);
2044 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2045 _(skip_first_commit_msg_str) :
2046 _(first_commit_msg_str));
2047 strbuf_addstr(&buf, "\n\n");
2048 if (is_fixup_flag(command, flag))
2049 strbuf_add_commented_lines(&buf, body, strlen(body),
2050 comment_line_char);
2051 else
2052 strbuf_addstr(&buf, body);
2054 repo_unuse_commit_buffer(r, head_commit, head_message);
2057 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2058 return error(_("could not read commit message of %s"),
2059 oid_to_hex(&commit->object.oid));
2060 find_commit_subject(message, &body);
2062 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2063 res = append_squash_message(&buf, body, command, opts, flag);
2064 } else if (command == TODO_FIXUP) {
2065 strbuf_addf(&buf, "\n%c ", comment_line_char);
2066 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2067 ++opts->current_fixup_count + 1);
2068 strbuf_addstr(&buf, "\n\n");
2069 strbuf_add_commented_lines(&buf, body, strlen(body),
2070 comment_line_char);
2071 } else
2072 return error(_("unknown command: %d"), command);
2073 repo_unuse_commit_buffer(r, commit, message);
2075 if (!res)
2076 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2078 strbuf_release(&buf);
2080 if (!res) {
2081 strbuf_addf(&opts->current_fixups, "%s%s %s",
2082 opts->current_fixups.len ? "\n" : "",
2083 command_to_string(command),
2084 oid_to_hex(&commit->object.oid));
2085 res = write_message(opts->current_fixups.buf,
2086 opts->current_fixups.len,
2087 rebase_path_current_fixups(), 0);
2090 return res;
2093 static void flush_rewritten_pending(void)
2095 struct strbuf buf = STRBUF_INIT;
2096 struct object_id newoid;
2097 FILE *out;
2099 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2100 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2101 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2102 char *bol = buf.buf, *eol;
2104 while (*bol) {
2105 eol = strchrnul(bol, '\n');
2106 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2107 bol, oid_to_hex(&newoid));
2108 if (!*eol)
2109 break;
2110 bol = eol + 1;
2112 fclose(out);
2113 unlink(rebase_path_rewritten_pending());
2115 strbuf_release(&buf);
2118 static void record_in_rewritten(struct object_id *oid,
2119 enum todo_command next_command)
2121 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2123 if (!out)
2124 return;
2126 fprintf(out, "%s\n", oid_to_hex(oid));
2127 fclose(out);
2129 if (!is_fixup(next_command))
2130 flush_rewritten_pending();
2133 static int should_edit(struct replay_opts *opts) {
2134 if (opts->edit < 0)
2136 * Note that we only handle the case of non-conflicted
2137 * commits; continue_single_pick() handles the conflicted
2138 * commits itself instead of calling this function.
2140 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2141 return opts->edit;
2144 static void refer_to_commit(struct replay_opts *opts,
2145 struct strbuf *msgbuf, struct commit *commit)
2147 if (opts->commit_use_reference) {
2148 struct pretty_print_context ctx = {
2149 .abbrev = DEFAULT_ABBREV,
2150 .date_mode.type = DATE_SHORT,
2152 repo_format_commit_message(the_repository, commit,
2153 "%h (%s, %ad)", msgbuf, &ctx);
2154 } else {
2155 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2159 static int do_pick_commit(struct repository *r,
2160 struct todo_item *item,
2161 struct replay_opts *opts,
2162 int final_fixup, int *check_todo)
2164 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2165 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2166 struct object_id head;
2167 struct commit *base, *next, *parent;
2168 const char *base_label, *next_label;
2169 char *author = NULL;
2170 struct commit_message msg = { NULL, NULL, NULL, NULL };
2171 struct strbuf msgbuf = STRBUF_INIT;
2172 int res, unborn = 0, reword = 0, allow, drop_commit;
2173 enum todo_command command = item->command;
2174 struct commit *commit = item->commit;
2176 if (opts->no_commit) {
2178 * We do not intend to commit immediately. We just want to
2179 * merge the differences in, so let's compute the tree
2180 * that represents the "current" state for the merge machinery
2181 * to work on.
2183 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2184 return error(_("your index file is unmerged."));
2185 } else {
2186 unborn = repo_get_oid(r, "HEAD", &head);
2187 /* Do we want to generate a root commit? */
2188 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2189 oideq(&head, &opts->squash_onto)) {
2190 if (is_fixup(command))
2191 return error(_("cannot fixup root commit"));
2192 flags |= CREATE_ROOT_COMMIT;
2193 unborn = 1;
2194 } else if (unborn)
2195 oidcpy(&head, the_hash_algo->empty_tree);
2196 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2197 NULL, 0))
2198 return error_dirty_index(r, opts);
2200 discard_index(r->index);
2202 if (!commit->parents)
2203 parent = NULL;
2204 else if (commit->parents->next) {
2205 /* Reverting or cherry-picking a merge commit */
2206 int cnt;
2207 struct commit_list *p;
2209 if (!opts->mainline)
2210 return error(_("commit %s is a merge but no -m option was given."),
2211 oid_to_hex(&commit->object.oid));
2213 for (cnt = 1, p = commit->parents;
2214 cnt != opts->mainline && p;
2215 cnt++)
2216 p = p->next;
2217 if (cnt != opts->mainline || !p)
2218 return error(_("commit %s does not have parent %d"),
2219 oid_to_hex(&commit->object.oid), opts->mainline);
2220 parent = p->item;
2221 } else if (1 < opts->mainline)
2223 * Non-first parent explicitly specified as mainline for
2224 * non-merge commit
2226 return error(_("commit %s does not have parent %d"),
2227 oid_to_hex(&commit->object.oid), opts->mainline);
2228 else
2229 parent = commit->parents->item;
2231 if (get_message(commit, &msg) != 0)
2232 return error(_("cannot get commit message for %s"),
2233 oid_to_hex(&commit->object.oid));
2235 if (opts->allow_ff && !is_fixup(command) &&
2236 ((parent && oideq(&parent->object.oid, &head)) ||
2237 (!parent && unborn))) {
2238 if (is_rebase_i(opts))
2239 write_author_script(msg.message);
2240 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2241 opts);
2242 if (res || command != TODO_REWORD)
2243 goto leave;
2244 reword = 1;
2245 msg_file = NULL;
2246 goto fast_forward_edit;
2248 if (parent && repo_parse_commit(r, parent) < 0)
2249 /* TRANSLATORS: The first %s will be a "todo" command like
2250 "revert" or "pick", the second %s a SHA1. */
2251 return error(_("%s: cannot parse parent commit %s"),
2252 command_to_string(command),
2253 oid_to_hex(&parent->object.oid));
2256 * "commit" is an existing commit. We would want to apply
2257 * the difference it introduces since its first parent "prev"
2258 * on top of the current HEAD if we are cherry-pick. Or the
2259 * reverse of it if we are revert.
2262 if (command == TODO_REVERT) {
2263 const char *orig_subject;
2265 base = commit;
2266 base_label = msg.label;
2267 next = parent;
2268 next_label = msg.parent_label;
2269 if (opts->commit_use_reference) {
2270 strbuf_addstr(&msgbuf,
2271 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2272 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2274 * We don't touch pre-existing repeated reverts, because
2275 * theoretically these can be nested arbitrarily deeply,
2276 * thus requiring excessive complexity to deal with.
2278 !starts_with(orig_subject, "Revert \"")) {
2279 strbuf_addstr(&msgbuf, "Reapply \"");
2280 strbuf_addstr(&msgbuf, orig_subject);
2281 } else {
2282 strbuf_addstr(&msgbuf, "Revert \"");
2283 strbuf_addstr(&msgbuf, msg.subject);
2284 strbuf_addstr(&msgbuf, "\"");
2286 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2287 refer_to_commit(opts, &msgbuf, commit);
2289 if (commit->parents && commit->parents->next) {
2290 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2291 refer_to_commit(opts, &msgbuf, parent);
2293 strbuf_addstr(&msgbuf, ".\n");
2294 } else {
2295 const char *p;
2297 base = parent;
2298 base_label = msg.parent_label;
2299 next = commit;
2300 next_label = msg.label;
2302 /* Append the commit log message to msgbuf. */
2303 if (find_commit_subject(msg.message, &p))
2304 strbuf_addstr(&msgbuf, p);
2306 if (opts->record_origin) {
2307 strbuf_complete_line(&msgbuf);
2308 if (!has_conforming_footer(&msgbuf, NULL, 0))
2309 strbuf_addch(&msgbuf, '\n');
2310 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2311 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2312 strbuf_addstr(&msgbuf, ")\n");
2314 if (!is_fixup(command))
2315 author = get_author(msg.message);
2318 if (command == TODO_REWORD)
2319 reword = 1;
2320 else if (is_fixup(command)) {
2321 if (update_squash_messages(r, command, commit,
2322 opts, item->flags)) {
2323 res = -1;
2324 goto leave;
2326 flags |= AMEND_MSG;
2327 if (!final_fixup)
2328 msg_file = rebase_path_squash_msg();
2329 else if (file_exists(rebase_path_fixup_msg())) {
2330 flags |= VERBATIM_MSG;
2331 msg_file = rebase_path_fixup_msg();
2332 } else {
2333 const char *dest = git_path_squash_msg(r);
2334 unlink(dest);
2335 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2336 res = error(_("could not copy '%s' to '%s'"),
2337 rebase_path_squash_msg(), dest);
2338 goto leave;
2340 unlink(git_path_merge_msg(r));
2341 msg_file = dest;
2342 flags |= EDIT_MSG;
2346 if (opts->signoff && !is_fixup(command))
2347 append_signoff(&msgbuf, 0, 0);
2349 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2350 res = -1;
2351 else if (!opts->strategy ||
2352 !strcmp(opts->strategy, "recursive") ||
2353 !strcmp(opts->strategy, "ort") ||
2354 command == TODO_REVERT) {
2355 res = do_recursive_merge(r, base, next, base_label, next_label,
2356 &head, &msgbuf, opts);
2357 if (res < 0)
2358 goto leave;
2360 res |= write_message(msgbuf.buf, msgbuf.len,
2361 git_path_merge_msg(r), 0);
2362 } else {
2363 struct commit_list *common = NULL;
2364 struct commit_list *remotes = NULL;
2366 res = write_message(msgbuf.buf, msgbuf.len,
2367 git_path_merge_msg(r), 0);
2369 commit_list_insert(base, &common);
2370 commit_list_insert(next, &remotes);
2371 res |= try_merge_command(r, opts->strategy,
2372 opts->xopts.nr, opts->xopts.v,
2373 common, oid_to_hex(&head), remotes);
2374 free_commit_list(common);
2375 free_commit_list(remotes);
2379 * If the merge was clean or if it failed due to conflict, we write
2380 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2381 * However, if the merge did not even start, then we don't want to
2382 * write it at all.
2384 if ((command == TODO_PICK || command == TODO_REWORD ||
2385 command == TODO_EDIT) && !opts->no_commit &&
2386 (res == 0 || res == 1) &&
2387 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2388 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2389 res = -1;
2390 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2391 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2392 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2393 res = -1;
2395 if (res) {
2396 error(command == TODO_REVERT
2397 ? _("could not revert %s... %s")
2398 : _("could not apply %s... %s"),
2399 short_commit_name(r, commit), msg.subject);
2400 print_advice(r, res == 1, opts);
2401 repo_rerere(r, opts->allow_rerere_auto);
2402 goto leave;
2405 drop_commit = 0;
2406 allow = allow_empty(r, opts, commit);
2407 if (allow < 0) {
2408 res = allow;
2409 goto leave;
2410 } else if (allow == 1) {
2411 flags |= ALLOW_EMPTY;
2412 } else if (allow == 2) {
2413 drop_commit = 1;
2414 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2415 NULL, REF_NO_DEREF);
2416 unlink(git_path_merge_msg(r));
2417 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2418 NULL, REF_NO_DEREF);
2419 fprintf(stderr,
2420 _("dropping %s %s -- patch contents already upstream\n"),
2421 oid_to_hex(&commit->object.oid), msg.subject);
2422 } /* else allow == 0 and there's nothing special to do */
2423 if (!opts->no_commit && !drop_commit) {
2424 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2425 res = do_commit(r, msg_file, author, opts, flags,
2426 commit? &commit->object.oid : NULL);
2427 else
2428 res = error(_("unable to parse commit author"));
2429 *check_todo = !!(flags & EDIT_MSG);
2430 if (!res && reword) {
2431 fast_forward_edit:
2432 res = run_git_commit(NULL, opts, EDIT_MSG |
2433 VERIFY_MSG | AMEND_MSG |
2434 (flags & ALLOW_EMPTY));
2435 *check_todo = 1;
2440 if (!res && final_fixup) {
2441 unlink(rebase_path_fixup_msg());
2442 unlink(rebase_path_squash_msg());
2443 unlink(rebase_path_current_fixups());
2444 strbuf_reset(&opts->current_fixups);
2445 opts->current_fixup_count = 0;
2448 leave:
2449 free_message(commit, &msg);
2450 free(author);
2451 strbuf_release(&msgbuf);
2452 update_abort_safety_file();
2454 return res;
2457 static int prepare_revs(struct replay_opts *opts)
2460 * picking (but not reverting) ranges (but not individual revisions)
2461 * should be done in reverse
2463 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2464 opts->revs->reverse ^= 1;
2466 if (prepare_revision_walk(opts->revs))
2467 return error(_("revision walk setup failed"));
2469 return 0;
2472 static int read_and_refresh_cache(struct repository *r,
2473 struct replay_opts *opts)
2475 struct lock_file index_lock = LOCK_INIT;
2476 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2477 if (repo_read_index(r) < 0) {
2478 rollback_lock_file(&index_lock);
2479 return error(_("git %s: failed to read the index"),
2480 action_name(opts));
2482 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2484 if (index_fd >= 0) {
2485 if (write_locked_index(r->index, &index_lock,
2486 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2487 return error(_("git %s: failed to refresh the index"),
2488 action_name(opts));
2493 * If we are resolving merges in any way other than "ort", then
2494 * expand the sparse index.
2496 if (opts->strategy && strcmp(opts->strategy, "ort"))
2497 ensure_full_index(r->index);
2498 return 0;
2501 void todo_list_release(struct todo_list *todo_list)
2503 strbuf_release(&todo_list->buf);
2504 FREE_AND_NULL(todo_list->items);
2505 todo_list->nr = todo_list->alloc = 0;
2508 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2510 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2511 return todo_list->items + todo_list->nr++;
2514 const char *todo_item_get_arg(struct todo_list *todo_list,
2515 struct todo_item *item)
2517 return todo_list->buf.buf + item->arg_offset;
2520 static int is_command(enum todo_command command, const char **bol)
2522 const char *str = todo_command_info[command].str;
2523 const char nick = todo_command_info[command].c;
2524 const char *p = *bol;
2526 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2527 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2528 (*bol = p);
2531 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2533 switch (command) {
2534 case TODO_LABEL:
2536 * '#' is not a valid label as the merge command uses it to
2537 * separate merge parents from the commit subject.
2539 if (!strcmp(arg, "#") ||
2540 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2541 return error(_("'%s' is not a valid label"), arg);
2542 break;
2544 case TODO_UPDATE_REF:
2545 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2546 return error(_("'%s' is not a valid refname"), arg);
2547 if (check_refname_format(arg, 0))
2548 return error(_("update-ref requires a fully qualified "
2549 "refname e.g. refs/heads/%s"), arg);
2550 break;
2552 default:
2553 BUG("unexpected todo_command");
2556 return 0;
2559 static int parse_insn_line(struct repository *r, struct todo_item *item,
2560 const char *buf, const char *bol, char *eol)
2562 struct object_id commit_oid;
2563 char *end_of_object_name;
2564 int i, saved, status, padding;
2566 item->flags = 0;
2568 /* left-trim */
2569 bol += strspn(bol, " \t");
2571 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2572 item->command = TODO_COMMENT;
2573 item->commit = NULL;
2574 item->arg_offset = bol - buf;
2575 item->arg_len = eol - bol;
2576 return 0;
2579 for (i = 0; i < TODO_COMMENT; i++)
2580 if (is_command(i, &bol)) {
2581 item->command = i;
2582 break;
2584 if (i >= TODO_COMMENT)
2585 return error(_("invalid command '%.*s'"),
2586 (int)strcspn(bol, " \t\r\n"), bol);
2588 /* Eat up extra spaces/ tabs before object name */
2589 padding = strspn(bol, " \t");
2590 bol += padding;
2592 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2593 if (bol != eol)
2594 return error(_("%s does not accept arguments: '%s'"),
2595 command_to_string(item->command), bol);
2596 item->commit = NULL;
2597 item->arg_offset = bol - buf;
2598 item->arg_len = eol - bol;
2599 return 0;
2602 if (!padding)
2603 return error(_("missing arguments for %s"),
2604 command_to_string(item->command));
2606 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2607 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2608 int ret = 0;
2610 item->commit = NULL;
2611 item->arg_offset = bol - buf;
2612 item->arg_len = (int)(eol - bol);
2613 if (item->command == TODO_LABEL ||
2614 item->command == TODO_UPDATE_REF) {
2615 saved = *eol;
2616 *eol = '\0';
2617 ret = check_label_or_ref_arg(item->command, bol);
2618 *eol = saved;
2620 return ret;
2623 if (item->command == TODO_FIXUP) {
2624 if (skip_prefix(bol, "-C", &bol)) {
2625 bol += strspn(bol, " \t");
2626 item->flags |= TODO_REPLACE_FIXUP_MSG;
2627 } else if (skip_prefix(bol, "-c", &bol)) {
2628 bol += strspn(bol, " \t");
2629 item->flags |= TODO_EDIT_FIXUP_MSG;
2633 if (item->command == TODO_MERGE) {
2634 if (skip_prefix(bol, "-C", &bol))
2635 bol += strspn(bol, " \t");
2636 else if (skip_prefix(bol, "-c", &bol)) {
2637 bol += strspn(bol, " \t");
2638 item->flags |= TODO_EDIT_MERGE_MSG;
2639 } else {
2640 item->flags |= TODO_EDIT_MERGE_MSG;
2641 item->commit = NULL;
2642 item->arg_offset = bol - buf;
2643 item->arg_len = (int)(eol - bol);
2644 return 0;
2648 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2649 saved = *end_of_object_name;
2650 *end_of_object_name = '\0';
2651 status = repo_get_oid(r, bol, &commit_oid);
2652 if (status < 0)
2653 error(_("could not parse '%s'"), bol); /* return later */
2654 *end_of_object_name = saved;
2656 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2657 item->arg_offset = bol - buf;
2658 item->arg_len = (int)(eol - bol);
2660 if (status < 0)
2661 return status;
2663 item->commit = lookup_commit_reference(r, &commit_oid);
2664 return item->commit ? 0 : -1;
2667 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2669 const char *todo_file, *bol;
2670 struct strbuf buf = STRBUF_INIT;
2671 int ret = 0;
2673 todo_file = git_path_todo_file();
2674 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2675 if (errno == ENOENT || errno == ENOTDIR)
2676 return -1;
2677 else
2678 return error_errno("unable to open '%s'", todo_file);
2680 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2681 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2682 *action = REPLAY_PICK;
2683 else if (is_command(TODO_REVERT, &bol) &&
2684 (*bol == ' ' || *bol == '\t'))
2685 *action = REPLAY_REVERT;
2686 else
2687 ret = -1;
2689 strbuf_release(&buf);
2691 return ret;
2694 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2695 struct todo_list *todo_list)
2697 struct todo_item *item;
2698 char *p = buf, *next_p;
2699 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2701 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2703 for (i = 1; *p; i++, p = next_p) {
2704 char *eol = strchrnul(p, '\n');
2706 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2708 if (p != eol && eol[-1] == '\r')
2709 eol--; /* strip Carriage Return */
2711 item = append_new_todo(todo_list);
2712 item->offset_in_buf = p - todo_list->buf.buf;
2713 if (parse_insn_line(r, item, buf, p, eol)) {
2714 res = error(_("invalid line %d: %.*s"),
2715 i, (int)(eol - p), p);
2716 item->command = TODO_COMMENT + 1;
2717 item->arg_offset = p - buf;
2718 item->arg_len = (int)(eol - p);
2719 item->commit = NULL;
2722 if (item->command != TODO_COMMENT)
2723 todo_list->total_nr++;
2725 if (fixup_okay)
2726 ; /* do nothing */
2727 else if (is_fixup(item->command))
2728 res = error(_("cannot '%s' without a previous commit"),
2729 command_to_string(item->command));
2730 else if (!is_noop(item->command))
2731 fixup_okay = 1;
2734 return res;
2737 static int count_commands(struct todo_list *todo_list)
2739 int count = 0, i;
2741 for (i = 0; i < todo_list->nr; i++)
2742 if (todo_list->items[i].command != TODO_COMMENT)
2743 count++;
2745 return count;
2748 static int get_item_line_offset(struct todo_list *todo_list, int index)
2750 return index < todo_list->nr ?
2751 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2754 static const char *get_item_line(struct todo_list *todo_list, int index)
2756 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2759 static int get_item_line_length(struct todo_list *todo_list, int index)
2761 return get_item_line_offset(todo_list, index + 1)
2762 - get_item_line_offset(todo_list, index);
2765 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2767 int fd;
2768 ssize_t len;
2770 fd = open(path, O_RDONLY);
2771 if (fd < 0)
2772 return error_errno(_("could not open '%s'"), path);
2773 len = strbuf_read(sb, fd, 0);
2774 close(fd);
2775 if (len < 0)
2776 return error(_("could not read '%s'."), path);
2777 return len;
2780 static int have_finished_the_last_pick(void)
2782 struct strbuf buf = STRBUF_INIT;
2783 const char *eol;
2784 const char *todo_path = git_path_todo_file();
2785 int ret = 0;
2787 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2788 if (errno == ENOENT) {
2789 return 0;
2790 } else {
2791 error_errno("unable to open '%s'", todo_path);
2792 return 0;
2795 /* If there is only one line then we are done */
2796 eol = strchr(buf.buf, '\n');
2797 if (!eol || !eol[1])
2798 ret = 1;
2800 strbuf_release(&buf);
2802 return ret;
2805 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2807 struct replay_opts opts = REPLAY_OPTS_INIT;
2808 int need_cleanup = 0;
2810 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2811 if (!refs_delete_ref(get_main_ref_store(r), "",
2812 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2813 verbose)
2814 warning(_("cancelling a cherry picking in progress"));
2815 opts.action = REPLAY_PICK;
2816 need_cleanup = 1;
2819 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2820 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2821 NULL, REF_NO_DEREF) &&
2822 verbose)
2823 warning(_("cancelling a revert in progress"));
2824 opts.action = REPLAY_REVERT;
2825 need_cleanup = 1;
2828 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2829 NULL, REF_NO_DEREF);
2831 if (!need_cleanup)
2832 return;
2834 if (!have_finished_the_last_pick())
2835 return;
2837 sequencer_remove_state(&opts);
2840 static void todo_list_write_total_nr(struct todo_list *todo_list)
2842 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2844 if (f) {
2845 fprintf(f, "%d\n", todo_list->total_nr);
2846 fclose(f);
2850 static int read_populate_todo(struct repository *r,
2851 struct todo_list *todo_list,
2852 struct replay_opts *opts)
2854 const char *todo_file = get_todo_path(opts);
2855 int res;
2857 strbuf_reset(&todo_list->buf);
2858 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2859 return -1;
2861 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2862 if (res) {
2863 if (is_rebase_i(opts))
2864 return error(_("please fix this using "
2865 "'git rebase --edit-todo'."));
2866 return error(_("unusable instruction sheet: '%s'"), todo_file);
2869 if (!todo_list->nr &&
2870 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2871 return error(_("no commits parsed."));
2873 if (!is_rebase_i(opts)) {
2874 enum todo_command valid =
2875 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2876 int i;
2878 for (i = 0; i < todo_list->nr; i++)
2879 if (valid == todo_list->items[i].command)
2880 continue;
2881 else if (valid == TODO_PICK)
2882 return error(_("cannot cherry-pick during a revert."));
2883 else
2884 return error(_("cannot revert during a cherry-pick."));
2887 if (is_rebase_i(opts)) {
2888 struct todo_list done = TODO_LIST_INIT;
2890 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2891 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2892 todo_list->done_nr = count_commands(&done);
2893 else
2894 todo_list->done_nr = 0;
2896 todo_list->total_nr = todo_list->done_nr
2897 + count_commands(todo_list);
2898 todo_list_release(&done);
2900 todo_list_write_total_nr(todo_list);
2903 return 0;
2906 static int git_config_string_dup(char **dest,
2907 const char *var, const char *value)
2909 if (!value)
2910 return config_error_nonbool(var);
2911 free(*dest);
2912 *dest = xstrdup(value);
2913 return 0;
2916 static int populate_opts_cb(const char *key, const char *value,
2917 const struct config_context *ctx,
2918 void *data)
2920 struct replay_opts *opts = data;
2921 int error_flag = 1;
2923 if (!value)
2924 error_flag = 0;
2925 else if (!strcmp(key, "options.no-commit"))
2926 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2927 else if (!strcmp(key, "options.edit"))
2928 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2929 else if (!strcmp(key, "options.allow-empty"))
2930 opts->allow_empty =
2931 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2932 else if (!strcmp(key, "options.allow-empty-message"))
2933 opts->allow_empty_message =
2934 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2935 else if (!strcmp(key, "options.keep-redundant-commits"))
2936 opts->keep_redundant_commits =
2937 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2938 else if (!strcmp(key, "options.signoff"))
2939 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2940 else if (!strcmp(key, "options.record-origin"))
2941 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2942 else if (!strcmp(key, "options.allow-ff"))
2943 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2944 else if (!strcmp(key, "options.mainline"))
2945 opts->mainline = git_config_int(key, value, ctx->kvi);
2946 else if (!strcmp(key, "options.strategy"))
2947 git_config_string_dup(&opts->strategy, key, value);
2948 else if (!strcmp(key, "options.gpg-sign"))
2949 git_config_string_dup(&opts->gpg_sign, key, value);
2950 else if (!strcmp(key, "options.strategy-option")) {
2951 strvec_push(&opts->xopts, value);
2952 } else if (!strcmp(key, "options.allow-rerere-auto"))
2953 opts->allow_rerere_auto =
2954 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
2955 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2956 else if (!strcmp(key, "options.default-msg-cleanup")) {
2957 opts->explicit_cleanup = 1;
2958 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2959 } else
2960 return error(_("invalid key: %s"), key);
2962 if (!error_flag)
2963 return error(_("invalid value for '%s': '%s'"), key, value);
2965 return 0;
2968 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2970 int i;
2971 int count;
2972 const char **argv;
2973 char *strategy_opts_string = raw_opts;
2975 if (*strategy_opts_string == ' ')
2976 strategy_opts_string++;
2978 count = split_cmdline(strategy_opts_string, &argv);
2979 if (count < 0)
2980 BUG("could not split '%s': %s", strategy_opts_string,
2981 split_cmdline_strerror(count));
2982 for (i = 0; i < count; i++) {
2983 const char *arg = argv[i];
2985 skip_prefix(arg, "--", &arg);
2986 strvec_push(&opts->xopts, arg);
2988 free(argv);
2991 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2993 strbuf_reset(buf);
2994 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2995 return;
2996 opts->strategy = strbuf_detach(buf, NULL);
2997 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2998 return;
3000 parse_strategy_opts(opts, buf->buf);
3003 static int read_populate_opts(struct replay_opts *opts)
3005 if (is_rebase_i(opts)) {
3006 struct strbuf buf = STRBUF_INIT;
3007 int ret = 0;
3009 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3010 READ_ONELINER_SKIP_IF_EMPTY)) {
3011 if (!starts_with(buf.buf, "-S"))
3012 strbuf_reset(&buf);
3013 else {
3014 free(opts->gpg_sign);
3015 opts->gpg_sign = xstrdup(buf.buf + 2);
3017 strbuf_reset(&buf);
3020 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3021 READ_ONELINER_SKIP_IF_EMPTY)) {
3022 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3023 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3024 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3025 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3026 strbuf_reset(&buf);
3029 if (file_exists(rebase_path_verbose()))
3030 opts->verbose = 1;
3032 if (file_exists(rebase_path_quiet()))
3033 opts->quiet = 1;
3035 if (file_exists(rebase_path_signoff())) {
3036 opts->allow_ff = 0;
3037 opts->signoff = 1;
3040 if (file_exists(rebase_path_cdate_is_adate())) {
3041 opts->allow_ff = 0;
3042 opts->committer_date_is_author_date = 1;
3045 if (file_exists(rebase_path_ignore_date())) {
3046 opts->allow_ff = 0;
3047 opts->ignore_date = 1;
3050 if (file_exists(rebase_path_reschedule_failed_exec()))
3051 opts->reschedule_failed_exec = 1;
3052 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3053 opts->reschedule_failed_exec = 0;
3055 if (file_exists(rebase_path_drop_redundant_commits()))
3056 opts->drop_redundant_commits = 1;
3058 if (file_exists(rebase_path_keep_redundant_commits()))
3059 opts->keep_redundant_commits = 1;
3061 read_strategy_opts(opts, &buf);
3062 strbuf_reset(&buf);
3064 if (read_oneliner(&opts->current_fixups,
3065 rebase_path_current_fixups(),
3066 READ_ONELINER_SKIP_IF_EMPTY)) {
3067 const char *p = opts->current_fixups.buf;
3068 opts->current_fixup_count = 1;
3069 while ((p = strchr(p, '\n'))) {
3070 opts->current_fixup_count++;
3071 p++;
3075 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3076 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3077 ret = error(_("unusable squash-onto"));
3078 goto done_rebase_i;
3080 opts->have_squash_onto = 1;
3083 done_rebase_i:
3084 strbuf_release(&buf);
3085 return ret;
3088 if (!file_exists(git_path_opts_file()))
3089 return 0;
3091 * The function git_parse_source(), called from git_config_from_file(),
3092 * may die() in case of a syntactically incorrect file. We do not care
3093 * about this case, though, because we wrote that file ourselves, so we
3094 * are pretty certain that it is syntactically correct.
3096 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3097 return error(_("malformed options sheet: '%s'"),
3098 git_path_opts_file());
3099 return 0;
3102 static void write_strategy_opts(struct replay_opts *opts)
3104 struct strbuf buf = STRBUF_INIT;
3107 * Quote strategy options so that they can be read correctly
3108 * by split_cmdline().
3110 quote_cmdline(&buf, opts->xopts.v);
3111 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3112 strbuf_release(&buf);
3115 int write_basic_state(struct replay_opts *opts, const char *head_name,
3116 struct commit *onto, const struct object_id *orig_head)
3118 if (head_name)
3119 write_file(rebase_path_head_name(), "%s\n", head_name);
3120 if (onto)
3121 write_file(rebase_path_onto(), "%s\n",
3122 oid_to_hex(&onto->object.oid));
3123 if (orig_head)
3124 write_file(rebase_path_orig_head(), "%s\n",
3125 oid_to_hex(orig_head));
3127 if (opts->quiet)
3128 write_file(rebase_path_quiet(), "%s", "");
3129 if (opts->verbose)
3130 write_file(rebase_path_verbose(), "%s", "");
3131 if (opts->strategy)
3132 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3133 if (opts->xopts.nr > 0)
3134 write_strategy_opts(opts);
3136 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3137 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3138 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3139 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3141 if (opts->gpg_sign)
3142 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3143 if (opts->signoff)
3144 write_file(rebase_path_signoff(), "--signoff\n");
3145 if (opts->drop_redundant_commits)
3146 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3147 if (opts->keep_redundant_commits)
3148 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3149 if (opts->committer_date_is_author_date)
3150 write_file(rebase_path_cdate_is_adate(), "%s", "");
3151 if (opts->ignore_date)
3152 write_file(rebase_path_ignore_date(), "%s", "");
3153 if (opts->reschedule_failed_exec)
3154 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3155 else
3156 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3158 return 0;
3161 static int walk_revs_populate_todo(struct todo_list *todo_list,
3162 struct replay_opts *opts)
3164 enum todo_command command = opts->action == REPLAY_PICK ?
3165 TODO_PICK : TODO_REVERT;
3166 const char *command_string = todo_command_info[command].str;
3167 const char *encoding;
3168 struct commit *commit;
3170 if (prepare_revs(opts))
3171 return -1;
3173 encoding = get_log_output_encoding();
3175 while ((commit = get_revision(opts->revs))) {
3176 struct todo_item *item = append_new_todo(todo_list);
3177 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3178 commit, NULL,
3179 encoding);
3180 const char *subject;
3181 int subject_len;
3183 item->command = command;
3184 item->commit = commit;
3185 item->arg_offset = 0;
3186 item->arg_len = 0;
3187 item->offset_in_buf = todo_list->buf.len;
3188 subject_len = find_commit_subject(commit_buffer, &subject);
3189 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3190 short_commit_name(the_repository, commit),
3191 subject_len, subject);
3192 repo_unuse_commit_buffer(the_repository, commit,
3193 commit_buffer);
3196 if (!todo_list->nr)
3197 return error(_("empty commit set passed"));
3199 return 0;
3202 static int create_seq_dir(struct repository *r)
3204 enum replay_action action;
3205 const char *in_progress_error = NULL;
3206 const char *in_progress_advice = NULL;
3207 unsigned int advise_skip =
3208 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3209 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3211 if (!sequencer_get_last_command(r, &action)) {
3212 switch (action) {
3213 case REPLAY_REVERT:
3214 in_progress_error = _("revert is already in progress");
3215 in_progress_advice =
3216 _("try \"git revert (--continue | %s--abort | --quit)\"");
3217 break;
3218 case REPLAY_PICK:
3219 in_progress_error = _("cherry-pick is already in progress");
3220 in_progress_advice =
3221 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3222 break;
3223 default:
3224 BUG("unexpected action in create_seq_dir");
3227 if (in_progress_error) {
3228 error("%s", in_progress_error);
3229 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3230 advise(in_progress_advice,
3231 advise_skip ? "--skip | " : "");
3232 return -1;
3234 if (mkdir(git_path_seq_dir(), 0777) < 0)
3235 return error_errno(_("could not create sequencer directory '%s'"),
3236 git_path_seq_dir());
3238 return 0;
3241 static int save_head(const char *head)
3243 return write_message(head, strlen(head), git_path_head_file(), 1);
3246 static int rollback_is_safe(void)
3248 struct strbuf sb = STRBUF_INIT;
3249 struct object_id expected_head, actual_head;
3251 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3252 strbuf_trim(&sb);
3253 if (get_oid_hex(sb.buf, &expected_head)) {
3254 strbuf_release(&sb);
3255 die(_("could not parse %s"), git_path_abort_safety_file());
3257 strbuf_release(&sb);
3259 else if (errno == ENOENT)
3260 oidclr(&expected_head);
3261 else
3262 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3264 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3265 oidclr(&actual_head);
3267 return oideq(&actual_head, &expected_head);
3270 static int reset_merge(const struct object_id *oid)
3272 struct child_process cmd = CHILD_PROCESS_INIT;
3274 cmd.git_cmd = 1;
3275 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3277 if (!is_null_oid(oid))
3278 strvec_push(&cmd.args, oid_to_hex(oid));
3280 return run_command(&cmd);
3283 static int rollback_single_pick(struct repository *r)
3285 struct object_id head_oid;
3287 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3288 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3289 return error(_("no cherry-pick or revert in progress"));
3290 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3291 return error(_("cannot resolve HEAD"));
3292 if (is_null_oid(&head_oid))
3293 return error(_("cannot abort from a branch yet to be born"));
3294 return reset_merge(&head_oid);
3297 static int skip_single_pick(void)
3299 struct object_id head;
3301 if (read_ref_full("HEAD", 0, &head, NULL))
3302 return error(_("cannot resolve HEAD"));
3303 return reset_merge(&head);
3306 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3308 FILE *f;
3309 struct object_id oid;
3310 struct strbuf buf = STRBUF_INIT;
3311 const char *p;
3313 f = fopen(git_path_head_file(), "r");
3314 if (!f && errno == ENOENT) {
3316 * There is no multiple-cherry-pick in progress.
3317 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3318 * a single-cherry-pick in progress, abort that.
3320 return rollback_single_pick(r);
3322 if (!f)
3323 return error_errno(_("cannot open '%s'"), git_path_head_file());
3324 if (strbuf_getline_lf(&buf, f)) {
3325 error(_("cannot read '%s': %s"), git_path_head_file(),
3326 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3327 fclose(f);
3328 goto fail;
3330 fclose(f);
3331 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3332 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3333 git_path_head_file());
3334 goto fail;
3336 if (is_null_oid(&oid)) {
3337 error(_("cannot abort from a branch yet to be born"));
3338 goto fail;
3341 if (!rollback_is_safe()) {
3342 /* Do not error, just do not rollback */
3343 warning(_("You seem to have moved HEAD. "
3344 "Not rewinding, check your HEAD!"));
3345 } else
3346 if (reset_merge(&oid))
3347 goto fail;
3348 strbuf_release(&buf);
3349 return sequencer_remove_state(opts);
3350 fail:
3351 strbuf_release(&buf);
3352 return -1;
3355 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3357 enum replay_action action = -1;
3358 sequencer_get_last_command(r, &action);
3361 * Check whether the subcommand requested to skip the commit is actually
3362 * in progress and that it's safe to skip the commit.
3364 * opts->action tells us which subcommand requested to skip the commit.
3365 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3366 * action is in progress and we can skip the commit.
3368 * Otherwise we check that the last instruction was related to the
3369 * particular subcommand we're trying to execute and barf if that's not
3370 * the case.
3372 * Finally we check that the rollback is "safe", i.e., has the HEAD
3373 * moved? In this case, it doesn't make sense to "reset the merge" and
3374 * "skip the commit" as the user already handled this by committing. But
3375 * we'd not want to barf here, instead give advice on how to proceed. We
3376 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3377 * it gets removed when the user commits, so if it still exists we're
3378 * sure the user can't have committed before.
3380 switch (opts->action) {
3381 case REPLAY_REVERT:
3382 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3383 if (action != REPLAY_REVERT)
3384 return error(_("no revert in progress"));
3385 if (!rollback_is_safe())
3386 goto give_advice;
3388 break;
3389 case REPLAY_PICK:
3390 if (!refs_ref_exists(get_main_ref_store(r),
3391 "CHERRY_PICK_HEAD")) {
3392 if (action != REPLAY_PICK)
3393 return error(_("no cherry-pick in progress"));
3394 if (!rollback_is_safe())
3395 goto give_advice;
3397 break;
3398 default:
3399 BUG("unexpected action in sequencer_skip");
3402 if (skip_single_pick())
3403 return error(_("failed to skip the commit"));
3404 if (!is_directory(git_path_seq_dir()))
3405 return 0;
3407 return sequencer_continue(r, opts);
3409 give_advice:
3410 error(_("there is nothing to skip"));
3412 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3413 advise(_("have you committed already?\n"
3414 "try \"git %s --continue\""),
3415 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3417 return -1;
3420 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3421 int reschedule)
3423 struct lock_file todo_lock = LOCK_INIT;
3424 const char *todo_path = get_todo_path(opts);
3425 int next = todo_list->current, offset, fd;
3428 * rebase -i writes "git-rebase-todo" without the currently executing
3429 * command, appending it to "done" instead.
3431 if (is_rebase_i(opts) && !reschedule)
3432 next++;
3434 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3435 if (fd < 0)
3436 return error_errno(_("could not lock '%s'"), todo_path);
3437 offset = get_item_line_offset(todo_list, next);
3438 if (write_in_full(fd, todo_list->buf.buf + offset,
3439 todo_list->buf.len - offset) < 0)
3440 return error_errno(_("could not write to '%s'"), todo_path);
3441 if (commit_lock_file(&todo_lock) < 0)
3442 return error(_("failed to finalize '%s'"), todo_path);
3444 if (is_rebase_i(opts) && !reschedule && next > 0) {
3445 const char *done = rebase_path_done();
3446 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3447 int ret = 0;
3449 if (fd < 0)
3450 return 0;
3451 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3452 get_item_line_length(todo_list, next - 1))
3453 < 0)
3454 ret = error_errno(_("could not write to '%s'"), done);
3455 if (close(fd) < 0)
3456 ret = error_errno(_("failed to finalize '%s'"), done);
3457 return ret;
3459 return 0;
3462 static int save_opts(struct replay_opts *opts)
3464 const char *opts_file = git_path_opts_file();
3465 int res = 0;
3467 if (opts->no_commit)
3468 res |= git_config_set_in_file_gently(opts_file,
3469 "options.no-commit", "true");
3470 if (opts->edit >= 0)
3471 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3472 opts->edit ? "true" : "false");
3473 if (opts->allow_empty)
3474 res |= git_config_set_in_file_gently(opts_file,
3475 "options.allow-empty", "true");
3476 if (opts->allow_empty_message)
3477 res |= git_config_set_in_file_gently(opts_file,
3478 "options.allow-empty-message", "true");
3479 if (opts->keep_redundant_commits)
3480 res |= git_config_set_in_file_gently(opts_file,
3481 "options.keep-redundant-commits", "true");
3482 if (opts->signoff)
3483 res |= git_config_set_in_file_gently(opts_file,
3484 "options.signoff", "true");
3485 if (opts->record_origin)
3486 res |= git_config_set_in_file_gently(opts_file,
3487 "options.record-origin", "true");
3488 if (opts->allow_ff)
3489 res |= git_config_set_in_file_gently(opts_file,
3490 "options.allow-ff", "true");
3491 if (opts->mainline) {
3492 struct strbuf buf = STRBUF_INIT;
3493 strbuf_addf(&buf, "%d", opts->mainline);
3494 res |= git_config_set_in_file_gently(opts_file,
3495 "options.mainline", buf.buf);
3496 strbuf_release(&buf);
3498 if (opts->strategy)
3499 res |= git_config_set_in_file_gently(opts_file,
3500 "options.strategy", opts->strategy);
3501 if (opts->gpg_sign)
3502 res |= git_config_set_in_file_gently(opts_file,
3503 "options.gpg-sign", opts->gpg_sign);
3504 for (size_t i = 0; i < opts->xopts.nr; i++)
3505 res |= git_config_set_multivar_in_file_gently(opts_file,
3506 "options.strategy-option",
3507 opts->xopts.v[i], "^$", 0);
3508 if (opts->allow_rerere_auto)
3509 res |= git_config_set_in_file_gently(opts_file,
3510 "options.allow-rerere-auto",
3511 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3512 "true" : "false");
3514 if (opts->explicit_cleanup)
3515 res |= git_config_set_in_file_gently(opts_file,
3516 "options.default-msg-cleanup",
3517 describe_cleanup_mode(opts->default_msg_cleanup));
3518 return res;
3521 static int make_patch(struct repository *r,
3522 struct commit *commit,
3523 struct replay_opts *opts)
3525 struct rev_info log_tree_opt;
3526 const char *subject;
3527 char hex[GIT_MAX_HEXSZ + 1];
3528 int res = 0;
3530 if (!is_rebase_i(opts))
3531 BUG("make_patch should only be called when rebasing");
3533 oid_to_hex_r(hex, &commit->object.oid);
3534 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3535 return -1;
3536 res |= write_rebase_head(&commit->object.oid);
3538 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3539 repo_init_revisions(r, &log_tree_opt, NULL);
3540 log_tree_opt.abbrev = 0;
3541 log_tree_opt.diff = 1;
3542 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3543 log_tree_opt.disable_stdin = 1;
3544 log_tree_opt.no_commit_id = 1;
3545 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3546 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3547 if (!log_tree_opt.diffopt.file)
3548 res |= error_errno(_("could not open '%s'"),
3549 rebase_path_patch());
3550 else {
3551 res |= log_tree_commit(&log_tree_opt, commit);
3552 fclose(log_tree_opt.diffopt.file);
3555 if (!file_exists(rebase_path_message())) {
3556 const char *encoding = get_commit_output_encoding();
3557 const char *commit_buffer = repo_logmsg_reencode(r,
3558 commit, NULL,
3559 encoding);
3560 find_commit_subject(commit_buffer, &subject);
3561 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3562 repo_unuse_commit_buffer(r, commit,
3563 commit_buffer);
3565 release_revisions(&log_tree_opt);
3567 return res;
3570 static int intend_to_amend(void)
3572 struct object_id head;
3573 char *p;
3575 if (repo_get_oid(the_repository, "HEAD", &head))
3576 return error(_("cannot read HEAD"));
3578 p = oid_to_hex(&head);
3579 return write_message(p, strlen(p), rebase_path_amend(), 1);
3582 static int error_with_patch(struct repository *r,
3583 struct commit *commit,
3584 const char *subject, int subject_len,
3585 struct replay_opts *opts,
3586 int exit_code, int to_amend)
3588 if (commit) {
3589 if (make_patch(r, commit, opts))
3590 return -1;
3591 } else if (copy_file(rebase_path_message(),
3592 git_path_merge_msg(r), 0666))
3593 return error(_("unable to copy '%s' to '%s'"),
3594 git_path_merge_msg(r), rebase_path_message());
3596 if (to_amend) {
3597 if (intend_to_amend())
3598 return -1;
3600 fprintf(stderr,
3601 _("You can amend the commit now, with\n"
3602 "\n"
3603 " git commit --amend %s\n"
3604 "\n"
3605 "Once you are satisfied with your changes, run\n"
3606 "\n"
3607 " git rebase --continue\n"),
3608 gpg_sign_opt_quoted(opts));
3609 } else if (exit_code) {
3610 if (commit)
3611 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3612 short_commit_name(r, commit), subject_len, subject);
3613 else
3615 * We don't have the hash of the parent so
3616 * just print the line from the todo file.
3618 fprintf_ln(stderr, _("Could not merge %.*s"),
3619 subject_len, subject);
3622 return exit_code;
3625 static int error_failed_squash(struct repository *r,
3626 struct commit *commit,
3627 struct replay_opts *opts,
3628 int subject_len,
3629 const char *subject)
3631 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3632 return error(_("could not copy '%s' to '%s'"),
3633 rebase_path_squash_msg(), rebase_path_message());
3634 unlink(git_path_merge_msg(r));
3635 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3636 return error(_("could not copy '%s' to '%s'"),
3637 rebase_path_message(),
3638 git_path_merge_msg(r));
3639 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3642 static int do_exec(struct repository *r, const char *command_line)
3644 struct child_process cmd = CHILD_PROCESS_INIT;
3645 int dirty, status;
3647 fprintf(stderr, _("Executing: %s\n"), command_line);
3648 cmd.use_shell = 1;
3649 strvec_push(&cmd.args, command_line);
3650 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3651 status = run_command(&cmd);
3653 /* force re-reading of the cache */
3654 discard_index(r->index);
3655 if (repo_read_index(r) < 0)
3656 return error(_("could not read index"));
3658 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3660 if (status) {
3661 warning(_("execution failed: %s\n%s"
3662 "You can fix the problem, and then run\n"
3663 "\n"
3664 " git rebase --continue\n"
3665 "\n"),
3666 command_line,
3667 dirty ? _("and made changes to the index and/or the "
3668 "working tree.\n") : "");
3669 if (status == 127)
3670 /* command not found */
3671 status = 1;
3672 } else if (dirty) {
3673 warning(_("execution succeeded: %s\nbut "
3674 "left changes to the index and/or the working tree.\n"
3675 "Commit or stash your changes, and then run\n"
3676 "\n"
3677 " git rebase --continue\n"
3678 "\n"), command_line);
3679 status = 1;
3682 return status;
3685 __attribute__((format (printf, 2, 3)))
3686 static int safe_append(const char *filename, const char *fmt, ...)
3688 va_list ap;
3689 struct lock_file lock = LOCK_INIT;
3690 int fd = hold_lock_file_for_update(&lock, filename,
3691 LOCK_REPORT_ON_ERROR);
3692 struct strbuf buf = STRBUF_INIT;
3694 if (fd < 0)
3695 return -1;
3697 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3698 error_errno(_("could not read '%s'"), filename);
3699 rollback_lock_file(&lock);
3700 return -1;
3702 strbuf_complete(&buf, '\n');
3703 va_start(ap, fmt);
3704 strbuf_vaddf(&buf, fmt, ap);
3705 va_end(ap);
3707 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3708 error_errno(_("could not write to '%s'"), filename);
3709 strbuf_release(&buf);
3710 rollback_lock_file(&lock);
3711 return -1;
3713 if (commit_lock_file(&lock) < 0) {
3714 strbuf_release(&buf);
3715 return error(_("failed to finalize '%s'"), filename);
3718 strbuf_release(&buf);
3719 return 0;
3722 static int do_label(struct repository *r, const char *name, int len)
3724 struct ref_store *refs = get_main_ref_store(r);
3725 struct ref_transaction *transaction;
3726 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3727 struct strbuf msg = STRBUF_INIT;
3728 int ret = 0;
3729 struct object_id head_oid;
3731 if (len == 1 && *name == '#')
3732 return error(_("illegal label name: '%.*s'"), len, name);
3734 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3735 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3737 transaction = ref_store_transaction_begin(refs, &err);
3738 if (!transaction) {
3739 error("%s", err.buf);
3740 ret = -1;
3741 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3742 error(_("could not read HEAD"));
3743 ret = -1;
3744 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3745 NULL, 0, msg.buf, &err) < 0 ||
3746 ref_transaction_commit(transaction, &err)) {
3747 error("%s", err.buf);
3748 ret = -1;
3750 ref_transaction_free(transaction);
3751 strbuf_release(&err);
3752 strbuf_release(&msg);
3754 if (!ret)
3755 ret = safe_append(rebase_path_refs_to_delete(),
3756 "%s\n", ref_name.buf);
3757 strbuf_release(&ref_name);
3759 return ret;
3762 static const char *sequencer_reflog_action(struct replay_opts *opts)
3764 if (!opts->reflog_action) {
3765 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3766 opts->reflog_action =
3767 xstrdup(opts->reflog_action ? opts->reflog_action
3768 : action_name(opts));
3771 return opts->reflog_action;
3774 __attribute__((format (printf, 3, 4)))
3775 static const char *reflog_message(struct replay_opts *opts,
3776 const char *sub_action, const char *fmt, ...)
3778 va_list ap;
3779 static struct strbuf buf = STRBUF_INIT;
3781 va_start(ap, fmt);
3782 strbuf_reset(&buf);
3783 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3784 if (sub_action)
3785 strbuf_addf(&buf, " (%s)", sub_action);
3786 if (fmt) {
3787 strbuf_addstr(&buf, ": ");
3788 strbuf_vaddf(&buf, fmt, ap);
3790 va_end(ap);
3792 return buf.buf;
3795 static struct commit *lookup_label(struct repository *r, const char *label,
3796 int len, struct strbuf *buf)
3798 struct commit *commit;
3799 struct object_id oid;
3801 strbuf_reset(buf);
3802 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3803 if (!read_ref(buf->buf, &oid)) {
3804 commit = lookup_commit_object(r, &oid);
3805 } else {
3806 /* fall back to non-rewritten ref or commit */
3807 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3808 commit = lookup_commit_reference_by_name(buf->buf);
3811 if (!commit)
3812 error(_("could not resolve '%s'"), buf->buf);
3814 return commit;
3817 static int do_reset(struct repository *r,
3818 const char *name, int len,
3819 struct replay_opts *opts)
3821 struct strbuf ref_name = STRBUF_INIT;
3822 struct object_id oid;
3823 struct lock_file lock = LOCK_INIT;
3824 struct tree_desc desc = { 0 };
3825 struct tree *tree;
3826 struct unpack_trees_options unpack_tree_opts = { 0 };
3827 int ret = 0;
3829 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3830 return -1;
3832 if (len == 10 && !strncmp("[new root]", name, len)) {
3833 if (!opts->have_squash_onto) {
3834 const char *hex;
3835 if (commit_tree("", 0, the_hash_algo->empty_tree,
3836 NULL, &opts->squash_onto,
3837 NULL, NULL))
3838 return error(_("writing fake root commit"));
3839 opts->have_squash_onto = 1;
3840 hex = oid_to_hex(&opts->squash_onto);
3841 if (write_message(hex, strlen(hex),
3842 rebase_path_squash_onto(), 0))
3843 return error(_("writing squash-onto"));
3845 oidcpy(&oid, &opts->squash_onto);
3846 } else {
3847 int i;
3848 struct commit *commit;
3850 /* Determine the length of the label */
3851 for (i = 0; i < len; i++)
3852 if (isspace(name[i]))
3853 break;
3854 len = i;
3856 commit = lookup_label(r, name, len, &ref_name);
3857 if (!commit) {
3858 ret = -1;
3859 goto cleanup;
3861 oid = commit->object.oid;
3864 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3865 unpack_tree_opts.head_idx = 1;
3866 unpack_tree_opts.src_index = r->index;
3867 unpack_tree_opts.dst_index = r->index;
3868 unpack_tree_opts.fn = oneway_merge;
3869 unpack_tree_opts.merge = 1;
3870 unpack_tree_opts.update = 1;
3871 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3872 unpack_tree_opts.skip_cache_tree_update = 1;
3873 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3875 if (repo_read_index_unmerged(r)) {
3876 ret = error_resolve_conflict(action_name(opts));
3877 goto cleanup;
3880 if (!fill_tree_descriptor(r, &desc, &oid)) {
3881 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3882 goto cleanup;
3885 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3886 ret = -1;
3887 goto cleanup;
3890 tree = parse_tree_indirect(&oid);
3891 if (!tree)
3892 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
3893 prime_cache_tree(r, r->index, tree);
3895 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3896 ret = error(_("could not write index"));
3898 if (!ret)
3899 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3900 len, name), "HEAD", &oid,
3901 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3902 cleanup:
3903 free((void *)desc.buffer);
3904 if (ret < 0)
3905 rollback_lock_file(&lock);
3906 strbuf_release(&ref_name);
3907 clear_unpack_trees_porcelain(&unpack_tree_opts);
3908 return ret;
3911 static int do_merge(struct repository *r,
3912 struct commit *commit,
3913 const char *arg, int arg_len,
3914 int flags, int *check_todo, struct replay_opts *opts)
3916 int run_commit_flags = 0;
3917 struct strbuf ref_name = STRBUF_INIT;
3918 struct commit *head_commit, *merge_commit, *i;
3919 struct commit_list *bases, *j;
3920 struct commit_list *to_merge = NULL, **tail = &to_merge;
3921 const char *strategy = !opts->xopts.nr &&
3922 (!opts->strategy ||
3923 !strcmp(opts->strategy, "recursive") ||
3924 !strcmp(opts->strategy, "ort")) ?
3925 NULL : opts->strategy;
3926 struct merge_options o;
3927 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3928 static struct lock_file lock;
3929 const char *p;
3931 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3932 ret = -1;
3933 goto leave_merge;
3936 head_commit = lookup_commit_reference_by_name("HEAD");
3937 if (!head_commit) {
3938 ret = error(_("cannot merge without a current revision"));
3939 goto leave_merge;
3943 * For octopus merges, the arg starts with the list of revisions to be
3944 * merged. The list is optionally followed by '#' and the oneline.
3946 merge_arg_len = oneline_offset = arg_len;
3947 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3948 if (!*p)
3949 break;
3950 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3951 p += 1 + strspn(p + 1, " \t\n");
3952 oneline_offset = p - arg;
3953 break;
3955 k = strcspn(p, " \t\n");
3956 if (!k)
3957 continue;
3958 merge_commit = lookup_label(r, p, k, &ref_name);
3959 if (!merge_commit) {
3960 ret = error(_("unable to parse '%.*s'"), k, p);
3961 goto leave_merge;
3963 tail = &commit_list_insert(merge_commit, tail)->next;
3964 p += k;
3965 merge_arg_len = p - arg;
3968 if (!to_merge) {
3969 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3970 goto leave_merge;
3973 if (opts->have_squash_onto &&
3974 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3976 * When the user tells us to "merge" something into a
3977 * "[new root]", let's simply fast-forward to the merge head.
3979 rollback_lock_file(&lock);
3980 if (to_merge->next)
3981 ret = error(_("octopus merge cannot be executed on "
3982 "top of a [new root]"));
3983 else
3984 ret = fast_forward_to(r, &to_merge->item->object.oid,
3985 &head_commit->object.oid, 0,
3986 opts);
3987 goto leave_merge;
3991 * If HEAD is not identical to the first parent of the original merge
3992 * commit, we cannot fast-forward.
3994 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3995 oideq(&commit->parents->item->object.oid,
3996 &head_commit->object.oid);
3999 * If any merge head is different from the original one, we cannot
4000 * fast-forward.
4002 if (can_fast_forward) {
4003 struct commit_list *p = commit->parents->next;
4005 for (j = to_merge; j && p; j = j->next, p = p->next)
4006 if (!oideq(&j->item->object.oid,
4007 &p->item->object.oid)) {
4008 can_fast_forward = 0;
4009 break;
4012 * If the number of merge heads differs from the original merge
4013 * commit, we cannot fast-forward.
4015 if (j || p)
4016 can_fast_forward = 0;
4019 if (can_fast_forward) {
4020 rollback_lock_file(&lock);
4021 ret = fast_forward_to(r, &commit->object.oid,
4022 &head_commit->object.oid, 0, opts);
4023 if (flags & TODO_EDIT_MERGE_MSG)
4024 goto fast_forward_edit;
4026 goto leave_merge;
4029 if (commit) {
4030 const char *encoding = get_commit_output_encoding();
4031 const char *message = repo_logmsg_reencode(r, commit, NULL,
4032 encoding);
4033 const char *body;
4034 int len;
4036 if (!message) {
4037 ret = error(_("could not get commit message of '%s'"),
4038 oid_to_hex(&commit->object.oid));
4039 goto leave_merge;
4041 write_author_script(message);
4042 find_commit_subject(message, &body);
4043 len = strlen(body);
4044 ret = write_message(body, len, git_path_merge_msg(r), 0);
4045 repo_unuse_commit_buffer(r, commit, message);
4046 if (ret) {
4047 error_errno(_("could not write '%s'"),
4048 git_path_merge_msg(r));
4049 goto leave_merge;
4051 } else {
4052 struct strbuf buf = STRBUF_INIT;
4053 int len;
4055 strbuf_addf(&buf, "author %s", git_author_info(0));
4056 write_author_script(buf.buf);
4057 strbuf_reset(&buf);
4059 if (oneline_offset < arg_len) {
4060 p = arg + oneline_offset;
4061 len = arg_len - oneline_offset;
4062 } else {
4063 strbuf_addf(&buf, "Merge %s '%.*s'",
4064 to_merge->next ? "branches" : "branch",
4065 merge_arg_len, arg);
4066 p = buf.buf;
4067 len = buf.len;
4070 ret = write_message(p, len, git_path_merge_msg(r), 0);
4071 strbuf_release(&buf);
4072 if (ret) {
4073 error_errno(_("could not write '%s'"),
4074 git_path_merge_msg(r));
4075 goto leave_merge;
4079 if (strategy || to_merge->next) {
4080 /* Octopus merge */
4081 struct child_process cmd = CHILD_PROCESS_INIT;
4083 if (read_env_script(&cmd.env)) {
4084 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4086 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4087 goto leave_merge;
4090 if (opts->committer_date_is_author_date)
4091 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4092 opts->ignore_date ?
4093 "" :
4094 author_date_from_env(&cmd.env));
4095 if (opts->ignore_date)
4096 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4098 cmd.git_cmd = 1;
4099 strvec_push(&cmd.args, "merge");
4100 strvec_push(&cmd.args, "-s");
4101 if (!strategy)
4102 strvec_push(&cmd.args, "octopus");
4103 else {
4104 strvec_push(&cmd.args, strategy);
4105 for (k = 0; k < opts->xopts.nr; k++)
4106 strvec_pushf(&cmd.args,
4107 "-X%s", opts->xopts.v[k]);
4109 if (!(flags & TODO_EDIT_MERGE_MSG))
4110 strvec_push(&cmd.args, "--no-edit");
4111 else
4112 strvec_push(&cmd.args, "--edit");
4113 strvec_push(&cmd.args, "--no-ff");
4114 strvec_push(&cmd.args, "--no-log");
4115 strvec_push(&cmd.args, "--no-stat");
4116 strvec_push(&cmd.args, "-F");
4117 strvec_push(&cmd.args, git_path_merge_msg(r));
4118 if (opts->gpg_sign)
4119 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4120 else
4121 strvec_push(&cmd.args, "--no-gpg-sign");
4123 /* Add the tips to be merged */
4124 for (j = to_merge; j; j = j->next)
4125 strvec_push(&cmd.args,
4126 oid_to_hex(&j->item->object.oid));
4128 strbuf_release(&ref_name);
4129 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4130 NULL, REF_NO_DEREF);
4131 rollback_lock_file(&lock);
4133 ret = run_command(&cmd);
4135 /* force re-reading of the cache */
4136 if (!ret) {
4137 discard_index(r->index);
4138 if (repo_read_index(r) < 0)
4139 ret = error(_("could not read index"));
4141 goto leave_merge;
4144 merge_commit = to_merge->item;
4145 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4146 if (bases && oideq(&merge_commit->object.oid,
4147 &bases->item->object.oid)) {
4148 ret = 0;
4149 /* skip merging an ancestor of HEAD */
4150 goto leave_merge;
4153 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4154 git_path_merge_head(r), 0);
4155 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4157 bases = reverse_commit_list(bases);
4159 repo_read_index(r);
4160 init_merge_options(&o, r);
4161 o.branch1 = "HEAD";
4162 o.branch2 = ref_name.buf;
4163 o.buffer_output = 2;
4165 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4167 * TODO: Should use merge_incore_recursive() and
4168 * merge_switch_to_result(), skipping the call to
4169 * merge_switch_to_result() when we don't actually need to
4170 * update the index and working copy immediately.
4172 ret = merge_ort_recursive(&o,
4173 head_commit, merge_commit, bases,
4174 &i);
4175 } else {
4176 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4177 &i);
4179 if (ret <= 0)
4180 fputs(o.obuf.buf, stdout);
4181 strbuf_release(&o.obuf);
4182 if (ret < 0) {
4183 error(_("could not even attempt to merge '%.*s'"),
4184 merge_arg_len, arg);
4185 unlink(git_path_merge_msg(r));
4186 goto leave_merge;
4189 * The return value of merge_recursive() is 1 on clean, and 0 on
4190 * unclean merge.
4192 * Let's reverse that, so that do_merge() returns 0 upon success and
4193 * 1 upon failed merge (keeping the return value -1 for the cases where
4194 * we will want to reschedule the `merge` command).
4196 ret = !ret;
4198 if (r->index->cache_changed &&
4199 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4200 ret = error(_("merge: Unable to write new index file"));
4201 goto leave_merge;
4204 rollback_lock_file(&lock);
4205 if (ret)
4206 repo_rerere(r, opts->allow_rerere_auto);
4207 else
4209 * In case of problems, we now want to return a positive
4210 * value (a negative one would indicate that the `merge`
4211 * command needs to be rescheduled).
4213 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4214 run_commit_flags);
4216 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4217 fast_forward_edit:
4218 *check_todo = 1;
4219 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4220 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4224 leave_merge:
4225 strbuf_release(&ref_name);
4226 rollback_lock_file(&lock);
4227 free_commit_list(to_merge);
4228 return ret;
4231 static int write_update_refs_state(struct string_list *refs_to_oids)
4233 int result = 0;
4234 struct lock_file lock = LOCK_INIT;
4235 FILE *fp = NULL;
4236 struct string_list_item *item;
4237 char *path;
4239 path = rebase_path_update_refs(the_repository->gitdir);
4241 if (!refs_to_oids->nr) {
4242 if (unlink(path) && errno != ENOENT)
4243 result = error_errno(_("could not unlink: %s"), path);
4244 goto cleanup;
4247 if (safe_create_leading_directories(path)) {
4248 result = error(_("unable to create leading directories of %s"),
4249 path);
4250 goto cleanup;
4253 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4254 result = error(_("another 'rebase' process appears to be running; "
4255 "'%s.lock' already exists"),
4256 path);
4257 goto cleanup;
4260 fp = fdopen_lock_file(&lock, "w");
4261 if (!fp) {
4262 result = error_errno(_("could not open '%s' for writing"), path);
4263 rollback_lock_file(&lock);
4264 goto cleanup;
4267 for_each_string_list_item(item, refs_to_oids) {
4268 struct update_ref_record *rec = item->util;
4269 fprintf(fp, "%s\n%s\n%s\n", item->string,
4270 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4273 result = commit_lock_file(&lock);
4275 cleanup:
4276 free(path);
4277 return result;
4281 * Parse the update-refs file for the current rebase, then remove the
4282 * refs that do not appear in the todo_list (and have not had updated
4283 * values stored) and add refs that are in the todo_list but not
4284 * represented in the update-refs file.
4286 * If there are changes to the update-refs list, then write the new state
4287 * to disk.
4289 void todo_list_filter_update_refs(struct repository *r,
4290 struct todo_list *todo_list)
4292 int i;
4293 int updated = 0;
4294 struct string_list update_refs = STRING_LIST_INIT_DUP;
4296 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4299 * For each item in the update_refs list, if it has no updated
4300 * value and does not appear in the todo_list, then remove it
4301 * from the update_refs list.
4303 for (i = 0; i < update_refs.nr; i++) {
4304 int j;
4305 int found = 0;
4306 const char *ref = update_refs.items[i].string;
4307 size_t reflen = strlen(ref);
4308 struct update_ref_record *rec = update_refs.items[i].util;
4310 /* OID already stored as updated. */
4311 if (!is_null_oid(&rec->after))
4312 continue;
4314 for (j = 0; !found && j < todo_list->nr; j++) {
4315 struct todo_item *item = &todo_list->items[j];
4316 const char *arg = todo_list->buf.buf + item->arg_offset;
4318 if (item->command != TODO_UPDATE_REF)
4319 continue;
4321 if (item->arg_len != reflen ||
4322 strncmp(arg, ref, reflen))
4323 continue;
4325 found = 1;
4328 if (!found) {
4329 free(update_refs.items[i].string);
4330 free(update_refs.items[i].util);
4332 update_refs.nr--;
4333 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4335 updated = 1;
4336 i--;
4341 * For each todo_item, check if its ref is in the update_refs list.
4342 * If not, then add it as an un-updated ref.
4344 for (i = 0; i < todo_list->nr; i++) {
4345 struct todo_item *item = &todo_list->items[i];
4346 const char *arg = todo_list->buf.buf + item->arg_offset;
4347 int j, found = 0;
4349 if (item->command != TODO_UPDATE_REF)
4350 continue;
4352 for (j = 0; !found && j < update_refs.nr; j++) {
4353 const char *ref = update_refs.items[j].string;
4355 found = strlen(ref) == item->arg_len &&
4356 !strncmp(ref, arg, item->arg_len);
4359 if (!found) {
4360 struct string_list_item *inserted;
4361 struct strbuf argref = STRBUF_INIT;
4363 strbuf_add(&argref, arg, item->arg_len);
4364 inserted = string_list_insert(&update_refs, argref.buf);
4365 inserted->util = init_update_ref_record(argref.buf);
4366 strbuf_release(&argref);
4367 updated = 1;
4371 if (updated)
4372 write_update_refs_state(&update_refs);
4373 string_list_clear(&update_refs, 1);
4376 static int do_update_ref(struct repository *r, const char *refname)
4378 struct string_list_item *item;
4379 struct string_list list = STRING_LIST_INIT_DUP;
4381 if (sequencer_get_update_refs_state(r->gitdir, &list))
4382 return -1;
4384 for_each_string_list_item(item, &list) {
4385 if (!strcmp(item->string, refname)) {
4386 struct update_ref_record *rec = item->util;
4387 if (read_ref("HEAD", &rec->after))
4388 return -1;
4389 break;
4393 write_update_refs_state(&list);
4394 string_list_clear(&list, 1);
4395 return 0;
4398 static int do_update_refs(struct repository *r, int quiet)
4400 int res = 0;
4401 struct string_list_item *item;
4402 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4403 struct ref_store *refs = get_main_ref_store(r);
4404 struct strbuf update_msg = STRBUF_INIT;
4405 struct strbuf error_msg = STRBUF_INIT;
4407 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4408 return res;
4410 for_each_string_list_item(item, &refs_to_oids) {
4411 struct update_ref_record *rec = item->util;
4412 int loop_res;
4414 loop_res = refs_update_ref(refs, "rewritten during rebase",
4415 item->string,
4416 &rec->after, &rec->before,
4417 0, UPDATE_REFS_MSG_ON_ERR);
4418 res |= loop_res;
4420 if (quiet)
4421 continue;
4423 if (loop_res)
4424 strbuf_addf(&error_msg, "\t%s\n", item->string);
4425 else
4426 strbuf_addf(&update_msg, "\t%s\n", item->string);
4429 if (!quiet &&
4430 (update_msg.len || error_msg.len)) {
4431 fprintf(stderr,
4432 _("Updated the following refs with %s:\n%s"),
4433 "--update-refs",
4434 update_msg.buf);
4436 if (res)
4437 fprintf(stderr,
4438 _("Failed to update the following refs with %s:\n%s"),
4439 "--update-refs",
4440 error_msg.buf);
4443 string_list_clear(&refs_to_oids, 1);
4444 strbuf_release(&update_msg);
4445 strbuf_release(&error_msg);
4446 return res;
4449 static int is_final_fixup(struct todo_list *todo_list)
4451 int i = todo_list->current;
4453 if (!is_fixup(todo_list->items[i].command))
4454 return 0;
4456 while (++i < todo_list->nr)
4457 if (is_fixup(todo_list->items[i].command))
4458 return 0;
4459 else if (!is_noop(todo_list->items[i].command))
4460 break;
4461 return 1;
4464 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4466 int i;
4468 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4469 if (!is_noop(todo_list->items[i].command))
4470 return todo_list->items[i].command;
4472 return -1;
4475 static void create_autostash_internal(struct repository *r,
4476 const char *path,
4477 const char *refname)
4479 struct strbuf buf = STRBUF_INIT;
4480 struct lock_file lock_file = LOCK_INIT;
4481 int fd;
4483 if (path && refname)
4484 BUG("can only pass path or refname");
4486 fd = repo_hold_locked_index(r, &lock_file, 0);
4487 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4488 if (0 <= fd)
4489 repo_update_index_if_able(r, &lock_file);
4490 rollback_lock_file(&lock_file);
4492 if (has_unstaged_changes(r, 1) ||
4493 has_uncommitted_changes(r, 1)) {
4494 struct child_process stash = CHILD_PROCESS_INIT;
4495 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4496 struct object_id oid;
4498 strvec_pushl(&stash.args,
4499 "stash", "create", "autostash", NULL);
4500 stash.git_cmd = 1;
4501 stash.no_stdin = 1;
4502 strbuf_reset(&buf);
4503 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4504 die(_("Cannot autostash"));
4505 strbuf_trim_trailing_newline(&buf);
4506 if (repo_get_oid(r, buf.buf, &oid))
4507 die(_("Unexpected stash response: '%s'"),
4508 buf.buf);
4509 strbuf_reset(&buf);
4510 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4512 if (path) {
4513 if (safe_create_leading_directories_const(path))
4514 die(_("Could not create directory for '%s'"),
4515 path);
4516 write_file(path, "%s", oid_to_hex(&oid));
4517 } else {
4518 refs_update_ref(get_main_ref_store(r), "", refname,
4519 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4522 printf(_("Created autostash: %s\n"), buf.buf);
4523 if (reset_head(r, &ropts) < 0)
4524 die(_("could not reset --hard"));
4525 discard_index(r->index);
4526 if (repo_read_index(r) < 0)
4527 die(_("could not read index"));
4529 strbuf_release(&buf);
4532 void create_autostash(struct repository *r, const char *path)
4534 create_autostash_internal(r, path, NULL);
4537 void create_autostash_ref(struct repository *r, const char *refname)
4539 create_autostash_internal(r, NULL, refname);
4542 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4544 struct child_process child = CHILD_PROCESS_INIT;
4545 int ret = 0;
4547 if (attempt_apply) {
4548 child.git_cmd = 1;
4549 child.no_stdout = 1;
4550 child.no_stderr = 1;
4551 strvec_push(&child.args, "stash");
4552 strvec_push(&child.args, "apply");
4553 strvec_push(&child.args, stash_oid);
4554 ret = run_command(&child);
4557 if (attempt_apply && !ret)
4558 fprintf(stderr, _("Applied autostash.\n"));
4559 else {
4560 struct child_process store = CHILD_PROCESS_INIT;
4562 store.git_cmd = 1;
4563 strvec_push(&store.args, "stash");
4564 strvec_push(&store.args, "store");
4565 strvec_push(&store.args, "-m");
4566 strvec_push(&store.args, "autostash");
4567 strvec_push(&store.args, "-q");
4568 strvec_push(&store.args, stash_oid);
4569 if (run_command(&store))
4570 ret = error(_("cannot store %s"), stash_oid);
4571 else
4572 fprintf(stderr,
4573 _("%s\n"
4574 "Your changes are safe in the stash.\n"
4575 "You can run \"git stash pop\" or"
4576 " \"git stash drop\" at any time.\n"),
4577 attempt_apply ?
4578 _("Applying autostash resulted in conflicts.") :
4579 _("Autostash exists; creating a new stash entry."));
4582 return ret;
4585 static int apply_save_autostash(const char *path, int attempt_apply)
4587 struct strbuf stash_oid = STRBUF_INIT;
4588 int ret = 0;
4590 if (!read_oneliner(&stash_oid, path,
4591 READ_ONELINER_SKIP_IF_EMPTY)) {
4592 strbuf_release(&stash_oid);
4593 return 0;
4595 strbuf_trim(&stash_oid);
4597 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4599 unlink(path);
4600 strbuf_release(&stash_oid);
4601 return ret;
4604 int save_autostash(const char *path)
4606 return apply_save_autostash(path, 0);
4609 int apply_autostash(const char *path)
4611 return apply_save_autostash(path, 1);
4614 int apply_autostash_oid(const char *stash_oid)
4616 return apply_save_autostash_oid(stash_oid, 1);
4619 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4620 int attempt_apply)
4622 struct object_id stash_oid;
4623 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4624 int flag, ret;
4626 if (!refs_ref_exists(get_main_ref_store(r), refname))
4627 return 0;
4629 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4630 RESOLVE_REF_READING, &stash_oid, &flag))
4631 return -1;
4632 if (flag & REF_ISSYMREF)
4633 return error(_("autostash reference is a symref"));
4635 oid_to_hex_r(stash_oid_hex, &stash_oid);
4636 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4638 refs_delete_ref(get_main_ref_store(r), "", refname,
4639 &stash_oid, REF_NO_DEREF);
4641 return ret;
4644 int save_autostash_ref(struct repository *r, const char *refname)
4646 return apply_save_autostash_ref(r, refname, 0);
4649 int apply_autostash_ref(struct repository *r, const char *refname)
4651 return apply_save_autostash_ref(r, refname, 1);
4654 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4655 const char *onto_name, const struct object_id *onto,
4656 const struct object_id *orig_head)
4658 struct reset_head_opts ropts = {
4659 .oid = onto,
4660 .orig_head = orig_head,
4661 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4662 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4663 .head_msg = reflog_message(opts, "start", "checkout %s",
4664 onto_name),
4665 .default_reflog_action = sequencer_reflog_action(opts)
4667 if (reset_head(r, &ropts)) {
4668 apply_autostash(rebase_path_autostash());
4669 sequencer_remove_state(opts);
4670 return error(_("could not detach HEAD"));
4673 return 0;
4676 static int stopped_at_head(struct repository *r)
4678 struct object_id head;
4679 struct commit *commit;
4680 struct commit_message message;
4682 if (repo_get_oid(r, "HEAD", &head) ||
4683 !(commit = lookup_commit(r, &head)) ||
4684 repo_parse_commit(r, commit) || get_message(commit, &message))
4685 fprintf(stderr, _("Stopped at HEAD\n"));
4686 else {
4687 fprintf(stderr, _("Stopped at %s\n"), message.label);
4688 free_message(commit, &message);
4690 return 0;
4694 static int reread_todo_if_changed(struct repository *r,
4695 struct todo_list *todo_list,
4696 struct replay_opts *opts)
4698 int offset;
4699 struct strbuf buf = STRBUF_INIT;
4701 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4702 return -1;
4703 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4704 if (buf.len != todo_list->buf.len - offset ||
4705 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4706 /* Reread the todo file if it has changed. */
4707 todo_list_release(todo_list);
4708 if (read_populate_todo(r, todo_list, opts))
4709 return -1; /* message was printed */
4710 /* `current` will be incremented on return */
4711 todo_list->current = -1;
4713 strbuf_release(&buf);
4715 return 0;
4718 static const char rescheduled_advice[] =
4719 N_("Could not execute the todo command\n"
4720 "\n"
4721 " %.*s"
4722 "\n"
4723 "It has been rescheduled; To edit the command before continuing, please\n"
4724 "edit the todo list first:\n"
4725 "\n"
4726 " git rebase --edit-todo\n"
4727 " git rebase --continue\n");
4729 static int pick_one_commit(struct repository *r,
4730 struct todo_list *todo_list,
4731 struct replay_opts *opts,
4732 int *check_todo, int* reschedule)
4734 int res;
4735 struct todo_item *item = todo_list->items + todo_list->current;
4736 const char *arg = todo_item_get_arg(todo_list, item);
4737 if (is_rebase_i(opts))
4738 opts->reflog_message = reflog_message(
4739 opts, command_to_string(item->command), NULL);
4741 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4742 check_todo);
4743 if (is_rebase_i(opts) && res < 0) {
4744 /* Reschedule */
4745 *reschedule = 1;
4746 return -1;
4748 if (item->command == TODO_EDIT) {
4749 struct commit *commit = item->commit;
4750 if (!res) {
4751 if (!opts->verbose)
4752 term_clear_line();
4753 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4754 short_commit_name(r, commit), item->arg_len, arg);
4756 return error_with_patch(r, commit,
4757 arg, item->arg_len, opts, res, !res);
4759 if (is_rebase_i(opts) && !res)
4760 record_in_rewritten(&item->commit->object.oid,
4761 peek_command(todo_list, 1));
4762 if (res && is_fixup(item->command)) {
4763 if (res == 1)
4764 intend_to_amend();
4765 return error_failed_squash(r, item->commit, opts,
4766 item->arg_len, arg);
4767 } else if (res && is_rebase_i(opts) && item->commit) {
4768 int to_amend = 0;
4769 struct object_id oid;
4772 * If we are rewording and have either
4773 * fast-forwarded already, or are about to
4774 * create a new root commit, we want to amend,
4775 * otherwise we do not.
4777 if (item->command == TODO_REWORD &&
4778 !repo_get_oid(r, "HEAD", &oid) &&
4779 (oideq(&item->commit->object.oid, &oid) ||
4780 (opts->have_squash_onto &&
4781 oideq(&opts->squash_onto, &oid))))
4782 to_amend = 1;
4784 return res | error_with_patch(r, item->commit,
4785 arg, item->arg_len, opts,
4786 res, to_amend);
4788 return res;
4791 static int pick_commits(struct repository *r,
4792 struct todo_list *todo_list,
4793 struct replay_opts *opts)
4795 int res = 0, reschedule = 0;
4797 opts->reflog_message = sequencer_reflog_action(opts);
4798 if (opts->allow_ff)
4799 assert(!(opts->signoff || opts->no_commit ||
4800 opts->record_origin || should_edit(opts) ||
4801 opts->committer_date_is_author_date ||
4802 opts->ignore_date));
4803 if (read_and_refresh_cache(r, opts))
4804 return -1;
4806 unlink(rebase_path_message());
4807 unlink(rebase_path_stopped_sha());
4808 unlink(rebase_path_amend());
4809 unlink(rebase_path_patch());
4811 while (todo_list->current < todo_list->nr) {
4812 struct todo_item *item = todo_list->items + todo_list->current;
4813 const char *arg = todo_item_get_arg(todo_list, item);
4814 int check_todo = 0;
4816 if (save_todo(todo_list, opts, reschedule))
4817 return -1;
4818 if (is_rebase_i(opts)) {
4819 if (item->command != TODO_COMMENT) {
4820 FILE *f = fopen(rebase_path_msgnum(), "w");
4822 todo_list->done_nr++;
4824 if (f) {
4825 fprintf(f, "%d\n", todo_list->done_nr);
4826 fclose(f);
4828 if (!opts->quiet)
4829 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4830 todo_list->done_nr,
4831 todo_list->total_nr,
4832 opts->verbose ? "\n" : "\r");
4834 unlink(rebase_path_author_script());
4835 unlink(git_path_merge_head(r));
4836 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4837 NULL, REF_NO_DEREF);
4838 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4839 NULL, REF_NO_DEREF);
4841 if (item->command == TODO_BREAK) {
4842 if (!opts->verbose)
4843 term_clear_line();
4844 return stopped_at_head(r);
4847 if (item->command <= TODO_SQUASH) {
4848 res = pick_one_commit(r, todo_list, opts, &check_todo,
4849 &reschedule);
4850 if (!res && item->command == TODO_EDIT)
4851 return 0;
4852 } else if (item->command == TODO_EXEC) {
4853 char *end_of_arg = (char *)(arg + item->arg_len);
4854 int saved = *end_of_arg;
4856 if (!opts->verbose)
4857 term_clear_line();
4858 *end_of_arg = '\0';
4859 res = do_exec(r, arg);
4860 *end_of_arg = saved;
4862 if (res) {
4863 if (opts->reschedule_failed_exec)
4864 reschedule = 1;
4866 check_todo = 1;
4867 } else if (item->command == TODO_LABEL) {
4868 if ((res = do_label(r, arg, item->arg_len)))
4869 reschedule = 1;
4870 } else if (item->command == TODO_RESET) {
4871 if ((res = do_reset(r, arg, item->arg_len, opts)))
4872 reschedule = 1;
4873 } else if (item->command == TODO_MERGE) {
4874 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4875 item->flags, &check_todo, opts)) < 0)
4876 reschedule = 1;
4877 else if (item->commit)
4878 record_in_rewritten(&item->commit->object.oid,
4879 peek_command(todo_list, 1));
4880 if (res > 0)
4881 /* failed with merge conflicts */
4882 return error_with_patch(r, item->commit,
4883 arg, item->arg_len,
4884 opts, res, 0);
4885 } else if (item->command == TODO_UPDATE_REF) {
4886 struct strbuf ref = STRBUF_INIT;
4887 strbuf_add(&ref, arg, item->arg_len);
4888 if ((res = do_update_ref(r, ref.buf)))
4889 reschedule = 1;
4890 strbuf_release(&ref);
4891 } else if (!is_noop(item->command))
4892 return error(_("unknown command %d"), item->command);
4894 if (reschedule) {
4895 advise(_(rescheduled_advice),
4896 get_item_line_length(todo_list,
4897 todo_list->current),
4898 get_item_line(todo_list, todo_list->current));
4899 if (save_todo(todo_list, opts, reschedule))
4900 return -1;
4901 if (item->commit)
4902 write_rebase_head(&item->commit->object.oid);
4903 } else if (is_rebase_i(opts) && check_todo && !res &&
4904 reread_todo_if_changed(r, todo_list, opts)) {
4905 return -1;
4908 if (res)
4909 return res;
4911 todo_list->current++;
4914 if (is_rebase_i(opts)) {
4915 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4916 struct stat st;
4918 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4919 starts_with(head_ref.buf, "refs/")) {
4920 const char *msg;
4921 struct object_id head, orig;
4922 int res;
4924 if (repo_get_oid(r, "HEAD", &head)) {
4925 res = error(_("cannot read HEAD"));
4926 cleanup_head_ref:
4927 strbuf_release(&head_ref);
4928 strbuf_release(&buf);
4929 return res;
4931 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4932 get_oid_hex(buf.buf, &orig)) {
4933 res = error(_("could not read orig-head"));
4934 goto cleanup_head_ref;
4936 strbuf_reset(&buf);
4937 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4938 res = error(_("could not read 'onto'"));
4939 goto cleanup_head_ref;
4941 msg = reflog_message(opts, "finish", "%s onto %s",
4942 head_ref.buf, buf.buf);
4943 if (update_ref(msg, head_ref.buf, &head, &orig,
4944 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4945 res = error(_("could not update %s"),
4946 head_ref.buf);
4947 goto cleanup_head_ref;
4949 msg = reflog_message(opts, "finish", "returning to %s",
4950 head_ref.buf);
4951 if (create_symref("HEAD", head_ref.buf, msg)) {
4952 res = error(_("could not update HEAD to %s"),
4953 head_ref.buf);
4954 goto cleanup_head_ref;
4956 strbuf_reset(&buf);
4959 if (opts->verbose) {
4960 struct rev_info log_tree_opt;
4961 struct object_id orig, head;
4963 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4964 repo_init_revisions(r, &log_tree_opt, NULL);
4965 log_tree_opt.diff = 1;
4966 log_tree_opt.diffopt.output_format =
4967 DIFF_FORMAT_DIFFSTAT;
4968 log_tree_opt.disable_stdin = 1;
4970 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4971 !repo_get_oid(r, buf.buf, &orig) &&
4972 !repo_get_oid(r, "HEAD", &head)) {
4973 diff_tree_oid(&orig, &head, "",
4974 &log_tree_opt.diffopt);
4975 log_tree_diff_flush(&log_tree_opt);
4977 release_revisions(&log_tree_opt);
4979 flush_rewritten_pending();
4980 if (!stat(rebase_path_rewritten_list(), &st) &&
4981 st.st_size > 0) {
4982 struct child_process child = CHILD_PROCESS_INIT;
4983 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4985 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4986 child.git_cmd = 1;
4987 strvec_push(&child.args, "notes");
4988 strvec_push(&child.args, "copy");
4989 strvec_push(&child.args, "--for-rewrite=rebase");
4990 /* we don't care if this copying failed */
4991 run_command(&child);
4993 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4994 strvec_push(&hook_opt.args, "rebase");
4995 run_hooks_opt("post-rewrite", &hook_opt);
4997 apply_autostash(rebase_path_autostash());
4999 if (!opts->quiet) {
5000 if (!opts->verbose)
5001 term_clear_line();
5002 fprintf(stderr,
5003 _("Successfully rebased and updated %s.\n"),
5004 head_ref.buf);
5007 strbuf_release(&buf);
5008 strbuf_release(&head_ref);
5010 if (do_update_refs(r, opts->quiet))
5011 return -1;
5015 * Sequence of picks finished successfully; cleanup by
5016 * removing the .git/sequencer directory
5018 return sequencer_remove_state(opts);
5021 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5023 struct child_process cmd = CHILD_PROCESS_INIT;
5025 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5026 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5027 return error(_("no cherry-pick or revert in progress"));
5029 cmd.git_cmd = 1;
5030 strvec_push(&cmd.args, "commit");
5033 * continue_single_pick() handles the case of recovering from a
5034 * conflict. should_edit() doesn't handle that case; for a conflict,
5035 * we want to edit if the user asked for it, or if they didn't specify
5036 * and stdin is a tty.
5038 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5040 * Include --cleanup=strip as well because we don't want the
5041 * "# Conflicts:" messages.
5043 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5045 return run_command(&cmd);
5048 static int commit_staged_changes(struct repository *r,
5049 struct replay_opts *opts,
5050 struct todo_list *todo_list)
5052 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5053 unsigned int final_fixup = 0, is_clean;
5055 if (has_unstaged_changes(r, 1))
5056 return error(_("cannot rebase: You have unstaged changes."));
5058 is_clean = !has_uncommitted_changes(r, 0);
5060 if (!is_clean && !file_exists(rebase_path_message())) {
5061 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5063 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5065 if (file_exists(rebase_path_amend())) {
5066 struct strbuf rev = STRBUF_INIT;
5067 struct object_id head, to_amend;
5069 if (repo_get_oid(r, "HEAD", &head))
5070 return error(_("cannot amend non-existing commit"));
5071 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5072 return error(_("invalid file: '%s'"), rebase_path_amend());
5073 if (get_oid_hex(rev.buf, &to_amend))
5074 return error(_("invalid contents: '%s'"),
5075 rebase_path_amend());
5076 if (!is_clean && !oideq(&head, &to_amend))
5077 return error(_("\nYou have uncommitted changes in your "
5078 "working tree. Please, commit them\n"
5079 "first and then run 'git rebase "
5080 "--continue' again."));
5082 * When skipping a failed fixup/squash, we need to edit the
5083 * commit message, the current fixup list and count, and if it
5084 * was the last fixup/squash in the chain, we need to clean up
5085 * the commit message and if there was a squash, let the user
5086 * edit it.
5088 if (!is_clean || !opts->current_fixup_count)
5089 ; /* this is not the final fixup */
5090 else if (!oideq(&head, &to_amend) ||
5091 !file_exists(rebase_path_stopped_sha())) {
5092 /* was a final fixup or squash done manually? */
5093 if (!is_fixup(peek_command(todo_list, 0))) {
5094 unlink(rebase_path_fixup_msg());
5095 unlink(rebase_path_squash_msg());
5096 unlink(rebase_path_current_fixups());
5097 strbuf_reset(&opts->current_fixups);
5098 opts->current_fixup_count = 0;
5100 } else {
5101 /* we are in a fixup/squash chain */
5102 const char *p = opts->current_fixups.buf;
5103 int len = opts->current_fixups.len;
5105 opts->current_fixup_count--;
5106 if (!len)
5107 BUG("Incorrect current_fixups:\n%s", p);
5108 while (len && p[len - 1] != '\n')
5109 len--;
5110 strbuf_setlen(&opts->current_fixups, len);
5111 if (write_message(p, len, rebase_path_current_fixups(),
5112 0) < 0)
5113 return error(_("could not write file: '%s'"),
5114 rebase_path_current_fixups());
5117 * If a fixup/squash in a fixup/squash chain failed, the
5118 * commit message is already correct, no need to commit
5119 * it again.
5121 * Only if it is the final command in the fixup/squash
5122 * chain, and only if the chain is longer than a single
5123 * fixup/squash command (which was just skipped), do we
5124 * actually need to re-commit with a cleaned up commit
5125 * message.
5127 if (opts->current_fixup_count > 0 &&
5128 !is_fixup(peek_command(todo_list, 0))) {
5129 final_fixup = 1;
5131 * If there was not a single "squash" in the
5132 * chain, we only need to clean up the commit
5133 * message, no need to bother the user with
5134 * opening the commit message in the editor.
5136 if (!starts_with(p, "squash ") &&
5137 !strstr(p, "\nsquash "))
5138 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5139 } else if (is_fixup(peek_command(todo_list, 0))) {
5141 * We need to update the squash message to skip
5142 * the latest commit message.
5144 int res = 0;
5145 struct commit *commit;
5146 const char *msg;
5147 const char *path = rebase_path_squash_msg();
5148 const char *encoding = get_commit_output_encoding();
5150 if (parse_head(r, &commit))
5151 return error(_("could not parse HEAD"));
5153 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5154 if (!p) {
5155 res = error(_("could not parse commit %s"),
5156 oid_to_hex(&commit->object.oid));
5157 goto unuse_commit_buffer;
5159 find_commit_subject(p, &msg);
5160 if (write_message(msg, strlen(msg), path, 0)) {
5161 res = error(_("could not write file: "
5162 "'%s'"), path);
5163 goto unuse_commit_buffer;
5165 unuse_commit_buffer:
5166 repo_unuse_commit_buffer(r, commit, p);
5167 if (res)
5168 return res;
5172 strbuf_release(&rev);
5173 flags |= AMEND_MSG;
5176 if (is_clean) {
5177 if (refs_ref_exists(get_main_ref_store(r),
5178 "CHERRY_PICK_HEAD") &&
5179 refs_delete_ref(get_main_ref_store(r), "",
5180 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5181 return error(_("could not remove CHERRY_PICK_HEAD"));
5182 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5183 return error_errno(_("could not remove '%s'"),
5184 git_path_merge_msg(r));
5185 if (!final_fixup)
5186 return 0;
5189 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5190 opts, flags))
5191 return error(_("could not commit staged changes."));
5192 unlink(rebase_path_amend());
5193 unlink(git_path_merge_head(r));
5194 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5195 NULL, REF_NO_DEREF);
5196 if (final_fixup) {
5197 unlink(rebase_path_fixup_msg());
5198 unlink(rebase_path_squash_msg());
5200 if (opts->current_fixup_count > 0) {
5202 * Whether final fixup or not, we just cleaned up the commit
5203 * message...
5205 unlink(rebase_path_current_fixups());
5206 strbuf_reset(&opts->current_fixups);
5207 opts->current_fixup_count = 0;
5209 return 0;
5212 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5214 struct todo_list todo_list = TODO_LIST_INIT;
5215 int res;
5217 if (read_and_refresh_cache(r, opts))
5218 return -1;
5220 if (read_populate_opts(opts))
5221 return -1;
5222 if (is_rebase_i(opts)) {
5223 if ((res = read_populate_todo(r, &todo_list, opts)))
5224 goto release_todo_list;
5226 if (file_exists(rebase_path_dropped())) {
5227 if ((res = todo_list_check_against_backup(r, &todo_list)))
5228 goto release_todo_list;
5230 unlink(rebase_path_dropped());
5233 opts->reflog_message = reflog_message(opts, "continue", NULL);
5234 if (commit_staged_changes(r, opts, &todo_list)) {
5235 res = -1;
5236 goto release_todo_list;
5238 } else if (!file_exists(get_todo_path(opts)))
5239 return continue_single_pick(r, opts);
5240 else if ((res = read_populate_todo(r, &todo_list, opts)))
5241 goto release_todo_list;
5243 if (!is_rebase_i(opts)) {
5244 /* Verify that the conflict has been resolved */
5245 if (refs_ref_exists(get_main_ref_store(r),
5246 "CHERRY_PICK_HEAD") ||
5247 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5248 res = continue_single_pick(r, opts);
5249 if (res)
5250 goto release_todo_list;
5252 if (index_differs_from(r, "HEAD", NULL, 0)) {
5253 res = error_dirty_index(r, opts);
5254 goto release_todo_list;
5256 todo_list.current++;
5257 } else if (file_exists(rebase_path_stopped_sha())) {
5258 struct strbuf buf = STRBUF_INIT;
5259 struct object_id oid;
5261 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5262 READ_ONELINER_SKIP_IF_EMPTY) &&
5263 !get_oid_hex(buf.buf, &oid))
5264 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5265 strbuf_release(&buf);
5268 res = pick_commits(r, &todo_list, opts);
5269 release_todo_list:
5270 todo_list_release(&todo_list);
5271 return res;
5274 static int single_pick(struct repository *r,
5275 struct commit *cmit,
5276 struct replay_opts *opts)
5278 int check_todo;
5279 struct todo_item item;
5281 item.command = opts->action == REPLAY_PICK ?
5282 TODO_PICK : TODO_REVERT;
5283 item.commit = cmit;
5285 opts->reflog_message = sequencer_reflog_action(opts);
5286 return do_pick_commit(r, &item, opts, 0, &check_todo);
5289 int sequencer_pick_revisions(struct repository *r,
5290 struct replay_opts *opts)
5292 struct todo_list todo_list = TODO_LIST_INIT;
5293 struct object_id oid;
5294 int i, res;
5296 assert(opts->revs);
5297 if (read_and_refresh_cache(r, opts))
5298 return -1;
5300 for (i = 0; i < opts->revs->pending.nr; i++) {
5301 struct object_id oid;
5302 const char *name = opts->revs->pending.objects[i].name;
5304 /* This happens when using --stdin. */
5305 if (!strlen(name))
5306 continue;
5308 if (!repo_get_oid(r, name, &oid)) {
5309 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5310 enum object_type type = oid_object_info(r,
5311 &oid,
5312 NULL);
5313 return error(_("%s: can't cherry-pick a %s"),
5314 name, type_name(type));
5316 } else
5317 return error(_("%s: bad revision"), name);
5321 * If we were called as "git cherry-pick <commit>", just
5322 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5323 * REVERT_HEAD, and don't touch the sequencer state.
5324 * This means it is possible to cherry-pick in the middle
5325 * of a cherry-pick sequence.
5327 if (opts->revs->cmdline.nr == 1 &&
5328 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5329 opts->revs->no_walk &&
5330 !opts->revs->cmdline.rev->flags) {
5331 struct commit *cmit;
5332 if (prepare_revision_walk(opts->revs))
5333 return error(_("revision walk setup failed"));
5334 cmit = get_revision(opts->revs);
5335 if (!cmit)
5336 return error(_("empty commit set passed"));
5337 if (get_revision(opts->revs))
5338 BUG("unexpected extra commit from walk");
5339 return single_pick(r, cmit, opts);
5343 * Start a new cherry-pick/ revert sequence; but
5344 * first, make sure that an existing one isn't in
5345 * progress
5348 if (walk_revs_populate_todo(&todo_list, opts) ||
5349 create_seq_dir(r) < 0)
5350 return -1;
5351 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5352 return error(_("can't revert as initial commit"));
5353 if (save_head(oid_to_hex(&oid)))
5354 return -1;
5355 if (save_opts(opts))
5356 return -1;
5357 update_abort_safety_file();
5358 res = pick_commits(r, &todo_list, opts);
5359 todo_list_release(&todo_list);
5360 return res;
5363 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5365 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5366 struct strbuf sob = STRBUF_INIT;
5367 int has_footer;
5369 strbuf_addstr(&sob, sign_off_header);
5370 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5371 strbuf_addch(&sob, '\n');
5373 if (!ignore_footer)
5374 strbuf_complete_line(msgbuf);
5377 * If the whole message buffer is equal to the sob, pretend that we
5378 * found a conforming footer with a matching sob
5380 if (msgbuf->len - ignore_footer == sob.len &&
5381 !strncmp(msgbuf->buf, sob.buf, sob.len))
5382 has_footer = 3;
5383 else
5384 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5386 if (!has_footer) {
5387 const char *append_newlines = NULL;
5388 size_t len = msgbuf->len - ignore_footer;
5390 if (!len) {
5392 * The buffer is completely empty. Leave foom for
5393 * the title and body to be filled in by the user.
5395 append_newlines = "\n\n";
5396 } else if (len == 1) {
5398 * Buffer contains a single newline. Add another
5399 * so that we leave room for the title and body.
5401 append_newlines = "\n";
5402 } else if (msgbuf->buf[len - 2] != '\n') {
5404 * Buffer ends with a single newline. Add another
5405 * so that there is an empty line between the message
5406 * body and the sob.
5408 append_newlines = "\n";
5409 } /* else, the buffer already ends with two newlines. */
5411 if (append_newlines)
5412 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5413 append_newlines, strlen(append_newlines));
5416 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5417 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5418 sob.buf, sob.len);
5420 strbuf_release(&sob);
5423 struct labels_entry {
5424 struct hashmap_entry entry;
5425 char label[FLEX_ARRAY];
5428 static int labels_cmp(const void *fndata UNUSED,
5429 const struct hashmap_entry *eptr,
5430 const struct hashmap_entry *entry_or_key, const void *key)
5432 const struct labels_entry *a, *b;
5434 a = container_of(eptr, const struct labels_entry, entry);
5435 b = container_of(entry_or_key, const struct labels_entry, entry);
5437 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5440 struct string_entry {
5441 struct oidmap_entry entry;
5442 char string[FLEX_ARRAY];
5445 struct label_state {
5446 struct oidmap commit2label;
5447 struct hashmap labels;
5448 struct strbuf buf;
5449 int max_label_length;
5452 static const char *label_oid(struct object_id *oid, const char *label,
5453 struct label_state *state)
5455 struct labels_entry *labels_entry;
5456 struct string_entry *string_entry;
5457 struct object_id dummy;
5458 int i;
5460 string_entry = oidmap_get(&state->commit2label, oid);
5461 if (string_entry)
5462 return string_entry->string;
5465 * For "uninteresting" commits, i.e. commits that are not to be
5466 * rebased, and which can therefore not be labeled, we use a unique
5467 * abbreviation of the commit name. This is slightly more complicated
5468 * than calling repo_find_unique_abbrev() because we also need to make
5469 * sure that the abbreviation does not conflict with any other
5470 * label.
5472 * We disallow "interesting" commits to be labeled by a string that
5473 * is a valid full-length hash, to ensure that we always can find an
5474 * abbreviation for any uninteresting commit's names that does not
5475 * clash with any other label.
5477 strbuf_reset(&state->buf);
5478 if (!label) {
5479 char *p;
5481 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5482 label = p = state->buf.buf;
5484 repo_find_unique_abbrev_r(the_repository, p, oid,
5485 default_abbrev);
5488 * We may need to extend the abbreviated hash so that there is
5489 * no conflicting label.
5491 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5492 size_t i = strlen(p) + 1;
5494 oid_to_hex_r(p, oid);
5495 for (; i < the_hash_algo->hexsz; i++) {
5496 char save = p[i];
5497 p[i] = '\0';
5498 if (!hashmap_get_from_hash(&state->labels,
5499 strihash(p), p))
5500 break;
5501 p[i] = save;
5504 } else {
5505 struct strbuf *buf = &state->buf;
5506 int label_is_utf8 = 1; /* start with this assumption */
5507 size_t max_len = buf->len + state->max_label_length;
5510 * Sanitize labels by replacing non-alpha-numeric characters
5511 * (including white-space ones) by dashes, as they might be
5512 * illegal in file names (and hence in ref names).
5514 * Note that we retain non-ASCII UTF-8 characters (identified
5515 * via the most significant bit). They should be all acceptable
5516 * in file names.
5518 * As we will use the labels as names of (loose) refs, it is
5519 * vital that the name not be longer than the maximum component
5520 * size of the file system (`NAME_MAX`). We are careful to
5521 * truncate the label accordingly, allowing for the `.lock`
5522 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5523 * truncating in the middle of a character).
5525 for (; *label && buf->len + 1 < max_len; label++)
5526 if (isalnum(*label) ||
5527 (!label_is_utf8 && (*label & 0x80)))
5528 strbuf_addch(buf, *label);
5529 else if (*label & 0x80) {
5530 const char *p = label;
5532 utf8_width(&p, NULL);
5533 if (p) {
5534 if (buf->len + (p - label) > max_len)
5535 break;
5536 strbuf_add(buf, label, p - label);
5537 label = p - 1;
5538 } else {
5539 label_is_utf8 = 0;
5540 strbuf_addch(buf, *label);
5542 /* avoid leading dash and double-dashes */
5543 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5544 strbuf_addch(buf, '-');
5545 if (!buf->len) {
5546 strbuf_addstr(buf, "rev-");
5547 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5549 label = buf->buf;
5551 if ((buf->len == the_hash_algo->hexsz &&
5552 !get_oid_hex(label, &dummy)) ||
5553 (buf->len == 1 && *label == '#') ||
5554 hashmap_get_from_hash(&state->labels,
5555 strihash(label), label)) {
5557 * If the label already exists, or if the label is a
5558 * valid full OID, or the label is a '#' (which we use
5559 * as a separator between merge heads and oneline), we
5560 * append a dash and a number to make it unique.
5562 size_t len = buf->len;
5564 for (i = 2; ; i++) {
5565 strbuf_setlen(buf, len);
5566 strbuf_addf(buf, "-%d", i);
5567 if (!hashmap_get_from_hash(&state->labels,
5568 strihash(buf->buf),
5569 buf->buf))
5570 break;
5573 label = buf->buf;
5577 FLEX_ALLOC_STR(labels_entry, label, label);
5578 hashmap_entry_init(&labels_entry->entry, strihash(label));
5579 hashmap_add(&state->labels, &labels_entry->entry);
5581 FLEX_ALLOC_STR(string_entry, string, label);
5582 oidcpy(&string_entry->entry.oid, oid);
5583 oidmap_put(&state->commit2label, string_entry);
5585 return string_entry->string;
5588 static int make_script_with_merges(struct pretty_print_context *pp,
5589 struct rev_info *revs, struct strbuf *out,
5590 unsigned flags)
5592 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5593 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5594 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5595 int skipped_commit = 0;
5596 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5597 struct strbuf label = STRBUF_INIT;
5598 struct commit_list *commits = NULL, **tail = &commits, *iter;
5599 struct commit_list *tips = NULL, **tips_tail = &tips;
5600 struct commit *commit;
5601 struct oidmap commit2todo = OIDMAP_INIT;
5602 struct string_entry *entry;
5603 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5604 shown = OIDSET_INIT;
5605 struct label_state state =
5606 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5608 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5609 const char *cmd_pick = abbr ? "p" : "pick",
5610 *cmd_label = abbr ? "l" : "label",
5611 *cmd_reset = abbr ? "t" : "reset",
5612 *cmd_merge = abbr ? "m" : "merge";
5614 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5616 oidmap_init(&commit2todo, 0);
5617 oidmap_init(&state.commit2label, 0);
5618 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5619 strbuf_init(&state.buf, 32);
5621 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5622 struct labels_entry *onto_label_entry;
5623 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5624 FLEX_ALLOC_STR(entry, string, "onto");
5625 oidcpy(&entry->entry.oid, oid);
5626 oidmap_put(&state.commit2label, entry);
5628 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5629 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5630 hashmap_add(&state.labels, &onto_label_entry->entry);
5634 * First phase:
5635 * - get onelines for all commits
5636 * - gather all branch tips (i.e. 2nd or later parents of merges)
5637 * - label all branch tips
5639 while ((commit = get_revision(revs))) {
5640 struct commit_list *to_merge;
5641 const char *p1, *p2;
5642 struct object_id *oid;
5643 int is_empty;
5645 tail = &commit_list_insert(commit, tail)->next;
5646 oidset_insert(&interesting, &commit->object.oid);
5648 is_empty = is_original_commit_empty(commit);
5649 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5650 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5651 warning(_("skipped previously applied commit %s"),
5652 short_commit_name(the_repository, commit));
5653 skipped_commit = 1;
5654 continue;
5656 if (is_empty && !keep_empty)
5657 continue;
5659 strbuf_reset(&oneline);
5660 pretty_print_commit(pp, commit, &oneline);
5662 to_merge = commit->parents ? commit->parents->next : NULL;
5663 if (!to_merge) {
5664 /* non-merge commit: easy case */
5665 strbuf_reset(&buf);
5666 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5667 oid_to_hex(&commit->object.oid),
5668 oneline.buf);
5669 if (is_empty)
5670 strbuf_addf(&buf, " %c empty",
5671 comment_line_char);
5673 FLEX_ALLOC_STR(entry, string, buf.buf);
5674 oidcpy(&entry->entry.oid, &commit->object.oid);
5675 oidmap_put(&commit2todo, entry);
5677 continue;
5680 /* Create a label */
5681 strbuf_reset(&label);
5682 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5683 (p1 = strchr(p1, '\'')) &&
5684 (p2 = strchr(++p1, '\'')))
5685 strbuf_add(&label, p1, p2 - p1);
5686 else if (skip_prefix(oneline.buf, "Merge pull request ",
5687 &p1) &&
5688 (p1 = strstr(p1, " from ")))
5689 strbuf_addstr(&label, p1 + strlen(" from "));
5690 else
5691 strbuf_addbuf(&label, &oneline);
5693 strbuf_reset(&buf);
5694 strbuf_addf(&buf, "%s -C %s",
5695 cmd_merge, oid_to_hex(&commit->object.oid));
5697 /* label the tips of merged branches */
5698 for (; to_merge; to_merge = to_merge->next) {
5699 oid = &to_merge->item->object.oid;
5700 strbuf_addch(&buf, ' ');
5702 if (!oidset_contains(&interesting, oid)) {
5703 strbuf_addstr(&buf, label_oid(oid, NULL,
5704 &state));
5705 continue;
5708 tips_tail = &commit_list_insert(to_merge->item,
5709 tips_tail)->next;
5711 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5713 strbuf_addf(&buf, " # %s", oneline.buf);
5715 FLEX_ALLOC_STR(entry, string, buf.buf);
5716 oidcpy(&entry->entry.oid, &commit->object.oid);
5717 oidmap_put(&commit2todo, entry);
5719 if (skipped_commit)
5720 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5721 _("use --reapply-cherry-picks to include skipped commits"));
5724 * Second phase:
5725 * - label branch points
5726 * - add HEAD to the branch tips
5728 for (iter = commits; iter; iter = iter->next) {
5729 struct commit_list *parent = iter->item->parents;
5730 for (; parent; parent = parent->next) {
5731 struct object_id *oid = &parent->item->object.oid;
5732 if (!oidset_contains(&interesting, oid))
5733 continue;
5734 if (oidset_insert(&child_seen, oid))
5735 label_oid(oid, "branch-point", &state);
5738 /* Add HEAD as implicit "tip of branch" */
5739 if (!iter->next)
5740 tips_tail = &commit_list_insert(iter->item,
5741 tips_tail)->next;
5745 * Third phase: output the todo list. This is a bit tricky, as we
5746 * want to avoid jumping back and forth between revisions. To
5747 * accomplish that goal, we walk backwards from the branch tips,
5748 * gathering commits not yet shown, reversing the list on the fly,
5749 * then outputting that list (labeling revisions as needed).
5751 strbuf_addf(out, "%s onto\n", cmd_label);
5752 for (iter = tips; iter; iter = iter->next) {
5753 struct commit_list *list = NULL, *iter2;
5755 commit = iter->item;
5756 if (oidset_contains(&shown, &commit->object.oid))
5757 continue;
5758 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5760 if (entry)
5761 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5762 else
5763 strbuf_addch(out, '\n');
5765 while (oidset_contains(&interesting, &commit->object.oid) &&
5766 !oidset_contains(&shown, &commit->object.oid)) {
5767 commit_list_insert(commit, &list);
5768 if (!commit->parents) {
5769 commit = NULL;
5770 break;
5772 commit = commit->parents->item;
5775 if (!commit)
5776 strbuf_addf(out, "%s %s\n", cmd_reset,
5777 rebase_cousins || root_with_onto ?
5778 "onto" : "[new root]");
5779 else {
5780 const char *to = NULL;
5782 entry = oidmap_get(&state.commit2label,
5783 &commit->object.oid);
5784 if (entry)
5785 to = entry->string;
5786 else if (!rebase_cousins)
5787 to = label_oid(&commit->object.oid, NULL,
5788 &state);
5790 if (!to || !strcmp(to, "onto"))
5791 strbuf_addf(out, "%s onto\n", cmd_reset);
5792 else {
5793 strbuf_reset(&oneline);
5794 pretty_print_commit(pp, commit, &oneline);
5795 strbuf_addf(out, "%s %s # %s\n",
5796 cmd_reset, to, oneline.buf);
5800 for (iter2 = list; iter2; iter2 = iter2->next) {
5801 struct object_id *oid = &iter2->item->object.oid;
5802 entry = oidmap_get(&commit2todo, oid);
5803 /* only show if not already upstream */
5804 if (entry)
5805 strbuf_addf(out, "%s\n", entry->string);
5806 entry = oidmap_get(&state.commit2label, oid);
5807 if (entry)
5808 strbuf_addf(out, "%s %s\n",
5809 cmd_label, entry->string);
5810 oidset_insert(&shown, oid);
5813 free_commit_list(list);
5816 free_commit_list(commits);
5817 free_commit_list(tips);
5819 strbuf_release(&label);
5820 strbuf_release(&oneline);
5821 strbuf_release(&buf);
5823 oidmap_free(&commit2todo, 1);
5824 oidmap_free(&state.commit2label, 1);
5825 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5826 strbuf_release(&state.buf);
5828 return 0;
5831 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5832 const char **argv, unsigned flags)
5834 char *format = NULL;
5835 struct pretty_print_context pp = {0};
5836 struct rev_info revs;
5837 struct commit *commit;
5838 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5839 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5840 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5841 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5842 int skipped_commit = 0;
5843 int ret = 0;
5845 repo_init_revisions(r, &revs, NULL);
5846 revs.verbose_header = 1;
5847 if (!rebase_merges)
5848 revs.max_parents = 1;
5849 revs.cherry_mark = !reapply_cherry_picks;
5850 revs.limited = 1;
5851 revs.reverse = 1;
5852 revs.right_only = 1;
5853 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5854 revs.topo_order = 1;
5856 revs.pretty_given = 1;
5857 git_config_get_string("rebase.instructionFormat", &format);
5858 if (!format || !*format) {
5859 free(format);
5860 format = xstrdup("%s");
5862 get_commit_format(format, &revs);
5863 free(format);
5864 pp.fmt = revs.commit_format;
5865 pp.output_encoding = get_log_output_encoding();
5867 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5868 ret = error(_("make_script: unhandled options"));
5869 goto cleanup;
5872 if (prepare_revision_walk(&revs) < 0) {
5873 ret = error(_("make_script: error preparing revisions"));
5874 goto cleanup;
5877 if (rebase_merges) {
5878 ret = make_script_with_merges(&pp, &revs, out, flags);
5879 goto cleanup;
5882 while ((commit = get_revision(&revs))) {
5883 int is_empty = is_original_commit_empty(commit);
5885 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5886 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5887 warning(_("skipped previously applied commit %s"),
5888 short_commit_name(r, commit));
5889 skipped_commit = 1;
5890 continue;
5892 if (is_empty && !keep_empty)
5893 continue;
5894 strbuf_addf(out, "%s %s ", insn,
5895 oid_to_hex(&commit->object.oid));
5896 pretty_print_commit(&pp, commit, out);
5897 if (is_empty)
5898 strbuf_addf(out, " %c empty", comment_line_char);
5899 strbuf_addch(out, '\n');
5901 if (skipped_commit)
5902 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5903 _("use --reapply-cherry-picks to include skipped commits"));
5904 cleanup:
5905 release_revisions(&revs);
5906 return ret;
5910 * Add commands after pick and (series of) squash/fixup commands
5911 * in the todo list.
5913 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5914 struct string_list *commands)
5916 struct strbuf *buf = &todo_list->buf;
5917 size_t base_offset = buf->len;
5918 int i, insert, nr = 0, alloc = 0;
5919 struct todo_item *items = NULL, *base_items = NULL;
5921 CALLOC_ARRAY(base_items, commands->nr);
5922 for (i = 0; i < commands->nr; i++) {
5923 size_t command_len = strlen(commands->items[i].string);
5925 strbuf_addstr(buf, commands->items[i].string);
5926 strbuf_addch(buf, '\n');
5928 base_items[i].command = TODO_EXEC;
5929 base_items[i].offset_in_buf = base_offset;
5930 base_items[i].arg_offset = base_offset;
5931 base_items[i].arg_len = command_len;
5933 base_offset += command_len + 1;
5937 * Insert <commands> after every pick. Here, fixup/squash chains
5938 * are considered part of the pick, so we insert the commands *after*
5939 * those chains if there are any.
5941 * As we insert the exec commands immediately after rearranging
5942 * any fixups and before the user edits the list, a fixup chain
5943 * can never contain comments (any comments are empty picks that
5944 * have been commented out because the user did not specify
5945 * --keep-empty). So, it is safe to insert an exec command
5946 * without looking at the command following a comment.
5948 insert = 0;
5949 for (i = 0; i < todo_list->nr; i++) {
5950 enum todo_command command = todo_list->items[i].command;
5951 if (insert && !is_fixup(command)) {
5952 ALLOC_GROW(items, nr + commands->nr, alloc);
5953 COPY_ARRAY(items + nr, base_items, commands->nr);
5954 nr += commands->nr;
5956 insert = 0;
5959 ALLOC_GROW(items, nr + 1, alloc);
5960 items[nr++] = todo_list->items[i];
5962 if (command == TODO_PICK || command == TODO_MERGE)
5963 insert = 1;
5966 /* insert or append final <commands> */
5967 if (insert) {
5968 ALLOC_GROW(items, nr + commands->nr, alloc);
5969 COPY_ARRAY(items + nr, base_items, commands->nr);
5970 nr += commands->nr;
5973 free(base_items);
5974 FREE_AND_NULL(todo_list->items);
5975 todo_list->items = items;
5976 todo_list->nr = nr;
5977 todo_list->alloc = alloc;
5980 static void todo_list_to_strbuf(struct repository *r,
5981 struct todo_list *todo_list,
5982 struct strbuf *buf, int num, unsigned flags)
5984 struct todo_item *item;
5985 int i, max = todo_list->nr;
5987 if (num > 0 && num < max)
5988 max = num;
5990 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5991 char cmd;
5993 /* if the item is not a command write it and continue */
5994 if (item->command >= TODO_COMMENT) {
5995 strbuf_addf(buf, "%.*s\n", item->arg_len,
5996 todo_item_get_arg(todo_list, item));
5997 continue;
6000 /* add command to the buffer */
6001 cmd = command_to_char(item->command);
6002 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6003 strbuf_addch(buf, cmd);
6004 else
6005 strbuf_addstr(buf, command_to_string(item->command));
6007 /* add commit id */
6008 if (item->commit) {
6009 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6010 short_commit_name(r, item->commit) :
6011 oid_to_hex(&item->commit->object.oid);
6013 if (item->command == TODO_FIXUP) {
6014 if (item->flags & TODO_EDIT_FIXUP_MSG)
6015 strbuf_addstr(buf, " -c");
6016 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6017 strbuf_addstr(buf, " -C");
6021 if (item->command == TODO_MERGE) {
6022 if (item->flags & TODO_EDIT_MERGE_MSG)
6023 strbuf_addstr(buf, " -c");
6024 else
6025 strbuf_addstr(buf, " -C");
6028 strbuf_addf(buf, " %s", oid);
6031 /* add all the rest */
6032 if (!item->arg_len)
6033 strbuf_addch(buf, '\n');
6034 else
6035 strbuf_addf(buf, " %.*s\n", item->arg_len,
6036 todo_item_get_arg(todo_list, item));
6040 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6041 const char *file, const char *shortrevisions,
6042 const char *shortonto, int num, unsigned flags)
6044 int res;
6045 struct strbuf buf = STRBUF_INIT;
6047 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6048 if (flags & TODO_LIST_APPEND_TODO_HELP)
6049 append_todo_help(count_commands(todo_list),
6050 shortrevisions, shortonto, &buf);
6052 res = write_message(buf.buf, buf.len, file, 0);
6053 strbuf_release(&buf);
6055 return res;
6058 /* skip picking commits whose parents are unchanged */
6059 static int skip_unnecessary_picks(struct repository *r,
6060 struct todo_list *todo_list,
6061 struct object_id *base_oid)
6063 struct object_id *parent_oid;
6064 int i;
6066 for (i = 0; i < todo_list->nr; i++) {
6067 struct todo_item *item = todo_list->items + i;
6069 if (item->command >= TODO_NOOP)
6070 continue;
6071 if (item->command != TODO_PICK)
6072 break;
6073 if (repo_parse_commit(r, item->commit)) {
6074 return error(_("could not parse commit '%s'"),
6075 oid_to_hex(&item->commit->object.oid));
6077 if (!item->commit->parents)
6078 break; /* root commit */
6079 if (item->commit->parents->next)
6080 break; /* merge commit */
6081 parent_oid = &item->commit->parents->item->object.oid;
6082 if (!oideq(parent_oid, base_oid))
6083 break;
6084 oidcpy(base_oid, &item->commit->object.oid);
6086 if (i > 0) {
6087 const char *done_path = rebase_path_done();
6089 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6090 error_errno(_("could not write to '%s'"), done_path);
6091 return -1;
6094 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6095 todo_list->nr -= i;
6096 todo_list->current = 0;
6097 todo_list->done_nr += i;
6099 if (is_fixup(peek_command(todo_list, 0)))
6100 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6103 return 0;
6106 struct todo_add_branch_context {
6107 struct todo_item *items;
6108 size_t items_nr;
6109 size_t items_alloc;
6110 struct strbuf *buf;
6111 struct commit *commit;
6112 struct string_list refs_to_oids;
6115 static int add_decorations_to_list(const struct commit *commit,
6116 struct todo_add_branch_context *ctx)
6118 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6119 const char *head_ref = resolve_ref_unsafe("HEAD",
6120 RESOLVE_REF_READING,
6121 NULL,
6122 NULL);
6124 while (decoration) {
6125 struct todo_item *item;
6126 const char *path;
6127 size_t base_offset = ctx->buf->len;
6130 * If the branch is the current HEAD, then it will be
6131 * updated by the default rebase behavior.
6133 if (head_ref && !strcmp(head_ref, decoration->name)) {
6134 decoration = decoration->next;
6135 continue;
6138 ALLOC_GROW(ctx->items,
6139 ctx->items_nr + 1,
6140 ctx->items_alloc);
6141 item = &ctx->items[ctx->items_nr];
6142 memset(item, 0, sizeof(*item));
6144 /* If the branch is checked out, then leave a comment instead. */
6145 if ((path = branch_checked_out(decoration->name))) {
6146 item->command = TODO_COMMENT;
6147 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6148 decoration->name, path);
6149 } else {
6150 struct string_list_item *sti;
6151 item->command = TODO_UPDATE_REF;
6152 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6154 sti = string_list_insert(&ctx->refs_to_oids,
6155 decoration->name);
6156 sti->util = init_update_ref_record(decoration->name);
6159 item->offset_in_buf = base_offset;
6160 item->arg_offset = base_offset;
6161 item->arg_len = ctx->buf->len - base_offset;
6162 ctx->items_nr++;
6164 decoration = decoration->next;
6167 return 0;
6171 * For each 'pick' command, find out if the commit has a decoration in
6172 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6174 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6176 int i, res;
6177 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6178 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6179 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6180 struct decoration_filter decoration_filter = {
6181 .include_ref_pattern = &decorate_refs_include,
6182 .exclude_ref_pattern = &decorate_refs_exclude,
6183 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6185 struct todo_add_branch_context ctx = {
6186 .buf = &todo_list->buf,
6187 .refs_to_oids = STRING_LIST_INIT_DUP,
6190 ctx.items_alloc = 2 * todo_list->nr + 1;
6191 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6193 string_list_append(&decorate_refs_include, "refs/heads/");
6194 load_ref_decorations(&decoration_filter, 0);
6196 for (i = 0; i < todo_list->nr; ) {
6197 struct todo_item *item = &todo_list->items[i];
6199 /* insert ith item into new list */
6200 ALLOC_GROW(ctx.items,
6201 ctx.items_nr + 1,
6202 ctx.items_alloc);
6204 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6206 if (item->commit) {
6207 ctx.commit = item->commit;
6208 add_decorations_to_list(item->commit, &ctx);
6212 res = write_update_refs_state(&ctx.refs_to_oids);
6214 string_list_clear(&ctx.refs_to_oids, 1);
6216 if (res) {
6217 /* we failed, so clean up the new list. */
6218 free(ctx.items);
6219 return res;
6222 free(todo_list->items);
6223 todo_list->items = ctx.items;
6224 todo_list->nr = ctx.items_nr;
6225 todo_list->alloc = ctx.items_alloc;
6227 return 0;
6230 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6231 const char *shortrevisions, const char *onto_name,
6232 struct commit *onto, const struct object_id *orig_head,
6233 struct string_list *commands, unsigned autosquash,
6234 unsigned update_refs,
6235 struct todo_list *todo_list)
6237 char shortonto[GIT_MAX_HEXSZ + 1];
6238 const char *todo_file = rebase_path_todo();
6239 struct todo_list new_todo = TODO_LIST_INIT;
6240 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6241 struct object_id oid = onto->object.oid;
6242 int res;
6244 repo_find_unique_abbrev_r(r, shortonto, &oid,
6245 DEFAULT_ABBREV);
6247 if (buf->len == 0) {
6248 struct todo_item *item = append_new_todo(todo_list);
6249 item->command = TODO_NOOP;
6250 item->commit = NULL;
6251 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6254 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6255 return -1;
6257 if (autosquash && todo_list_rearrange_squash(todo_list))
6258 return -1;
6260 if (commands->nr)
6261 todo_list_add_exec_commands(todo_list, commands);
6263 if (count_commands(todo_list) == 0) {
6264 apply_autostash(rebase_path_autostash());
6265 sequencer_remove_state(opts);
6267 return error(_("nothing to do"));
6270 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6271 shortonto, flags);
6272 if (res == -1)
6273 return -1;
6274 else if (res == -2) {
6275 apply_autostash(rebase_path_autostash());
6276 sequencer_remove_state(opts);
6278 return -1;
6279 } else if (res == -3) {
6280 apply_autostash(rebase_path_autostash());
6281 sequencer_remove_state(opts);
6282 todo_list_release(&new_todo);
6284 return error(_("nothing to do"));
6285 } else if (res == -4) {
6286 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6287 todo_list_release(&new_todo);
6289 return -1;
6292 /* Expand the commit IDs */
6293 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6294 strbuf_swap(&new_todo.buf, &buf2);
6295 strbuf_release(&buf2);
6296 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6297 new_todo.total_nr = 0;
6298 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6299 BUG("invalid todo list after expanding IDs:\n%s",
6300 new_todo.buf.buf);
6302 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6303 todo_list_release(&new_todo);
6304 return error(_("could not skip unnecessary pick commands"));
6307 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6308 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6309 todo_list_release(&new_todo);
6310 return error_errno(_("could not write '%s'"), todo_file);
6313 res = -1;
6315 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6316 goto cleanup;
6318 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6319 goto cleanup;
6321 todo_list_write_total_nr(&new_todo);
6322 res = pick_commits(r, &new_todo, opts);
6324 cleanup:
6325 todo_list_release(&new_todo);
6327 return res;
6330 struct subject2item_entry {
6331 struct hashmap_entry entry;
6332 int i;
6333 char subject[FLEX_ARRAY];
6336 static int subject2item_cmp(const void *fndata UNUSED,
6337 const struct hashmap_entry *eptr,
6338 const struct hashmap_entry *entry_or_key,
6339 const void *key)
6341 const struct subject2item_entry *a, *b;
6343 a = container_of(eptr, const struct subject2item_entry, entry);
6344 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6346 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6349 define_commit_slab(commit_todo_item, struct todo_item *);
6351 static int skip_fixupish(const char *subject, const char **p) {
6352 return skip_prefix(subject, "fixup! ", p) ||
6353 skip_prefix(subject, "amend! ", p) ||
6354 skip_prefix(subject, "squash! ", p);
6358 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6359 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6360 * after the former, and change "pick" to "fixup"/"squash".
6362 * Note that if the config has specified a custom instruction format, each log
6363 * message will have to be retrieved from the commit (as the oneline in the
6364 * script cannot be trusted) in order to normalize the autosquash arrangement.
6366 int todo_list_rearrange_squash(struct todo_list *todo_list)
6368 struct hashmap subject2item;
6369 int rearranged = 0, *next, *tail, i, nr = 0;
6370 char **subjects;
6371 struct commit_todo_item commit_todo;
6372 struct todo_item *items = NULL;
6374 init_commit_todo_item(&commit_todo);
6376 * The hashmap maps onelines to the respective todo list index.
6378 * If any items need to be rearranged, the next[i] value will indicate
6379 * which item was moved directly after the i'th.
6381 * In that case, last[i] will indicate the index of the latest item to
6382 * be moved to appear after the i'th.
6384 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6385 ALLOC_ARRAY(next, todo_list->nr);
6386 ALLOC_ARRAY(tail, todo_list->nr);
6387 ALLOC_ARRAY(subjects, todo_list->nr);
6388 for (i = 0; i < todo_list->nr; i++) {
6389 struct strbuf buf = STRBUF_INIT;
6390 struct todo_item *item = todo_list->items + i;
6391 const char *commit_buffer, *subject, *p;
6392 size_t subject_len;
6393 int i2 = -1;
6394 struct subject2item_entry *entry;
6396 next[i] = tail[i] = -1;
6397 if (!item->commit || item->command == TODO_DROP) {
6398 subjects[i] = NULL;
6399 continue;
6402 if (is_fixup(item->command)) {
6403 clear_commit_todo_item(&commit_todo);
6404 return error(_("the script was already rearranged."));
6407 repo_parse_commit(the_repository, item->commit);
6408 commit_buffer = repo_logmsg_reencode(the_repository,
6409 item->commit, NULL,
6410 "UTF-8");
6411 find_commit_subject(commit_buffer, &subject);
6412 format_subject(&buf, subject, " ");
6413 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6414 repo_unuse_commit_buffer(the_repository, item->commit,
6415 commit_buffer);
6416 if (skip_fixupish(subject, &p)) {
6417 struct commit *commit2;
6419 for (;;) {
6420 while (isspace(*p))
6421 p++;
6422 if (!skip_fixupish(p, &p))
6423 break;
6426 entry = hashmap_get_entry_from_hash(&subject2item,
6427 strhash(p), p,
6428 struct subject2item_entry,
6429 entry);
6430 if (entry)
6431 /* found by title */
6432 i2 = entry->i;
6433 else if (!strchr(p, ' ') &&
6434 (commit2 =
6435 lookup_commit_reference_by_name(p)) &&
6436 *commit_todo_item_at(&commit_todo, commit2))
6437 /* found by commit name */
6438 i2 = *commit_todo_item_at(&commit_todo, commit2)
6439 - todo_list->items;
6440 else {
6441 /* copy can be a prefix of the commit subject */
6442 for (i2 = 0; i2 < i; i2++)
6443 if (subjects[i2] &&
6444 starts_with(subjects[i2], p))
6445 break;
6446 if (i2 == i)
6447 i2 = -1;
6450 if (i2 >= 0) {
6451 rearranged = 1;
6452 if (starts_with(subject, "fixup!")) {
6453 todo_list->items[i].command = TODO_FIXUP;
6454 } else if (starts_with(subject, "amend!")) {
6455 todo_list->items[i].command = TODO_FIXUP;
6456 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6457 } else {
6458 todo_list->items[i].command = TODO_SQUASH;
6460 if (tail[i2] < 0) {
6461 next[i] = next[i2];
6462 next[i2] = i;
6463 } else {
6464 next[i] = next[tail[i2]];
6465 next[tail[i2]] = i;
6467 tail[i2] = i;
6468 } else if (!hashmap_get_from_hash(&subject2item,
6469 strhash(subject), subject)) {
6470 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6471 entry->i = i;
6472 hashmap_entry_init(&entry->entry,
6473 strhash(entry->subject));
6474 hashmap_put(&subject2item, &entry->entry);
6477 *commit_todo_item_at(&commit_todo, item->commit) = item;
6480 if (rearranged) {
6481 ALLOC_ARRAY(items, todo_list->nr);
6483 for (i = 0; i < todo_list->nr; i++) {
6484 enum todo_command command = todo_list->items[i].command;
6485 int cur = i;
6488 * Initially, all commands are 'pick's. If it is a
6489 * fixup or a squash now, we have rearranged it.
6491 if (is_fixup(command))
6492 continue;
6494 while (cur >= 0) {
6495 items[nr++] = todo_list->items[cur];
6496 cur = next[cur];
6500 assert(nr == todo_list->nr);
6501 todo_list->alloc = nr;
6502 FREE_AND_NULL(todo_list->items);
6503 todo_list->items = items;
6506 free(next);
6507 free(tail);
6508 for (i = 0; i < todo_list->nr; i++)
6509 free(subjects[i]);
6510 free(subjects);
6511 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6513 clear_commit_todo_item(&commit_todo);
6515 return 0;
6518 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6520 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6521 struct object_id cherry_pick_head, rebase_head;
6523 if (file_exists(git_path_seq_dir()))
6524 *whence = FROM_CHERRY_PICK_MULTI;
6525 if (file_exists(rebase_path()) &&
6526 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6527 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6528 oideq(&rebase_head, &cherry_pick_head))
6529 *whence = FROM_REBASE_PICK;
6530 else
6531 *whence = FROM_CHERRY_PICK_SINGLE;
6533 return 1;
6536 return 0;
6539 int sequencer_get_update_refs_state(const char *wt_dir,
6540 struct string_list *refs)
6542 int result = 0;
6543 FILE *fp = NULL;
6544 struct strbuf ref = STRBUF_INIT;
6545 struct strbuf hash = STRBUF_INIT;
6546 struct update_ref_record *rec = NULL;
6548 char *path = rebase_path_update_refs(wt_dir);
6550 fp = fopen(path, "r");
6551 if (!fp)
6552 goto cleanup;
6554 while (strbuf_getline(&ref, fp) != EOF) {
6555 struct string_list_item *item;
6557 CALLOC_ARRAY(rec, 1);
6559 if (strbuf_getline(&hash, fp) == EOF ||
6560 get_oid_hex(hash.buf, &rec->before)) {
6561 warning(_("update-refs file at '%s' is invalid"),
6562 path);
6563 result = -1;
6564 goto cleanup;
6567 if (strbuf_getline(&hash, fp) == EOF ||
6568 get_oid_hex(hash.buf, &rec->after)) {
6569 warning(_("update-refs file at '%s' is invalid"),
6570 path);
6571 result = -1;
6572 goto cleanup;
6575 item = string_list_insert(refs, ref.buf);
6576 item->util = rec;
6577 rec = NULL;
6580 cleanup:
6581 if (fp)
6582 fclose(fp);
6583 free(path);
6584 free(rec);
6585 strbuf_release(&ref);
6586 strbuf_release(&hash);
6587 return result;