clean: factorize incompatibility message
[git.git] / sequencer.c
blobd584cac8ed9307caad0f8a9ede98d1f57ceab874
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 "tag.h"
19 #include "run-command.h"
20 #include "hook.h"
21 #include "exec-cmd.h"
22 #include "utf8.h"
23 #include "cache-tree.h"
24 #include "diff.h"
25 #include "path.h"
26 #include "revision.h"
27 #include "rerere.h"
28 #include "merge.h"
29 #include "merge-ort.h"
30 #include "merge-ort-wrappers.h"
31 #include "refs.h"
32 #include "sparse-index.h"
33 #include "strvec.h"
34 #include "quote.h"
35 #include "trailer.h"
36 #include "log-tree.h"
37 #include "wt-status.h"
38 #include "hashmap.h"
39 #include "notes-utils.h"
40 #include "sigchain.h"
41 #include "unpack-trees.h"
42 #include "worktree.h"
43 #include "oidmap.h"
44 #include "oidset.h"
45 #include "commit-slab.h"
46 #include "alias.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
49 #include "reset.h"
50 #include "branch.h"
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
58 * are too long.
59 * Add some margin to stay clear from reaching `NAME_MAX`.
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63 static const char sign_off_header[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
66 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
68 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
70 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
75 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
82 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
85 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
90 * actions.
92 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
94 * The file to keep track of how many commands were already processed (e.g.
95 * for the prompt).
97 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
102 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
107 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
116 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
124 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
129 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
133 * being rebased.
135 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
144 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
149 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
154 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
161 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
162 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
163 "rebase-merge/rewritten-pending")
166 * The path of the file containing the OID of the "squash onto" commit, i.e.
167 * the dummy commit used for `reset [new root]`.
169 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
175 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
186 static char *rebase_path_update_refs(const char *wt_git_dir)
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
192 * The following files are written by git-rebase just after parsing the
193 * command-line.
195 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
196 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
197 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
198 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
199 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
200 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
201 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
202 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
203 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
204 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
205 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
206 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
207 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
208 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
210 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
211 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
214 * A 'struct update_refs_record' represents a value in the update-refs
215 * list. We use a string_list to map refs to these (before, after) pairs.
217 struct update_ref_record {
218 struct object_id before;
219 struct object_id after;
222 static struct update_ref_record *init_update_ref_record(const char *ref)
224 struct update_ref_record *rec;
226 CALLOC_ARRAY(rec, 1);
228 oidcpy(&rec->before, null_oid());
229 oidcpy(&rec->after, null_oid());
231 /* This may fail, but that's fine, we will keep the null OID. */
232 read_ref(ref, &rec->before);
234 return rec;
237 static int git_sequencer_config(const char *k, const char *v,
238 const struct config_context *ctx, void *cb)
240 struct replay_opts *opts = cb;
241 int status;
243 if (!strcmp(k, "commit.cleanup")) {
244 const char *s;
246 status = git_config_string(&s, k, v);
247 if (status)
248 return status;
250 if (!strcmp(s, "verbatim")) {
251 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
252 opts->explicit_cleanup = 1;
253 } else if (!strcmp(s, "whitespace")) {
254 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
255 opts->explicit_cleanup = 1;
256 } else if (!strcmp(s, "strip")) {
257 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
258 opts->explicit_cleanup = 1;
259 } else if (!strcmp(s, "scissors")) {
260 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
261 opts->explicit_cleanup = 1;
262 } else {
263 warning(_("invalid commit message cleanup mode '%s'"),
267 free((char *)s);
268 return status;
271 if (!strcmp(k, "commit.gpgsign")) {
272 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
273 return 0;
276 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
277 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
278 if (ret == 0) {
280 * pull.twohead is allowed to be multi-valued; we only
281 * care about the first value.
283 char *tmp = strchr(opts->default_strategy, ' ');
284 if (tmp)
285 *tmp = '\0';
287 return ret;
290 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
291 opts->commit_use_reference = git_config_bool(k, v);
293 return git_diff_basic_config(k, v, ctx, NULL);
296 void sequencer_init_config(struct replay_opts *opts)
298 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
299 git_config(git_sequencer_config, opts);
302 static inline int is_rebase_i(const struct replay_opts *opts)
304 return opts->action == REPLAY_INTERACTIVE_REBASE;
307 static const char *get_dir(const struct replay_opts *opts)
309 if (is_rebase_i(opts))
310 return rebase_path();
311 return git_path_seq_dir();
314 static const char *get_todo_path(const struct replay_opts *opts)
316 if (is_rebase_i(opts))
317 return rebase_path_todo();
318 return git_path_todo_file();
322 * Returns 0 for non-conforming footer
323 * Returns 1 for conforming footer
324 * Returns 2 when sob exists within conforming footer
325 * Returns 3 when sob exists within conforming footer as last entry
327 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
328 size_t ignore_footer)
330 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
331 struct trailer_info info;
332 size_t i;
333 int found_sob = 0, found_sob_last = 0;
334 char saved_char;
336 opts.no_divider = 1;
338 if (ignore_footer) {
339 saved_char = sb->buf[sb->len - ignore_footer];
340 sb->buf[sb->len - ignore_footer] = '\0';
343 trailer_info_get(&info, sb->buf, &opts);
345 if (ignore_footer)
346 sb->buf[sb->len - ignore_footer] = saved_char;
348 if (info.trailer_start == info.trailer_end)
349 return 0;
351 for (i = 0; i < info.trailer_nr; i++)
352 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
353 found_sob = 1;
354 if (i == info.trailer_nr - 1)
355 found_sob_last = 1;
358 trailer_info_release(&info);
360 if (found_sob_last)
361 return 3;
362 if (found_sob)
363 return 2;
364 return 1;
367 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
369 static struct strbuf buf = STRBUF_INIT;
371 strbuf_reset(&buf);
372 if (opts->gpg_sign)
373 sq_quotef(&buf, "-S%s", opts->gpg_sign);
374 return buf.buf;
377 void replay_opts_release(struct replay_opts *opts)
379 free(opts->gpg_sign);
380 free(opts->reflog_action);
381 free(opts->default_strategy);
382 free(opts->strategy);
383 strvec_clear (&opts->xopts);
384 strbuf_release(&opts->current_fixups);
385 if (opts->revs)
386 release_revisions(opts->revs);
387 free(opts->revs);
390 int sequencer_remove_state(struct replay_opts *opts)
392 struct strbuf buf = STRBUF_INIT;
393 int ret = 0;
395 if (is_rebase_i(opts) &&
396 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
397 char *p = buf.buf;
398 while (*p) {
399 char *eol = strchr(p, '\n');
400 if (eol)
401 *eol = '\0';
402 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
403 warning(_("could not delete '%s'"), p);
404 ret = -1;
406 if (!eol)
407 break;
408 p = eol + 1;
412 strbuf_reset(&buf);
413 strbuf_addstr(&buf, get_dir(opts));
414 if (remove_dir_recursively(&buf, 0))
415 ret = error(_("could not remove '%s'"), buf.buf);
416 strbuf_release(&buf);
418 return ret;
421 static const char *action_name(const struct replay_opts *opts)
423 switch (opts->action) {
424 case REPLAY_REVERT:
425 return N_("revert");
426 case REPLAY_PICK:
427 return N_("cherry-pick");
428 case REPLAY_INTERACTIVE_REBASE:
429 return N_("rebase");
431 die(_("unknown action: %d"), opts->action);
434 struct commit_message {
435 char *parent_label;
436 char *label;
437 char *subject;
438 const char *message;
441 static const char *short_commit_name(struct repository *r, struct commit *commit)
443 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
446 static int get_message(struct commit *commit, struct commit_message *out)
448 const char *abbrev, *subject;
449 int subject_len;
451 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
452 get_commit_output_encoding());
453 abbrev = short_commit_name(the_repository, commit);
455 subject_len = find_commit_subject(out->message, &subject);
457 out->subject = xmemdupz(subject, subject_len);
458 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
459 out->parent_label = xstrfmt("parent of %s", out->label);
461 return 0;
464 static void free_message(struct commit *commit, struct commit_message *msg)
466 free(msg->parent_label);
467 free(msg->label);
468 free(msg->subject);
469 repo_unuse_commit_buffer(the_repository, commit, msg->message);
472 static void print_advice(struct repository *r, int show_hint,
473 struct replay_opts *opts)
475 char *msg = getenv("GIT_CHERRY_PICK_HELP");
477 if (msg) {
478 advise("%s\n", msg);
480 * A conflict has occurred but the porcelain
481 * (typically rebase --interactive) wants to take care
482 * of the commit itself so remove CHERRY_PICK_HEAD
484 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
485 NULL, 0);
486 return;
489 if (show_hint) {
490 if (opts->no_commit)
491 advise(_("after resolving the conflicts, mark the corrected paths\n"
492 "with 'git add <paths>' or 'git rm <paths>'"));
493 else if (opts->action == REPLAY_PICK)
494 advise(_("After resolving the conflicts, mark them with\n"
495 "\"git add/rm <pathspec>\", then run\n"
496 "\"git cherry-pick --continue\".\n"
497 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
498 "To abort and get back to the state before \"git cherry-pick\",\n"
499 "run \"git cherry-pick --abort\"."));
500 else if (opts->action == REPLAY_REVERT)
501 advise(_("After resolving the conflicts, mark them with\n"
502 "\"git add/rm <pathspec>\", then run\n"
503 "\"git revert --continue\".\n"
504 "You can instead skip this commit with \"git revert --skip\".\n"
505 "To abort and get back to the state before \"git revert\",\n"
506 "run \"git revert --abort\"."));
507 else
508 BUG("unexpected pick action in print_advice()");
512 static int write_message(const void *buf, size_t len, const char *filename,
513 int append_eol)
515 struct lock_file msg_file = LOCK_INIT;
517 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
518 if (msg_fd < 0)
519 return error_errno(_("could not lock '%s'"), filename);
520 if (write_in_full(msg_fd, buf, len) < 0) {
521 error_errno(_("could not write to '%s'"), filename);
522 rollback_lock_file(&msg_file);
523 return -1;
525 if (append_eol && write(msg_fd, "\n", 1) < 0) {
526 error_errno(_("could not write eol to '%s'"), filename);
527 rollback_lock_file(&msg_file);
528 return -1;
530 if (commit_lock_file(&msg_file) < 0)
531 return error(_("failed to finalize '%s'"), filename);
533 return 0;
536 int read_oneliner(struct strbuf *buf,
537 const char *path, unsigned flags)
539 int orig_len = buf->len;
541 if (strbuf_read_file(buf, path, 0) < 0) {
542 if ((flags & READ_ONELINER_WARN_MISSING) ||
543 (errno != ENOENT && errno != ENOTDIR))
544 warning_errno(_("could not read '%s'"), path);
545 return 0;
548 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
549 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
550 --buf->len;
551 buf->buf[buf->len] = '\0';
554 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
555 return 0;
557 return 1;
560 static struct tree *empty_tree(struct repository *r)
562 return lookup_tree(r, the_hash_algo->empty_tree);
565 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
567 if (repo_read_index_unmerged(repo))
568 return error_resolve_conflict(action_name(opts));
570 error(_("your local changes would be overwritten by %s."),
571 _(action_name(opts)));
573 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
574 advise(_("commit your changes or stash them to proceed."));
575 return -1;
578 static void update_abort_safety_file(void)
580 struct object_id head;
582 /* Do nothing on a single-pick */
583 if (!file_exists(git_path_seq_dir()))
584 return;
586 if (!repo_get_oid(the_repository, "HEAD", &head))
587 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
588 else
589 write_file(git_path_abort_safety_file(), "%s", "");
592 static int fast_forward_to(struct repository *r,
593 const struct object_id *to,
594 const struct object_id *from,
595 int unborn,
596 struct replay_opts *opts)
598 struct ref_transaction *transaction;
599 struct strbuf sb = STRBUF_INIT;
600 struct strbuf err = STRBUF_INIT;
602 repo_read_index(r);
603 if (checkout_fast_forward(r, from, to, 1))
604 return -1; /* the callee should have complained already */
606 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
608 transaction = ref_transaction_begin(&err);
609 if (!transaction ||
610 ref_transaction_update(transaction, "HEAD",
611 to, unborn && !is_rebase_i(opts) ?
612 null_oid() : from,
613 0, sb.buf, &err) ||
614 ref_transaction_commit(transaction, &err)) {
615 ref_transaction_free(transaction);
616 error("%s", err.buf);
617 strbuf_release(&sb);
618 strbuf_release(&err);
619 return -1;
622 strbuf_release(&sb);
623 strbuf_release(&err);
624 ref_transaction_free(transaction);
625 update_abort_safety_file();
626 return 0;
629 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
630 int use_editor)
632 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
633 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
634 COMMIT_MSG_CLEANUP_SPACE;
635 else if (!strcmp(cleanup_arg, "verbatim"))
636 return COMMIT_MSG_CLEANUP_NONE;
637 else if (!strcmp(cleanup_arg, "whitespace"))
638 return COMMIT_MSG_CLEANUP_SPACE;
639 else if (!strcmp(cleanup_arg, "strip"))
640 return COMMIT_MSG_CLEANUP_ALL;
641 else if (!strcmp(cleanup_arg, "scissors"))
642 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
643 COMMIT_MSG_CLEANUP_SPACE;
644 else
645 die(_("Invalid cleanup mode %s"), cleanup_arg);
649 * NB using int rather than enum cleanup_mode to stop clang's
650 * -Wtautological-constant-out-of-range-compare complaining that the comparison
651 * is always true.
653 static const char *describe_cleanup_mode(int cleanup_mode)
655 static const char *modes[] = { "whitespace",
656 "verbatim",
657 "scissors",
658 "strip" };
660 if (cleanup_mode < ARRAY_SIZE(modes))
661 return modes[cleanup_mode];
663 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
666 void append_conflicts_hint(struct index_state *istate,
667 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
669 int i;
671 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
672 strbuf_addch(msgbuf, '\n');
673 wt_status_append_cut_line(msgbuf);
674 strbuf_addch(msgbuf, comment_line_char);
677 strbuf_addch(msgbuf, '\n');
678 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
679 for (i = 0; i < istate->cache_nr;) {
680 const struct cache_entry *ce = istate->cache[i++];
681 if (ce_stage(ce)) {
682 strbuf_commented_addf(msgbuf, comment_line_char,
683 "\t%s\n", ce->name);
684 while (i < istate->cache_nr &&
685 !strcmp(ce->name, istate->cache[i]->name))
686 i++;
691 static int do_recursive_merge(struct repository *r,
692 struct commit *base, struct commit *next,
693 const char *base_label, const char *next_label,
694 struct object_id *head, struct strbuf *msgbuf,
695 struct replay_opts *opts)
697 struct merge_options o;
698 struct merge_result result;
699 struct tree *next_tree, *base_tree, *head_tree;
700 int clean, show_output;
701 int i;
702 struct lock_file index_lock = LOCK_INIT;
704 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
705 return -1;
707 repo_read_index(r);
709 init_merge_options(&o, r);
710 o.ancestor = base ? base_label : "(empty tree)";
711 o.branch1 = "HEAD";
712 o.branch2 = next ? next_label : "(empty tree)";
713 if (is_rebase_i(opts))
714 o.buffer_output = 2;
715 o.show_rename_progress = 1;
717 head_tree = parse_tree_indirect(head);
718 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
719 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
721 for (i = 0; i < opts->xopts.nr; i++)
722 parse_merge_opt(&o, opts->xopts.v[i]);
724 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
725 memset(&result, 0, sizeof(result));
726 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
727 &result);
728 show_output = !is_rebase_i(opts) || !result.clean;
730 * TODO: merge_switch_to_result will update index/working tree;
731 * we only really want to do that if !result.clean || this is
732 * the final patch to be picked. But determining this is the
733 * final patch would take some work, and "head_tree" would need
734 * to be replace with the tree the index matched before we
735 * started doing any picks.
737 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
738 clean = result.clean;
739 } else {
740 ensure_full_index(r->index);
741 clean = merge_trees(&o, head_tree, next_tree, base_tree);
742 if (is_rebase_i(opts) && clean <= 0)
743 fputs(o.obuf.buf, stdout);
744 strbuf_release(&o.obuf);
746 if (clean < 0) {
747 rollback_lock_file(&index_lock);
748 return clean;
751 if (write_locked_index(r->index, &index_lock,
752 COMMIT_LOCK | SKIP_IF_UNCHANGED))
754 * TRANSLATORS: %s will be "revert", "cherry-pick" or
755 * "rebase".
757 return error(_("%s: Unable to write new index file"),
758 _(action_name(opts)));
760 if (!clean)
761 append_conflicts_hint(r->index, msgbuf,
762 opts->default_msg_cleanup);
764 return !clean;
767 static struct object_id *get_cache_tree_oid(struct index_state *istate)
769 if (!cache_tree_fully_valid(istate->cache_tree))
770 if (cache_tree_update(istate, 0)) {
771 error(_("unable to update cache tree"));
772 return NULL;
775 return &istate->cache_tree->oid;
778 static int is_index_unchanged(struct repository *r)
780 struct object_id head_oid, *cache_tree_oid;
781 struct commit *head_commit;
782 struct index_state *istate = r->index;
784 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
785 return error(_("could not resolve HEAD commit"));
787 head_commit = lookup_commit(r, &head_oid);
790 * If head_commit is NULL, check_commit, called from
791 * lookup_commit, would have indicated that head_commit is not
792 * a commit object already. repo_parse_commit() will return failure
793 * without further complaints in such a case. Otherwise, if
794 * the commit is invalid, repo_parse_commit() will complain. So
795 * there is nothing for us to say here. Just return failure.
797 if (repo_parse_commit(r, head_commit))
798 return -1;
800 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
801 return -1;
803 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
806 static int write_author_script(const char *message)
808 struct strbuf buf = STRBUF_INIT;
809 const char *eol;
810 int res;
812 for (;;)
813 if (!*message || starts_with(message, "\n")) {
814 missing_author:
815 /* Missing 'author' line? */
816 unlink(rebase_path_author_script());
817 return 0;
818 } else if (skip_prefix(message, "author ", &message))
819 break;
820 else if ((eol = strchr(message, '\n')))
821 message = eol + 1;
822 else
823 goto missing_author;
825 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
826 while (*message && *message != '\n' && *message != '\r')
827 if (skip_prefix(message, " <", &message))
828 break;
829 else if (*message != '\'')
830 strbuf_addch(&buf, *(message++));
831 else
832 strbuf_addf(&buf, "'\\%c'", *(message++));
833 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
834 while (*message && *message != '\n' && *message != '\r')
835 if (skip_prefix(message, "> ", &message))
836 break;
837 else if (*message != '\'')
838 strbuf_addch(&buf, *(message++));
839 else
840 strbuf_addf(&buf, "'\\%c'", *(message++));
841 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
842 while (*message && *message != '\n' && *message != '\r')
843 if (*message != '\'')
844 strbuf_addch(&buf, *(message++));
845 else
846 strbuf_addf(&buf, "'\\%c'", *(message++));
847 strbuf_addch(&buf, '\'');
848 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
849 strbuf_release(&buf);
850 return res;
854 * Take a series of KEY='VALUE' lines where VALUE part is
855 * sq-quoted, and append <KEY, VALUE> at the end of the string list
857 static int parse_key_value_squoted(char *buf, struct string_list *list)
859 while (*buf) {
860 struct string_list_item *item;
861 char *np;
862 char *cp = strchr(buf, '=');
863 if (!cp) {
864 np = strchrnul(buf, '\n');
865 return error(_("no key present in '%.*s'"),
866 (int) (np - buf), buf);
868 np = strchrnul(cp, '\n');
869 *cp++ = '\0';
870 item = string_list_append(list, buf);
872 buf = np + (*np == '\n');
873 *np = '\0';
874 cp = sq_dequote(cp);
875 if (!cp)
876 return error(_("unable to dequote value of '%s'"),
877 item->string);
878 item->util = xstrdup(cp);
880 return 0;
884 * Reads and parses the state directory's "author-script" file, and sets name,
885 * email and date accordingly.
886 * Returns 0 on success, -1 if the file could not be parsed.
888 * The author script is of the format:
890 * GIT_AUTHOR_NAME='$author_name'
891 * GIT_AUTHOR_EMAIL='$author_email'
892 * GIT_AUTHOR_DATE='$author_date'
894 * where $author_name, $author_email and $author_date are quoted. We are strict
895 * with our parsing, as the file was meant to be eval'd in the now-removed
896 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
897 * from what this function expects, it is better to bail out than to do
898 * something that the user does not expect.
900 int read_author_script(const char *path, char **name, char **email, char **date,
901 int allow_missing)
903 struct strbuf buf = STRBUF_INIT;
904 struct string_list kv = STRING_LIST_INIT_DUP;
905 int retval = -1; /* assume failure */
906 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
908 if (strbuf_read_file(&buf, path, 256) <= 0) {
909 strbuf_release(&buf);
910 if (errno == ENOENT && allow_missing)
911 return 0;
912 else
913 return error_errno(_("could not open '%s' for reading"),
914 path);
917 if (parse_key_value_squoted(buf.buf, &kv))
918 goto finish;
920 for (i = 0; i < kv.nr; i++) {
921 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
922 if (name_i != -2)
923 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
924 else
925 name_i = i;
926 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
927 if (email_i != -2)
928 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
929 else
930 email_i = i;
931 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
932 if (date_i != -2)
933 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
934 else
935 date_i = i;
936 } else {
937 err = error(_("unknown variable '%s'"),
938 kv.items[i].string);
941 if (name_i == -2)
942 error(_("missing 'GIT_AUTHOR_NAME'"));
943 if (email_i == -2)
944 error(_("missing 'GIT_AUTHOR_EMAIL'"));
945 if (date_i == -2)
946 error(_("missing 'GIT_AUTHOR_DATE'"));
947 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
948 goto finish;
949 *name = kv.items[name_i].util;
950 *email = kv.items[email_i].util;
951 *date = kv.items[date_i].util;
952 retval = 0;
953 finish:
954 string_list_clear(&kv, !!retval);
955 strbuf_release(&buf);
956 return retval;
960 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
961 * file with shell quoting into struct strvec. Returns -1 on
962 * error, 0 otherwise.
964 static int read_env_script(struct strvec *env)
966 char *name, *email, *date;
968 if (read_author_script(rebase_path_author_script(),
969 &name, &email, &date, 0))
970 return -1;
972 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
973 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
974 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
975 free(name);
976 free(email);
977 free(date);
979 return 0;
982 static char *get_author(const char *message)
984 size_t len;
985 const char *a;
987 a = find_commit_header(message, "author", &len);
988 if (a)
989 return xmemdupz(a, len);
991 return NULL;
994 static const char *author_date_from_env(const struct strvec *env)
996 int i;
997 const char *date;
999 for (i = 0; i < env->nr; i++)
1000 if (skip_prefix(env->v[i],
1001 "GIT_AUTHOR_DATE=", &date))
1002 return date;
1004 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1005 * reading the script
1007 BUG("GIT_AUTHOR_DATE missing from author script");
1010 static const char staged_changes_advice[] =
1011 N_("you have staged changes in your working tree\n"
1012 "If these changes are meant to be squashed into the previous commit, run:\n"
1013 "\n"
1014 " git commit --amend %s\n"
1015 "\n"
1016 "If they are meant to go into a new commit, run:\n"
1017 "\n"
1018 " git commit %s\n"
1019 "\n"
1020 "In both cases, once you're done, continue with:\n"
1021 "\n"
1022 " git rebase --continue\n");
1024 #define ALLOW_EMPTY (1<<0)
1025 #define EDIT_MSG (1<<1)
1026 #define AMEND_MSG (1<<2)
1027 #define CLEANUP_MSG (1<<3)
1028 #define VERIFY_MSG (1<<4)
1029 #define CREATE_ROOT_COMMIT (1<<5)
1030 #define VERBATIM_MSG (1<<6)
1032 static int run_command_silent_on_success(struct child_process *cmd)
1034 struct strbuf buf = STRBUF_INIT;
1035 int rc;
1037 cmd->stdout_to_stderr = 1;
1038 rc = pipe_command(cmd,
1039 NULL, 0,
1040 NULL, 0,
1041 &buf, 0);
1043 if (rc)
1044 fputs(buf.buf, stderr);
1045 strbuf_release(&buf);
1046 return rc;
1050 * If we are cherry-pick, and if the merge did not result in
1051 * hand-editing, we will hit this commit and inherit the original
1052 * author date and name.
1054 * If we are revert, or if our cherry-pick results in a hand merge,
1055 * we had better say that the current user is responsible for that.
1057 * An exception is when run_git_commit() is called during an
1058 * interactive rebase: in that case, we will want to retain the
1059 * author metadata.
1061 static int run_git_commit(const char *defmsg,
1062 struct replay_opts *opts,
1063 unsigned int flags)
1065 struct child_process cmd = CHILD_PROCESS_INIT;
1067 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1068 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1070 cmd.git_cmd = 1;
1072 if (is_rebase_i(opts) &&
1073 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1074 !(!defmsg && (flags & AMEND_MSG))) &&
1075 read_env_script(&cmd.env)) {
1076 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1078 return error(_(staged_changes_advice),
1079 gpg_opt, gpg_opt);
1082 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1084 if (opts->committer_date_is_author_date)
1085 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1086 opts->ignore_date ?
1087 "" :
1088 author_date_from_env(&cmd.env));
1089 if (opts->ignore_date)
1090 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1092 strvec_push(&cmd.args, "commit");
1094 if (!(flags & VERIFY_MSG))
1095 strvec_push(&cmd.args, "-n");
1096 if ((flags & AMEND_MSG))
1097 strvec_push(&cmd.args, "--amend");
1098 if (opts->gpg_sign)
1099 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1100 else
1101 strvec_push(&cmd.args, "--no-gpg-sign");
1102 if (defmsg)
1103 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1104 else if (!(flags & EDIT_MSG))
1105 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1106 if ((flags & CLEANUP_MSG))
1107 strvec_push(&cmd.args, "--cleanup=strip");
1108 if ((flags & VERBATIM_MSG))
1109 strvec_push(&cmd.args, "--cleanup=verbatim");
1110 if ((flags & EDIT_MSG))
1111 strvec_push(&cmd.args, "-e");
1112 else if (!(flags & CLEANUP_MSG) &&
1113 !opts->signoff && !opts->record_origin &&
1114 !opts->explicit_cleanup)
1115 strvec_push(&cmd.args, "--cleanup=verbatim");
1117 if ((flags & ALLOW_EMPTY))
1118 strvec_push(&cmd.args, "--allow-empty");
1120 if (!(flags & EDIT_MSG))
1121 strvec_push(&cmd.args, "--allow-empty-message");
1123 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1124 return run_command_silent_on_success(&cmd);
1125 else
1126 return run_command(&cmd);
1129 static int rest_is_empty(const struct strbuf *sb, int start)
1131 int i, eol;
1132 const char *nl;
1134 /* Check if the rest is just whitespace and Signed-off-by's. */
1135 for (i = start; i < sb->len; i++) {
1136 nl = memchr(sb->buf + i, '\n', sb->len - i);
1137 if (nl)
1138 eol = nl - sb->buf;
1139 else
1140 eol = sb->len;
1142 if (strlen(sign_off_header) <= eol - i &&
1143 starts_with(sb->buf + i, sign_off_header)) {
1144 i = eol;
1145 continue;
1147 while (i < eol)
1148 if (!isspace(sb->buf[i++]))
1149 return 0;
1152 return 1;
1155 void cleanup_message(struct strbuf *msgbuf,
1156 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1158 if (verbose || /* Truncate the message just before the diff, if any. */
1159 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1160 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1161 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1162 strbuf_stripspace(msgbuf,
1163 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1167 * Find out if the message in the strbuf contains only whitespace and
1168 * Signed-off-by lines.
1170 int message_is_empty(const struct strbuf *sb,
1171 enum commit_msg_cleanup_mode cleanup_mode)
1173 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1174 return 0;
1175 return rest_is_empty(sb, 0);
1179 * See if the user edited the message in the editor or left what
1180 * was in the template intact
1182 int template_untouched(const struct strbuf *sb, const char *template_file,
1183 enum commit_msg_cleanup_mode cleanup_mode)
1185 struct strbuf tmpl = STRBUF_INIT;
1186 const char *start;
1188 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1189 return 0;
1191 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1192 return 0;
1194 strbuf_stripspace(&tmpl,
1195 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1196 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1197 start = sb->buf;
1198 strbuf_release(&tmpl);
1199 return rest_is_empty(sb, start - sb->buf);
1202 int update_head_with_reflog(const struct commit *old_head,
1203 const struct object_id *new_head,
1204 const char *action, const struct strbuf *msg,
1205 struct strbuf *err)
1207 struct ref_transaction *transaction;
1208 struct strbuf sb = STRBUF_INIT;
1209 const char *nl;
1210 int ret = 0;
1212 if (action) {
1213 strbuf_addstr(&sb, action);
1214 strbuf_addstr(&sb, ": ");
1217 nl = strchr(msg->buf, '\n');
1218 if (nl) {
1219 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1220 } else {
1221 strbuf_addbuf(&sb, msg);
1222 strbuf_addch(&sb, '\n');
1225 transaction = ref_transaction_begin(err);
1226 if (!transaction ||
1227 ref_transaction_update(transaction, "HEAD", new_head,
1228 old_head ? &old_head->object.oid : null_oid(),
1229 0, sb.buf, err) ||
1230 ref_transaction_commit(transaction, err)) {
1231 ret = -1;
1233 ref_transaction_free(transaction);
1234 strbuf_release(&sb);
1236 return ret;
1239 static int run_rewrite_hook(const struct object_id *oldoid,
1240 const struct object_id *newoid)
1242 struct child_process proc = CHILD_PROCESS_INIT;
1243 int code;
1244 struct strbuf sb = STRBUF_INIT;
1245 const char *hook_path = find_hook("post-rewrite");
1247 if (!hook_path)
1248 return 0;
1250 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1251 proc.in = -1;
1252 proc.stdout_to_stderr = 1;
1253 proc.trace2_hook_name = "post-rewrite";
1255 code = start_command(&proc);
1256 if (code)
1257 return code;
1258 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1259 sigchain_push(SIGPIPE, SIG_IGN);
1260 write_in_full(proc.in, sb.buf, sb.len);
1261 close(proc.in);
1262 strbuf_release(&sb);
1263 sigchain_pop(SIGPIPE);
1264 return finish_command(&proc);
1267 void commit_post_rewrite(struct repository *r,
1268 const struct commit *old_head,
1269 const struct object_id *new_head)
1271 struct notes_rewrite_cfg *cfg;
1273 cfg = init_copy_notes_for_rewrite("amend");
1274 if (cfg) {
1275 /* we are amending, so old_head is not NULL */
1276 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1277 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1279 run_rewrite_hook(&old_head->object.oid, new_head);
1282 static int run_prepare_commit_msg_hook(struct repository *r,
1283 struct strbuf *msg,
1284 const char *commit)
1286 int ret = 0;
1287 const char *name, *arg1 = NULL, *arg2 = NULL;
1289 name = git_path_commit_editmsg();
1290 if (write_message(msg->buf, msg->len, name, 0))
1291 return -1;
1293 if (commit) {
1294 arg1 = "commit";
1295 arg2 = commit;
1296 } else {
1297 arg1 = "message";
1299 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1300 arg1, arg2, NULL))
1301 ret = error(_("'prepare-commit-msg' hook failed"));
1303 return ret;
1306 static const char implicit_ident_advice_noconfig[] =
1307 N_("Your name and email address were configured automatically based\n"
1308 "on your username and hostname. Please check that they are accurate.\n"
1309 "You can suppress this message by setting them explicitly. Run the\n"
1310 "following command and follow the instructions in your editor to edit\n"
1311 "your configuration file:\n"
1312 "\n"
1313 " git config --global --edit\n"
1314 "\n"
1315 "After doing this, you may fix the identity used for this commit with:\n"
1316 "\n"
1317 " git commit --amend --reset-author\n");
1319 static const char implicit_ident_advice_config[] =
1320 N_("Your name and email address were configured automatically based\n"
1321 "on your username and hostname. Please check that they are accurate.\n"
1322 "You can suppress this message by setting them explicitly:\n"
1323 "\n"
1324 " git config --global user.name \"Your Name\"\n"
1325 " git config --global user.email you@example.com\n"
1326 "\n"
1327 "After doing this, you may fix the identity used for this commit with:\n"
1328 "\n"
1329 " git commit --amend --reset-author\n");
1331 static const char *implicit_ident_advice(void)
1333 char *user_config = interpolate_path("~/.gitconfig", 0);
1334 char *xdg_config = xdg_config_home("config");
1335 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1337 free(user_config);
1338 free(xdg_config);
1340 if (config_exists)
1341 return _(implicit_ident_advice_config);
1342 else
1343 return _(implicit_ident_advice_noconfig);
1347 void print_commit_summary(struct repository *r,
1348 const char *prefix,
1349 const struct object_id *oid,
1350 unsigned int flags)
1352 struct rev_info rev;
1353 struct commit *commit;
1354 struct strbuf format = STRBUF_INIT;
1355 const char *head;
1356 struct pretty_print_context pctx = {0};
1357 struct strbuf author_ident = STRBUF_INIT;
1358 struct strbuf committer_ident = STRBUF_INIT;
1359 struct ref_store *refs;
1361 commit = lookup_commit(r, oid);
1362 if (!commit)
1363 die(_("couldn't look up newly created commit"));
1364 if (repo_parse_commit(r, commit))
1365 die(_("could not parse newly created commit"));
1367 strbuf_addstr(&format, "format:%h] %s");
1369 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1370 &pctx);
1371 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1372 &pctx);
1373 if (strbuf_cmp(&author_ident, &committer_ident)) {
1374 strbuf_addstr(&format, "\n Author: ");
1375 strbuf_addbuf_percentquote(&format, &author_ident);
1377 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1378 struct strbuf date = STRBUF_INIT;
1380 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1381 strbuf_addstr(&format, "\n Date: ");
1382 strbuf_addbuf_percentquote(&format, &date);
1383 strbuf_release(&date);
1385 if (!committer_ident_sufficiently_given()) {
1386 strbuf_addstr(&format, "\n Committer: ");
1387 strbuf_addbuf_percentquote(&format, &committer_ident);
1388 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1389 strbuf_addch(&format, '\n');
1390 strbuf_addstr(&format, implicit_ident_advice());
1393 strbuf_release(&author_ident);
1394 strbuf_release(&committer_ident);
1396 repo_init_revisions(r, &rev, prefix);
1397 setup_revisions(0, NULL, &rev, NULL);
1399 rev.diff = 1;
1400 rev.diffopt.output_format =
1401 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1403 rev.verbose_header = 1;
1404 rev.show_root_diff = 1;
1405 get_commit_format(format.buf, &rev);
1406 rev.always_show_header = 0;
1407 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1408 diff_setup_done(&rev.diffopt);
1410 refs = get_main_ref_store(r);
1411 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1412 if (!head)
1413 die(_("unable to resolve HEAD after creating commit"));
1414 if (!strcmp(head, "HEAD"))
1415 head = _("detached HEAD");
1416 else
1417 skip_prefix(head, "refs/heads/", &head);
1418 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1419 _(" (root-commit)") : "");
1421 if (!log_tree_commit(&rev, commit)) {
1422 rev.always_show_header = 1;
1423 rev.use_terminator = 1;
1424 log_tree_commit(&rev, commit);
1427 release_revisions(&rev);
1428 strbuf_release(&format);
1431 static int parse_head(struct repository *r, struct commit **head)
1433 struct commit *current_head;
1434 struct object_id oid;
1436 if (repo_get_oid(r, "HEAD", &oid)) {
1437 current_head = NULL;
1438 } else {
1439 current_head = lookup_commit_reference(r, &oid);
1440 if (!current_head)
1441 return error(_("could not parse HEAD"));
1442 if (!oideq(&oid, &current_head->object.oid)) {
1443 warning(_("HEAD %s is not a commit!"),
1444 oid_to_hex(&oid));
1446 if (repo_parse_commit(r, current_head))
1447 return error(_("could not parse HEAD commit"));
1449 *head = current_head;
1451 return 0;
1455 * Try to commit without forking 'git commit'. In some cases we need
1456 * to run 'git commit' to display an error message
1458 * Returns:
1459 * -1 - error unable to commit
1460 * 0 - success
1461 * 1 - run 'git commit'
1463 static int try_to_commit(struct repository *r,
1464 struct strbuf *msg, const char *author,
1465 struct replay_opts *opts, unsigned int flags,
1466 struct object_id *oid)
1468 struct object_id tree;
1469 struct commit *current_head = NULL;
1470 struct commit_list *parents = NULL;
1471 struct commit_extra_header *extra = NULL;
1472 struct strbuf err = STRBUF_INIT;
1473 struct strbuf commit_msg = STRBUF_INIT;
1474 char *amend_author = NULL;
1475 const char *committer = NULL;
1476 const char *hook_commit = NULL;
1477 enum commit_msg_cleanup_mode cleanup;
1478 int res = 0;
1480 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1481 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1483 if (parse_head(r, &current_head))
1484 return -1;
1486 if (flags & AMEND_MSG) {
1487 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1488 const char *out_enc = get_commit_output_encoding();
1489 const char *message = repo_logmsg_reencode(r, current_head,
1490 NULL, out_enc);
1492 if (!msg) {
1493 const char *orig_message = NULL;
1495 find_commit_subject(message, &orig_message);
1496 msg = &commit_msg;
1497 strbuf_addstr(msg, orig_message);
1498 hook_commit = "HEAD";
1500 author = amend_author = get_author(message);
1501 repo_unuse_commit_buffer(r, current_head,
1502 message);
1503 if (!author) {
1504 res = error(_("unable to parse commit author"));
1505 goto out;
1507 parents = copy_commit_list(current_head->parents);
1508 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1509 } else if (current_head &&
1510 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1511 commit_list_insert(current_head, &parents);
1514 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1515 res = error(_("git write-tree failed to write a tree"));
1516 goto out;
1519 if (!(flags & ALLOW_EMPTY)) {
1520 struct commit *first_parent = current_head;
1522 if (flags & AMEND_MSG) {
1523 if (current_head->parents) {
1524 first_parent = current_head->parents->item;
1525 if (repo_parse_commit(r, first_parent)) {
1526 res = error(_("could not parse HEAD commit"));
1527 goto out;
1529 } else {
1530 first_parent = NULL;
1533 if (oideq(first_parent
1534 ? get_commit_tree_oid(first_parent)
1535 : the_hash_algo->empty_tree,
1536 &tree)) {
1537 res = 1; /* run 'git commit' to display error message */
1538 goto out;
1542 if (hook_exists("prepare-commit-msg")) {
1543 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1544 if (res)
1545 goto out;
1546 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1547 2048) < 0) {
1548 res = error_errno(_("unable to read commit message "
1549 "from '%s'"),
1550 git_path_commit_editmsg());
1551 goto out;
1553 msg = &commit_msg;
1556 if (flags & CLEANUP_MSG)
1557 cleanup = COMMIT_MSG_CLEANUP_ALL;
1558 else if (flags & VERBATIM_MSG)
1559 cleanup = COMMIT_MSG_CLEANUP_NONE;
1560 else if ((opts->signoff || opts->record_origin) &&
1561 !opts->explicit_cleanup)
1562 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1563 else
1564 cleanup = opts->default_msg_cleanup;
1566 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1567 strbuf_stripspace(msg,
1568 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1569 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1570 res = 1; /* run 'git commit' to display error message */
1571 goto out;
1574 if (opts->committer_date_is_author_date) {
1575 struct ident_split id;
1576 struct strbuf date = STRBUF_INIT;
1578 if (!opts->ignore_date) {
1579 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1580 res = error(_("invalid author identity '%s'"),
1581 author);
1582 goto out;
1584 if (!id.date_begin) {
1585 res = error(_(
1586 "corrupt author: missing date information"));
1587 goto out;
1589 strbuf_addf(&date, "@%.*s %.*s",
1590 (int)(id.date_end - id.date_begin),
1591 id.date_begin,
1592 (int)(id.tz_end - id.tz_begin),
1593 id.tz_begin);
1594 } else {
1595 reset_ident_date();
1597 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1598 getenv("GIT_COMMITTER_EMAIL"),
1599 WANT_COMMITTER_IDENT,
1600 opts->ignore_date ? NULL : date.buf,
1601 IDENT_STRICT);
1602 strbuf_release(&date);
1603 } else {
1604 reset_ident_date();
1607 if (opts->ignore_date) {
1608 struct ident_split id;
1609 char *name, *email;
1611 if (split_ident_line(&id, author, strlen(author)) < 0) {
1612 error(_("invalid author identity '%s'"), author);
1613 goto out;
1615 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1616 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1617 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1618 IDENT_STRICT);
1619 free(name);
1620 free(email);
1623 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1624 author, committer, opts->gpg_sign, extra)) {
1625 res = error(_("failed to write commit object"));
1626 goto out;
1629 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1630 msg, &err)) {
1631 res = error("%s", err.buf);
1632 goto out;
1635 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1636 if (flags & AMEND_MSG)
1637 commit_post_rewrite(r, current_head, oid);
1639 out:
1640 free_commit_extra_headers(extra);
1641 strbuf_release(&err);
1642 strbuf_release(&commit_msg);
1643 free(amend_author);
1645 return res;
1648 static int write_rebase_head(struct object_id *oid)
1650 if (update_ref("rebase", "REBASE_HEAD", oid,
1651 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1652 return error(_("could not update %s"), "REBASE_HEAD");
1654 return 0;
1657 static int do_commit(struct repository *r,
1658 const char *msg_file, const char *author,
1659 struct replay_opts *opts, unsigned int flags,
1660 struct object_id *oid)
1662 int res = 1;
1664 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1665 struct object_id oid;
1666 struct strbuf sb = STRBUF_INIT;
1668 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1669 return error_errno(_("unable to read commit message "
1670 "from '%s'"),
1671 msg_file);
1673 res = try_to_commit(r, msg_file ? &sb : NULL,
1674 author, opts, flags, &oid);
1675 strbuf_release(&sb);
1676 if (!res) {
1677 refs_delete_ref(get_main_ref_store(r), "",
1678 "CHERRY_PICK_HEAD", NULL, 0);
1679 unlink(git_path_merge_msg(r));
1680 if (!is_rebase_i(opts))
1681 print_commit_summary(r, NULL, &oid,
1682 SUMMARY_SHOW_AUTHOR_DATE);
1683 return res;
1686 if (res == 1) {
1687 if (is_rebase_i(opts) && oid)
1688 if (write_rebase_head(oid))
1689 return -1;
1690 return run_git_commit(msg_file, opts, flags);
1693 return res;
1696 static int is_original_commit_empty(struct commit *commit)
1698 const struct object_id *ptree_oid;
1700 if (repo_parse_commit(the_repository, commit))
1701 return error(_("could not parse commit %s"),
1702 oid_to_hex(&commit->object.oid));
1703 if (commit->parents) {
1704 struct commit *parent = commit->parents->item;
1705 if (repo_parse_commit(the_repository, parent))
1706 return error(_("could not parse parent commit %s"),
1707 oid_to_hex(&parent->object.oid));
1708 ptree_oid = get_commit_tree_oid(parent);
1709 } else {
1710 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1713 return oideq(ptree_oid, get_commit_tree_oid(commit));
1717 * Should empty commits be allowed? Return status:
1718 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1719 * 0: Halt on empty commit
1720 * 1: Allow empty commit
1721 * 2: Drop empty commit
1723 static int allow_empty(struct repository *r,
1724 struct replay_opts *opts,
1725 struct commit *commit)
1727 int index_unchanged, originally_empty;
1730 * Four cases:
1732 * (1) we do not allow empty at all and error out.
1734 * (2) we allow ones that were initially empty, and
1735 * just drop the ones that become empty
1737 * (3) we allow ones that were initially empty, but
1738 * halt for the ones that become empty;
1740 * (4) we allow both.
1742 if (!opts->allow_empty)
1743 return 0; /* let "git commit" barf as necessary */
1745 index_unchanged = is_index_unchanged(r);
1746 if (index_unchanged < 0)
1747 return index_unchanged;
1748 if (!index_unchanged)
1749 return 0; /* we do not have to say --allow-empty */
1751 if (opts->keep_redundant_commits)
1752 return 1;
1754 originally_empty = is_original_commit_empty(commit);
1755 if (originally_empty < 0)
1756 return originally_empty;
1757 if (originally_empty)
1758 return 1;
1759 else if (opts->drop_redundant_commits)
1760 return 2;
1761 else
1762 return 0;
1765 static struct {
1766 char c;
1767 const char *str;
1768 } todo_command_info[] = {
1769 [TODO_PICK] = { 'p', "pick" },
1770 [TODO_REVERT] = { 0, "revert" },
1771 [TODO_EDIT] = { 'e', "edit" },
1772 [TODO_REWORD] = { 'r', "reword" },
1773 [TODO_FIXUP] = { 'f', "fixup" },
1774 [TODO_SQUASH] = { 's', "squash" },
1775 [TODO_EXEC] = { 'x', "exec" },
1776 [TODO_BREAK] = { 'b', "break" },
1777 [TODO_LABEL] = { 'l', "label" },
1778 [TODO_RESET] = { 't', "reset" },
1779 [TODO_MERGE] = { 'm', "merge" },
1780 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1781 [TODO_NOOP] = { 0, "noop" },
1782 [TODO_DROP] = { 'd', "drop" },
1783 [TODO_COMMENT] = { 0, NULL },
1786 static const char *command_to_string(const enum todo_command command)
1788 if (command < TODO_COMMENT)
1789 return todo_command_info[command].str;
1790 die(_("unknown command: %d"), command);
1793 static char command_to_char(const enum todo_command command)
1795 if (command < TODO_COMMENT)
1796 return todo_command_info[command].c;
1797 return comment_line_char;
1800 static int is_noop(const enum todo_command command)
1802 return TODO_NOOP <= command;
1805 static int is_fixup(enum todo_command command)
1807 return command == TODO_FIXUP || command == TODO_SQUASH;
1810 /* Does this command create a (non-merge) commit? */
1811 static int is_pick_or_similar(enum todo_command command)
1813 switch (command) {
1814 case TODO_PICK:
1815 case TODO_REVERT:
1816 case TODO_EDIT:
1817 case TODO_REWORD:
1818 case TODO_FIXUP:
1819 case TODO_SQUASH:
1820 return 1;
1821 default:
1822 return 0;
1826 enum todo_item_flags {
1827 TODO_EDIT_MERGE_MSG = (1 << 0),
1828 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1829 TODO_EDIT_FIXUP_MSG = (1 << 2),
1832 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1833 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1834 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1835 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1836 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1838 static int is_fixup_flag(enum todo_command command, unsigned flag)
1840 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1841 (flag & TODO_EDIT_FIXUP_MSG));
1845 * Wrapper around strbuf_add_commented_lines() which avoids double
1846 * commenting commit subjects.
1848 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1850 const char *s = str;
1851 while (len > 0 && s[0] == comment_line_char) {
1852 size_t count;
1853 const char *n = memchr(s, '\n', len);
1854 if (!n)
1855 count = len;
1856 else
1857 count = n - s + 1;
1858 strbuf_add(buf, s, count);
1859 s += count;
1860 len -= count;
1862 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1865 /* Does the current fixup chain contain a squash command? */
1866 static int seen_squash(struct replay_opts *opts)
1868 return starts_with(opts->current_fixups.buf, "squash") ||
1869 strstr(opts->current_fixups.buf, "\nsquash");
1872 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1874 strbuf_setlen(buf1, 2);
1875 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1876 strbuf_addch(buf1, '\n');
1877 strbuf_setlen(buf2, 2);
1878 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1879 strbuf_addch(buf2, '\n');
1883 * Comment out any un-commented commit messages, updating the message comments
1884 * to say they will be skipped but do not comment out the empty lines that
1885 * surround commit messages and their comments.
1887 static void update_squash_message_for_fixup(struct strbuf *msg)
1889 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1890 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1891 const char *s, *start;
1892 char *orig_msg;
1893 size_t orig_msg_len;
1894 int i = 1;
1896 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1897 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1898 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1899 while (s) {
1900 const char *next;
1901 size_t off;
1902 if (skip_prefix(s, buf1.buf, &next)) {
1904 * Copy the last message, preserving the blank line
1905 * preceding the current line
1907 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1908 copy_lines(msg, start, s - start - off);
1909 if (off)
1910 strbuf_addch(msg, '\n');
1912 * The next message needs to be commented out but the
1913 * message header is already commented out so just copy
1914 * it and the blank line that follows it.
1916 strbuf_addbuf(msg, &buf2);
1917 if (*next == '\n')
1918 strbuf_addch(msg, *next++);
1919 start = s = next;
1920 copy_lines = add_commented_lines;
1921 update_comment_bufs(&buf1, &buf2, ++i);
1922 } else if (skip_prefix(s, buf2.buf, &next)) {
1923 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1924 copy_lines(msg, start, s - start - off);
1925 start = s - off;
1926 s = next;
1927 copy_lines = strbuf_add;
1928 update_comment_bufs(&buf1, &buf2, ++i);
1929 } else {
1930 s = strchr(s, '\n');
1931 if (s)
1932 s++;
1935 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1936 free(orig_msg);
1937 strbuf_release(&buf1);
1938 strbuf_release(&buf2);
1941 static int append_squash_message(struct strbuf *buf, const char *body,
1942 enum todo_command command, struct replay_opts *opts,
1943 unsigned flag)
1945 const char *fixup_msg;
1946 size_t commented_len = 0, fixup_off;
1948 * amend is non-interactive and not normally used with fixup!
1949 * or squash! commits, so only comment out those subjects when
1950 * squashing commit messages.
1952 if (starts_with(body, "amend!") ||
1953 ((command == TODO_SQUASH || seen_squash(opts)) &&
1954 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1955 commented_len = commit_subject_length(body);
1957 strbuf_addf(buf, "\n%c ", comment_line_char);
1958 strbuf_addf(buf, _(nth_commit_msg_fmt),
1959 ++opts->current_fixup_count + 1);
1960 strbuf_addstr(buf, "\n\n");
1961 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1962 /* buf->buf may be reallocated so store an offset into the buffer */
1963 fixup_off = buf->len;
1964 strbuf_addstr(buf, body + commented_len);
1966 /* fixup -C after squash behaves like squash */
1967 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1969 * We're replacing the commit message so we need to
1970 * append the Signed-off-by: trailer if the user
1971 * requested '--signoff'.
1973 if (opts->signoff)
1974 append_signoff(buf, 0, 0);
1976 if ((command == TODO_FIXUP) &&
1977 (flag & TODO_REPLACE_FIXUP_MSG) &&
1978 (file_exists(rebase_path_fixup_msg()) ||
1979 !file_exists(rebase_path_squash_msg()))) {
1980 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1981 if (write_message(fixup_msg, strlen(fixup_msg),
1982 rebase_path_fixup_msg(), 0) < 0)
1983 return error(_("cannot write '%s'"),
1984 rebase_path_fixup_msg());
1985 } else {
1986 unlink(rebase_path_fixup_msg());
1988 } else {
1989 unlink(rebase_path_fixup_msg());
1992 return 0;
1995 static int update_squash_messages(struct repository *r,
1996 enum todo_command command,
1997 struct commit *commit,
1998 struct replay_opts *opts,
1999 unsigned flag)
2001 struct strbuf buf = STRBUF_INIT;
2002 int res = 0;
2003 const char *message, *body;
2004 const char *encoding = get_commit_output_encoding();
2006 if (opts->current_fixup_count > 0) {
2007 struct strbuf header = STRBUF_INIT;
2008 char *eol;
2010 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2011 return error(_("could not read '%s'"),
2012 rebase_path_squash_msg());
2014 eol = buf.buf[0] != comment_line_char ?
2015 buf.buf : strchrnul(buf.buf, '\n');
2017 strbuf_addf(&header, "%c ", comment_line_char);
2018 strbuf_addf(&header, _(combined_commit_msg_fmt),
2019 opts->current_fixup_count + 2);
2020 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2021 strbuf_release(&header);
2022 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2023 update_squash_message_for_fixup(&buf);
2024 } else {
2025 struct object_id head;
2026 struct commit *head_commit;
2027 const char *head_message, *body;
2029 if (repo_get_oid(r, "HEAD", &head))
2030 return error(_("need a HEAD to fixup"));
2031 if (!(head_commit = lookup_commit_reference(r, &head)))
2032 return error(_("could not read HEAD"));
2033 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2034 encoding)))
2035 return error(_("could not read HEAD's commit message"));
2037 find_commit_subject(head_message, &body);
2038 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2039 rebase_path_fixup_msg(), 0) < 0) {
2040 repo_unuse_commit_buffer(r, head_commit, head_message);
2041 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2043 strbuf_addf(&buf, "%c ", comment_line_char);
2044 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2045 strbuf_addf(&buf, "\n%c ", comment_line_char);
2046 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2047 _(skip_first_commit_msg_str) :
2048 _(first_commit_msg_str));
2049 strbuf_addstr(&buf, "\n\n");
2050 if (is_fixup_flag(command, flag))
2051 strbuf_add_commented_lines(&buf, body, strlen(body),
2052 comment_line_char);
2053 else
2054 strbuf_addstr(&buf, body);
2056 repo_unuse_commit_buffer(r, head_commit, head_message);
2059 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2060 return error(_("could not read commit message of %s"),
2061 oid_to_hex(&commit->object.oid));
2062 find_commit_subject(message, &body);
2064 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2065 res = append_squash_message(&buf, body, command, opts, flag);
2066 } else if (command == TODO_FIXUP) {
2067 strbuf_addf(&buf, "\n%c ", comment_line_char);
2068 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2069 ++opts->current_fixup_count + 1);
2070 strbuf_addstr(&buf, "\n\n");
2071 strbuf_add_commented_lines(&buf, body, strlen(body),
2072 comment_line_char);
2073 } else
2074 return error(_("unknown command: %d"), command);
2075 repo_unuse_commit_buffer(r, commit, message);
2077 if (!res)
2078 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2080 strbuf_release(&buf);
2082 if (!res) {
2083 strbuf_addf(&opts->current_fixups, "%s%s %s",
2084 opts->current_fixups.len ? "\n" : "",
2085 command_to_string(command),
2086 oid_to_hex(&commit->object.oid));
2087 res = write_message(opts->current_fixups.buf,
2088 opts->current_fixups.len,
2089 rebase_path_current_fixups(), 0);
2092 return res;
2095 static void flush_rewritten_pending(void)
2097 struct strbuf buf = STRBUF_INIT;
2098 struct object_id newoid;
2099 FILE *out;
2101 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2102 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2103 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2104 char *bol = buf.buf, *eol;
2106 while (*bol) {
2107 eol = strchrnul(bol, '\n');
2108 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2109 bol, oid_to_hex(&newoid));
2110 if (!*eol)
2111 break;
2112 bol = eol + 1;
2114 fclose(out);
2115 unlink(rebase_path_rewritten_pending());
2117 strbuf_release(&buf);
2120 static void record_in_rewritten(struct object_id *oid,
2121 enum todo_command next_command)
2123 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2125 if (!out)
2126 return;
2128 fprintf(out, "%s\n", oid_to_hex(oid));
2129 fclose(out);
2131 if (!is_fixup(next_command))
2132 flush_rewritten_pending();
2135 static int should_edit(struct replay_opts *opts) {
2136 if (opts->edit < 0)
2138 * Note that we only handle the case of non-conflicted
2139 * commits; continue_single_pick() handles the conflicted
2140 * commits itself instead of calling this function.
2142 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2143 return opts->edit;
2146 static void refer_to_commit(struct replay_opts *opts,
2147 struct strbuf *msgbuf, struct commit *commit)
2149 if (opts->commit_use_reference) {
2150 struct pretty_print_context ctx = {
2151 .abbrev = DEFAULT_ABBREV,
2152 .date_mode.type = DATE_SHORT,
2154 repo_format_commit_message(the_repository, commit,
2155 "%h (%s, %ad)", msgbuf, &ctx);
2156 } else {
2157 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2161 static int do_pick_commit(struct repository *r,
2162 struct todo_item *item,
2163 struct replay_opts *opts,
2164 int final_fixup, int *check_todo)
2166 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2167 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2168 struct object_id head;
2169 struct commit *base, *next, *parent;
2170 const char *base_label, *next_label;
2171 char *author = NULL;
2172 struct commit_message msg = { NULL, NULL, NULL, NULL };
2173 struct strbuf msgbuf = STRBUF_INIT;
2174 int res, unborn = 0, reword = 0, allow, drop_commit;
2175 enum todo_command command = item->command;
2176 struct commit *commit = item->commit;
2178 if (opts->no_commit) {
2180 * We do not intend to commit immediately. We just want to
2181 * merge the differences in, so let's compute the tree
2182 * that represents the "current" state for the merge machinery
2183 * to work on.
2185 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2186 return error(_("your index file is unmerged."));
2187 } else {
2188 unborn = repo_get_oid(r, "HEAD", &head);
2189 /* Do we want to generate a root commit? */
2190 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2191 oideq(&head, &opts->squash_onto)) {
2192 if (is_fixup(command))
2193 return error(_("cannot fixup root commit"));
2194 flags |= CREATE_ROOT_COMMIT;
2195 unborn = 1;
2196 } else if (unborn)
2197 oidcpy(&head, the_hash_algo->empty_tree);
2198 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2199 NULL, 0))
2200 return error_dirty_index(r, opts);
2202 discard_index(r->index);
2204 if (!commit->parents)
2205 parent = NULL;
2206 else if (commit->parents->next) {
2207 /* Reverting or cherry-picking a merge commit */
2208 int cnt;
2209 struct commit_list *p;
2211 if (!opts->mainline)
2212 return error(_("commit %s is a merge but no -m option was given."),
2213 oid_to_hex(&commit->object.oid));
2215 for (cnt = 1, p = commit->parents;
2216 cnt != opts->mainline && p;
2217 cnt++)
2218 p = p->next;
2219 if (cnt != opts->mainline || !p)
2220 return error(_("commit %s does not have parent %d"),
2221 oid_to_hex(&commit->object.oid), opts->mainline);
2222 parent = p->item;
2223 } else if (1 < opts->mainline)
2225 * Non-first parent explicitly specified as mainline for
2226 * non-merge commit
2228 return error(_("commit %s does not have parent %d"),
2229 oid_to_hex(&commit->object.oid), opts->mainline);
2230 else
2231 parent = commit->parents->item;
2233 if (get_message(commit, &msg) != 0)
2234 return error(_("cannot get commit message for %s"),
2235 oid_to_hex(&commit->object.oid));
2237 if (opts->allow_ff && !is_fixup(command) &&
2238 ((parent && oideq(&parent->object.oid, &head)) ||
2239 (!parent && unborn))) {
2240 if (is_rebase_i(opts))
2241 write_author_script(msg.message);
2242 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2243 opts);
2244 if (res || command != TODO_REWORD)
2245 goto leave;
2246 reword = 1;
2247 msg_file = NULL;
2248 goto fast_forward_edit;
2250 if (parent && repo_parse_commit(r, parent) < 0)
2251 /* TRANSLATORS: The first %s will be a "todo" command like
2252 "revert" or "pick", the second %s a SHA1. */
2253 return error(_("%s: cannot parse parent commit %s"),
2254 command_to_string(command),
2255 oid_to_hex(&parent->object.oid));
2258 * "commit" is an existing commit. We would want to apply
2259 * the difference it introduces since its first parent "prev"
2260 * on top of the current HEAD if we are cherry-pick. Or the
2261 * reverse of it if we are revert.
2264 if (command == TODO_REVERT) {
2265 const char *orig_subject;
2267 base = commit;
2268 base_label = msg.label;
2269 next = parent;
2270 next_label = msg.parent_label;
2271 if (opts->commit_use_reference) {
2272 strbuf_addstr(&msgbuf,
2273 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2274 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2276 * We don't touch pre-existing repeated reverts, because
2277 * theoretically these can be nested arbitrarily deeply,
2278 * thus requiring excessive complexity to deal with.
2280 !starts_with(orig_subject, "Revert \"")) {
2281 strbuf_addstr(&msgbuf, "Reapply \"");
2282 strbuf_addstr(&msgbuf, orig_subject);
2283 } else {
2284 strbuf_addstr(&msgbuf, "Revert \"");
2285 strbuf_addstr(&msgbuf, msg.subject);
2286 strbuf_addstr(&msgbuf, "\"");
2288 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2289 refer_to_commit(opts, &msgbuf, commit);
2291 if (commit->parents && commit->parents->next) {
2292 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2293 refer_to_commit(opts, &msgbuf, parent);
2295 strbuf_addstr(&msgbuf, ".\n");
2296 } else {
2297 const char *p;
2299 base = parent;
2300 base_label = msg.parent_label;
2301 next = commit;
2302 next_label = msg.label;
2304 /* Append the commit log message to msgbuf. */
2305 if (find_commit_subject(msg.message, &p))
2306 strbuf_addstr(&msgbuf, p);
2308 if (opts->record_origin) {
2309 strbuf_complete_line(&msgbuf);
2310 if (!has_conforming_footer(&msgbuf, NULL, 0))
2311 strbuf_addch(&msgbuf, '\n');
2312 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2313 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2314 strbuf_addstr(&msgbuf, ")\n");
2316 if (!is_fixup(command))
2317 author = get_author(msg.message);
2320 if (command == TODO_REWORD)
2321 reword = 1;
2322 else if (is_fixup(command)) {
2323 if (update_squash_messages(r, command, commit,
2324 opts, item->flags)) {
2325 res = -1;
2326 goto leave;
2328 flags |= AMEND_MSG;
2329 if (!final_fixup)
2330 msg_file = rebase_path_squash_msg();
2331 else if (file_exists(rebase_path_fixup_msg())) {
2332 flags |= VERBATIM_MSG;
2333 msg_file = rebase_path_fixup_msg();
2334 } else {
2335 const char *dest = git_path_squash_msg(r);
2336 unlink(dest);
2337 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2338 res = error(_("could not copy '%s' to '%s'"),
2339 rebase_path_squash_msg(), dest);
2340 goto leave;
2342 unlink(git_path_merge_msg(r));
2343 msg_file = dest;
2344 flags |= EDIT_MSG;
2348 if (opts->signoff && !is_fixup(command))
2349 append_signoff(&msgbuf, 0, 0);
2351 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2352 res = -1;
2353 else if (!opts->strategy ||
2354 !strcmp(opts->strategy, "recursive") ||
2355 !strcmp(opts->strategy, "ort") ||
2356 command == TODO_REVERT) {
2357 res = do_recursive_merge(r, base, next, base_label, next_label,
2358 &head, &msgbuf, opts);
2359 if (res < 0)
2360 goto leave;
2362 res |= write_message(msgbuf.buf, msgbuf.len,
2363 git_path_merge_msg(r), 0);
2364 } else {
2365 struct commit_list *common = NULL;
2366 struct commit_list *remotes = NULL;
2368 res = write_message(msgbuf.buf, msgbuf.len,
2369 git_path_merge_msg(r), 0);
2371 commit_list_insert(base, &common);
2372 commit_list_insert(next, &remotes);
2373 res |= try_merge_command(r, opts->strategy,
2374 opts->xopts.nr, opts->xopts.v,
2375 common, oid_to_hex(&head), remotes);
2376 free_commit_list(common);
2377 free_commit_list(remotes);
2381 * If the merge was clean or if it failed due to conflict, we write
2382 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2383 * However, if the merge did not even start, then we don't want to
2384 * write it at all.
2386 if ((command == TODO_PICK || command == TODO_REWORD ||
2387 command == TODO_EDIT) && !opts->no_commit &&
2388 (res == 0 || res == 1) &&
2389 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2390 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2391 res = -1;
2392 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2393 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2394 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2395 res = -1;
2397 if (res) {
2398 error(command == TODO_REVERT
2399 ? _("could not revert %s... %s")
2400 : _("could not apply %s... %s"),
2401 short_commit_name(r, commit), msg.subject);
2402 print_advice(r, res == 1, opts);
2403 repo_rerere(r, opts->allow_rerere_auto);
2404 goto leave;
2407 drop_commit = 0;
2408 allow = allow_empty(r, opts, commit);
2409 if (allow < 0) {
2410 res = allow;
2411 goto leave;
2412 } else if (allow == 1) {
2413 flags |= ALLOW_EMPTY;
2414 } else if (allow == 2) {
2415 drop_commit = 1;
2416 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2417 NULL, 0);
2418 unlink(git_path_merge_msg(r));
2419 unlink(git_path_auto_merge(r));
2420 fprintf(stderr,
2421 _("dropping %s %s -- patch contents already upstream\n"),
2422 oid_to_hex(&commit->object.oid), msg.subject);
2423 } /* else allow == 0 and there's nothing special to do */
2424 if (!opts->no_commit && !drop_commit) {
2425 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2426 res = do_commit(r, msg_file, author, opts, flags,
2427 commit? &commit->object.oid : NULL);
2428 else
2429 res = error(_("unable to parse commit author"));
2430 *check_todo = !!(flags & EDIT_MSG);
2431 if (!res && reword) {
2432 fast_forward_edit:
2433 res = run_git_commit(NULL, opts, EDIT_MSG |
2434 VERIFY_MSG | AMEND_MSG |
2435 (flags & ALLOW_EMPTY));
2436 *check_todo = 1;
2441 if (!res && final_fixup) {
2442 unlink(rebase_path_fixup_msg());
2443 unlink(rebase_path_squash_msg());
2444 unlink(rebase_path_current_fixups());
2445 strbuf_reset(&opts->current_fixups);
2446 opts->current_fixup_count = 0;
2449 leave:
2450 free_message(commit, &msg);
2451 free(author);
2452 strbuf_release(&msgbuf);
2453 update_abort_safety_file();
2455 return res;
2458 static int prepare_revs(struct replay_opts *opts)
2461 * picking (but not reverting) ranges (but not individual revisions)
2462 * should be done in reverse
2464 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2465 opts->revs->reverse ^= 1;
2467 if (prepare_revision_walk(opts->revs))
2468 return error(_("revision walk setup failed"));
2470 return 0;
2473 static int read_and_refresh_cache(struct repository *r,
2474 struct replay_opts *opts)
2476 struct lock_file index_lock = LOCK_INIT;
2477 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2478 if (repo_read_index(r) < 0) {
2479 rollback_lock_file(&index_lock);
2480 return error(_("git %s: failed to read the index"),
2481 action_name(opts));
2483 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2485 if (index_fd >= 0) {
2486 if (write_locked_index(r->index, &index_lock,
2487 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2488 return error(_("git %s: failed to refresh the index"),
2489 action_name(opts));
2494 * If we are resolving merges in any way other than "ort", then
2495 * expand the sparse index.
2497 if (opts->strategy && strcmp(opts->strategy, "ort"))
2498 ensure_full_index(r->index);
2499 return 0;
2502 void todo_list_release(struct todo_list *todo_list)
2504 strbuf_release(&todo_list->buf);
2505 FREE_AND_NULL(todo_list->items);
2506 todo_list->nr = todo_list->alloc = 0;
2509 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2511 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2512 return todo_list->items + todo_list->nr++;
2515 const char *todo_item_get_arg(struct todo_list *todo_list,
2516 struct todo_item *item)
2518 return todo_list->buf.buf + item->arg_offset;
2521 static int is_command(enum todo_command command, const char **bol)
2523 const char *str = todo_command_info[command].str;
2524 const char nick = todo_command_info[command].c;
2525 const char *p = *bol;
2527 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2528 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2529 (*bol = p);
2532 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2534 switch (command) {
2535 case TODO_LABEL:
2537 * '#' is not a valid label as the merge command uses it to
2538 * separate merge parents from the commit subject.
2540 if (!strcmp(arg, "#") ||
2541 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2542 return error(_("'%s' is not a valid label"), arg);
2543 break;
2545 case TODO_UPDATE_REF:
2546 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2547 return error(_("'%s' is not a valid refname"), arg);
2548 if (check_refname_format(arg, 0))
2549 return error(_("update-ref requires a fully qualified "
2550 "refname e.g. refs/heads/%s"), arg);
2551 break;
2553 default:
2554 BUG("unexpected todo_command");
2557 return 0;
2560 static int parse_insn_line(struct repository *r, struct todo_item *item,
2561 const char *buf, const char *bol, char *eol)
2563 struct object_id commit_oid;
2564 char *end_of_object_name;
2565 int i, saved, status, padding;
2567 item->flags = 0;
2569 /* left-trim */
2570 bol += strspn(bol, " \t");
2572 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2573 item->command = TODO_COMMENT;
2574 item->commit = NULL;
2575 item->arg_offset = bol - buf;
2576 item->arg_len = eol - bol;
2577 return 0;
2580 for (i = 0; i < TODO_COMMENT; i++)
2581 if (is_command(i, &bol)) {
2582 item->command = i;
2583 break;
2585 if (i >= TODO_COMMENT)
2586 return error(_("invalid command '%.*s'"),
2587 (int)strcspn(bol, " \t\r\n"), bol);
2589 /* Eat up extra spaces/ tabs before object name */
2590 padding = strspn(bol, " \t");
2591 bol += padding;
2593 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2594 if (bol != eol)
2595 return error(_("%s does not accept arguments: '%s'"),
2596 command_to_string(item->command), bol);
2597 item->commit = NULL;
2598 item->arg_offset = bol - buf;
2599 item->arg_len = eol - bol;
2600 return 0;
2603 if (!padding)
2604 return error(_("missing arguments for %s"),
2605 command_to_string(item->command));
2607 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2608 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2609 int ret = 0;
2611 item->commit = NULL;
2612 item->arg_offset = bol - buf;
2613 item->arg_len = (int)(eol - bol);
2614 if (item->command == TODO_LABEL ||
2615 item->command == TODO_UPDATE_REF) {
2616 saved = *eol;
2617 *eol = '\0';
2618 ret = check_label_or_ref_arg(item->command, bol);
2619 *eol = saved;
2621 return ret;
2624 if (item->command == TODO_FIXUP) {
2625 if (skip_prefix(bol, "-C", &bol)) {
2626 bol += strspn(bol, " \t");
2627 item->flags |= TODO_REPLACE_FIXUP_MSG;
2628 } else if (skip_prefix(bol, "-c", &bol)) {
2629 bol += strspn(bol, " \t");
2630 item->flags |= TODO_EDIT_FIXUP_MSG;
2634 if (item->command == TODO_MERGE) {
2635 if (skip_prefix(bol, "-C", &bol))
2636 bol += strspn(bol, " \t");
2637 else if (skip_prefix(bol, "-c", &bol)) {
2638 bol += strspn(bol, " \t");
2639 item->flags |= TODO_EDIT_MERGE_MSG;
2640 } else {
2641 item->flags |= TODO_EDIT_MERGE_MSG;
2642 item->commit = NULL;
2643 item->arg_offset = bol - buf;
2644 item->arg_len = (int)(eol - bol);
2645 return 0;
2649 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2650 saved = *end_of_object_name;
2651 *end_of_object_name = '\0';
2652 status = repo_get_oid(r, bol, &commit_oid);
2653 if (status < 0)
2654 error(_("could not parse '%s'"), bol); /* return later */
2655 *end_of_object_name = saved;
2657 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2658 item->arg_offset = bol - buf;
2659 item->arg_len = (int)(eol - bol);
2661 if (status < 0)
2662 return status;
2664 item->commit = lookup_commit_reference(r, &commit_oid);
2665 return item->commit ? 0 : -1;
2668 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2670 const char *todo_file, *bol;
2671 struct strbuf buf = STRBUF_INIT;
2672 int ret = 0;
2674 todo_file = git_path_todo_file();
2675 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2676 if (errno == ENOENT || errno == ENOTDIR)
2677 return -1;
2678 else
2679 return error_errno("unable to open '%s'", todo_file);
2681 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2682 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2683 *action = REPLAY_PICK;
2684 else if (is_command(TODO_REVERT, &bol) &&
2685 (*bol == ' ' || *bol == '\t'))
2686 *action = REPLAY_REVERT;
2687 else
2688 ret = -1;
2690 strbuf_release(&buf);
2692 return ret;
2695 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2696 struct todo_list *todo_list)
2698 struct todo_item *item;
2699 char *p = buf, *next_p;
2700 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2702 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2704 for (i = 1; *p; i++, p = next_p) {
2705 char *eol = strchrnul(p, '\n');
2707 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2709 if (p != eol && eol[-1] == '\r')
2710 eol--; /* strip Carriage Return */
2712 item = append_new_todo(todo_list);
2713 item->offset_in_buf = p - todo_list->buf.buf;
2714 if (parse_insn_line(r, item, buf, p, eol)) {
2715 res = error(_("invalid line %d: %.*s"),
2716 i, (int)(eol - p), p);
2717 item->command = TODO_COMMENT + 1;
2718 item->arg_offset = p - buf;
2719 item->arg_len = (int)(eol - p);
2720 item->commit = NULL;
2723 if (item->command != TODO_COMMENT)
2724 todo_list->total_nr++;
2726 if (fixup_okay)
2727 ; /* do nothing */
2728 else if (is_fixup(item->command))
2729 res = error(_("cannot '%s' without a previous commit"),
2730 command_to_string(item->command));
2731 else if (!is_noop(item->command))
2732 fixup_okay = 1;
2735 return res;
2738 static int count_commands(struct todo_list *todo_list)
2740 int count = 0, i;
2742 for (i = 0; i < todo_list->nr; i++)
2743 if (todo_list->items[i].command != TODO_COMMENT)
2744 count++;
2746 return count;
2749 static int get_item_line_offset(struct todo_list *todo_list, int index)
2751 return index < todo_list->nr ?
2752 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2755 static const char *get_item_line(struct todo_list *todo_list, int index)
2757 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2760 static int get_item_line_length(struct todo_list *todo_list, int index)
2762 return get_item_line_offset(todo_list, index + 1)
2763 - get_item_line_offset(todo_list, index);
2766 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2768 int fd;
2769 ssize_t len;
2771 fd = open(path, O_RDONLY);
2772 if (fd < 0)
2773 return error_errno(_("could not open '%s'"), path);
2774 len = strbuf_read(sb, fd, 0);
2775 close(fd);
2776 if (len < 0)
2777 return error(_("could not read '%s'."), path);
2778 return len;
2781 static int have_finished_the_last_pick(void)
2783 struct strbuf buf = STRBUF_INIT;
2784 const char *eol;
2785 const char *todo_path = git_path_todo_file();
2786 int ret = 0;
2788 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2789 if (errno == ENOENT) {
2790 return 0;
2791 } else {
2792 error_errno("unable to open '%s'", todo_path);
2793 return 0;
2796 /* If there is only one line then we are done */
2797 eol = strchr(buf.buf, '\n');
2798 if (!eol || !eol[1])
2799 ret = 1;
2801 strbuf_release(&buf);
2803 return ret;
2806 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2808 struct replay_opts opts = REPLAY_OPTS_INIT;
2809 int need_cleanup = 0;
2811 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2812 if (!refs_delete_ref(get_main_ref_store(r), "",
2813 "CHERRY_PICK_HEAD", NULL, 0) &&
2814 verbose)
2815 warning(_("cancelling a cherry picking in progress"));
2816 opts.action = REPLAY_PICK;
2817 need_cleanup = 1;
2820 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2821 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2822 NULL, 0) &&
2823 verbose)
2824 warning(_("cancelling a revert in progress"));
2825 opts.action = REPLAY_REVERT;
2826 need_cleanup = 1;
2829 unlink(git_path_auto_merge(r));
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 status = run_command(&cmd);
3652 /* force re-reading of the cache */
3653 discard_index(r->index);
3654 if (repo_read_index(r) < 0)
3655 return error(_("could not read index"));
3657 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3659 if (status) {
3660 warning(_("execution failed: %s\n%s"
3661 "You can fix the problem, and then run\n"
3662 "\n"
3663 " git rebase --continue\n"
3664 "\n"),
3665 command_line,
3666 dirty ? _("and made changes to the index and/or the "
3667 "working tree.\n") : "");
3668 if (status == 127)
3669 /* command not found */
3670 status = 1;
3671 } else if (dirty) {
3672 warning(_("execution succeeded: %s\nbut "
3673 "left changes to the index and/or the working tree.\n"
3674 "Commit or stash your changes, and then run\n"
3675 "\n"
3676 " git rebase --continue\n"
3677 "\n"), command_line);
3678 status = 1;
3681 return status;
3684 __attribute__((format (printf, 2, 3)))
3685 static int safe_append(const char *filename, const char *fmt, ...)
3687 va_list ap;
3688 struct lock_file lock = LOCK_INIT;
3689 int fd = hold_lock_file_for_update(&lock, filename,
3690 LOCK_REPORT_ON_ERROR);
3691 struct strbuf buf = STRBUF_INIT;
3693 if (fd < 0)
3694 return -1;
3696 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3697 error_errno(_("could not read '%s'"), filename);
3698 rollback_lock_file(&lock);
3699 return -1;
3701 strbuf_complete(&buf, '\n');
3702 va_start(ap, fmt);
3703 strbuf_vaddf(&buf, fmt, ap);
3704 va_end(ap);
3706 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3707 error_errno(_("could not write to '%s'"), filename);
3708 strbuf_release(&buf);
3709 rollback_lock_file(&lock);
3710 return -1;
3712 if (commit_lock_file(&lock) < 0) {
3713 strbuf_release(&buf);
3714 return error(_("failed to finalize '%s'"), filename);
3717 strbuf_release(&buf);
3718 return 0;
3721 static int do_label(struct repository *r, const char *name, int len)
3723 struct ref_store *refs = get_main_ref_store(r);
3724 struct ref_transaction *transaction;
3725 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3726 struct strbuf msg = STRBUF_INIT;
3727 int ret = 0;
3728 struct object_id head_oid;
3730 if (len == 1 && *name == '#')
3731 return error(_("illegal label name: '%.*s'"), len, name);
3733 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3734 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3736 transaction = ref_store_transaction_begin(refs, &err);
3737 if (!transaction) {
3738 error("%s", err.buf);
3739 ret = -1;
3740 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3741 error(_("could not read HEAD"));
3742 ret = -1;
3743 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3744 NULL, 0, msg.buf, &err) < 0 ||
3745 ref_transaction_commit(transaction, &err)) {
3746 error("%s", err.buf);
3747 ret = -1;
3749 ref_transaction_free(transaction);
3750 strbuf_release(&err);
3751 strbuf_release(&msg);
3753 if (!ret)
3754 ret = safe_append(rebase_path_refs_to_delete(),
3755 "%s\n", ref_name.buf);
3756 strbuf_release(&ref_name);
3758 return ret;
3761 static const char *sequencer_reflog_action(struct replay_opts *opts)
3763 if (!opts->reflog_action) {
3764 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3765 opts->reflog_action =
3766 xstrdup(opts->reflog_action ? opts->reflog_action
3767 : action_name(opts));
3770 return opts->reflog_action;
3773 __attribute__((format (printf, 3, 4)))
3774 static const char *reflog_message(struct replay_opts *opts,
3775 const char *sub_action, const char *fmt, ...)
3777 va_list ap;
3778 static struct strbuf buf = STRBUF_INIT;
3780 va_start(ap, fmt);
3781 strbuf_reset(&buf);
3782 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3783 if (sub_action)
3784 strbuf_addf(&buf, " (%s)", sub_action);
3785 if (fmt) {
3786 strbuf_addstr(&buf, ": ");
3787 strbuf_vaddf(&buf, fmt, ap);
3789 va_end(ap);
3791 return buf.buf;
3794 static struct commit *lookup_label(struct repository *r, const char *label,
3795 int len, struct strbuf *buf)
3797 struct commit *commit;
3798 struct object_id oid;
3800 strbuf_reset(buf);
3801 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3802 if (!read_ref(buf->buf, &oid)) {
3803 commit = lookup_commit_object(r, &oid);
3804 } else {
3805 /* fall back to non-rewritten ref or commit */
3806 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3807 commit = lookup_commit_reference_by_name(buf->buf);
3810 if (!commit)
3811 error(_("could not resolve '%s'"), buf->buf);
3813 return commit;
3816 static int do_reset(struct repository *r,
3817 const char *name, int len,
3818 struct replay_opts *opts)
3820 struct strbuf ref_name = STRBUF_INIT;
3821 struct object_id oid;
3822 struct lock_file lock = LOCK_INIT;
3823 struct tree_desc desc = { 0 };
3824 struct tree *tree;
3825 struct unpack_trees_options unpack_tree_opts = { 0 };
3826 int ret = 0;
3828 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3829 return -1;
3831 if (len == 10 && !strncmp("[new root]", name, len)) {
3832 if (!opts->have_squash_onto) {
3833 const char *hex;
3834 if (commit_tree("", 0, the_hash_algo->empty_tree,
3835 NULL, &opts->squash_onto,
3836 NULL, NULL))
3837 return error(_("writing fake root commit"));
3838 opts->have_squash_onto = 1;
3839 hex = oid_to_hex(&opts->squash_onto);
3840 if (write_message(hex, strlen(hex),
3841 rebase_path_squash_onto(), 0))
3842 return error(_("writing squash-onto"));
3844 oidcpy(&oid, &opts->squash_onto);
3845 } else {
3846 int i;
3847 struct commit *commit;
3849 /* Determine the length of the label */
3850 for (i = 0; i < len; i++)
3851 if (isspace(name[i]))
3852 break;
3853 len = i;
3855 commit = lookup_label(r, name, len, &ref_name);
3856 if (!commit) {
3857 ret = -1;
3858 goto cleanup;
3860 oid = commit->object.oid;
3863 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3864 unpack_tree_opts.head_idx = 1;
3865 unpack_tree_opts.src_index = r->index;
3866 unpack_tree_opts.dst_index = r->index;
3867 unpack_tree_opts.fn = oneway_merge;
3868 unpack_tree_opts.merge = 1;
3869 unpack_tree_opts.update = 1;
3870 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3871 unpack_tree_opts.skip_cache_tree_update = 1;
3872 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3874 if (repo_read_index_unmerged(r)) {
3875 ret = error_resolve_conflict(action_name(opts));
3876 goto cleanup;
3879 if (!fill_tree_descriptor(r, &desc, &oid)) {
3880 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3881 goto cleanup;
3884 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3885 ret = -1;
3886 goto cleanup;
3889 tree = parse_tree_indirect(&oid);
3890 prime_cache_tree(r, r->index, tree);
3892 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3893 ret = error(_("could not write index"));
3895 if (!ret)
3896 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3897 len, name), "HEAD", &oid,
3898 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3899 cleanup:
3900 free((void *)desc.buffer);
3901 if (ret < 0)
3902 rollback_lock_file(&lock);
3903 strbuf_release(&ref_name);
3904 clear_unpack_trees_porcelain(&unpack_tree_opts);
3905 return ret;
3908 static int do_merge(struct repository *r,
3909 struct commit *commit,
3910 const char *arg, int arg_len,
3911 int flags, int *check_todo, struct replay_opts *opts)
3913 int run_commit_flags = 0;
3914 struct strbuf ref_name = STRBUF_INIT;
3915 struct commit *head_commit, *merge_commit, *i;
3916 struct commit_list *bases, *j;
3917 struct commit_list *to_merge = NULL, **tail = &to_merge;
3918 const char *strategy = !opts->xopts.nr &&
3919 (!opts->strategy ||
3920 !strcmp(opts->strategy, "recursive") ||
3921 !strcmp(opts->strategy, "ort")) ?
3922 NULL : opts->strategy;
3923 struct merge_options o;
3924 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3925 static struct lock_file lock;
3926 const char *p;
3928 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3929 ret = -1;
3930 goto leave_merge;
3933 head_commit = lookup_commit_reference_by_name("HEAD");
3934 if (!head_commit) {
3935 ret = error(_("cannot merge without a current revision"));
3936 goto leave_merge;
3940 * For octopus merges, the arg starts with the list of revisions to be
3941 * merged. The list is optionally followed by '#' and the oneline.
3943 merge_arg_len = oneline_offset = arg_len;
3944 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3945 if (!*p)
3946 break;
3947 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3948 p += 1 + strspn(p + 1, " \t\n");
3949 oneline_offset = p - arg;
3950 break;
3952 k = strcspn(p, " \t\n");
3953 if (!k)
3954 continue;
3955 merge_commit = lookup_label(r, p, k, &ref_name);
3956 if (!merge_commit) {
3957 ret = error(_("unable to parse '%.*s'"), k, p);
3958 goto leave_merge;
3960 tail = &commit_list_insert(merge_commit, tail)->next;
3961 p += k;
3962 merge_arg_len = p - arg;
3965 if (!to_merge) {
3966 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3967 goto leave_merge;
3970 if (opts->have_squash_onto &&
3971 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3973 * When the user tells us to "merge" something into a
3974 * "[new root]", let's simply fast-forward to the merge head.
3976 rollback_lock_file(&lock);
3977 if (to_merge->next)
3978 ret = error(_("octopus merge cannot be executed on "
3979 "top of a [new root]"));
3980 else
3981 ret = fast_forward_to(r, &to_merge->item->object.oid,
3982 &head_commit->object.oid, 0,
3983 opts);
3984 goto leave_merge;
3988 * If HEAD is not identical to the first parent of the original merge
3989 * commit, we cannot fast-forward.
3991 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3992 oideq(&commit->parents->item->object.oid,
3993 &head_commit->object.oid);
3996 * If any merge head is different from the original one, we cannot
3997 * fast-forward.
3999 if (can_fast_forward) {
4000 struct commit_list *p = commit->parents->next;
4002 for (j = to_merge; j && p; j = j->next, p = p->next)
4003 if (!oideq(&j->item->object.oid,
4004 &p->item->object.oid)) {
4005 can_fast_forward = 0;
4006 break;
4009 * If the number of merge heads differs from the original merge
4010 * commit, we cannot fast-forward.
4012 if (j || p)
4013 can_fast_forward = 0;
4016 if (can_fast_forward) {
4017 rollback_lock_file(&lock);
4018 ret = fast_forward_to(r, &commit->object.oid,
4019 &head_commit->object.oid, 0, opts);
4020 if (flags & TODO_EDIT_MERGE_MSG)
4021 goto fast_forward_edit;
4023 goto leave_merge;
4026 if (commit) {
4027 const char *encoding = get_commit_output_encoding();
4028 const char *message = repo_logmsg_reencode(r, commit, NULL,
4029 encoding);
4030 const char *body;
4031 int len;
4033 if (!message) {
4034 ret = error(_("could not get commit message of '%s'"),
4035 oid_to_hex(&commit->object.oid));
4036 goto leave_merge;
4038 write_author_script(message);
4039 find_commit_subject(message, &body);
4040 len = strlen(body);
4041 ret = write_message(body, len, git_path_merge_msg(r), 0);
4042 repo_unuse_commit_buffer(r, commit, message);
4043 if (ret) {
4044 error_errno(_("could not write '%s'"),
4045 git_path_merge_msg(r));
4046 goto leave_merge;
4048 } else {
4049 struct strbuf buf = STRBUF_INIT;
4050 int len;
4052 strbuf_addf(&buf, "author %s", git_author_info(0));
4053 write_author_script(buf.buf);
4054 strbuf_reset(&buf);
4056 if (oneline_offset < arg_len) {
4057 p = arg + oneline_offset;
4058 len = arg_len - oneline_offset;
4059 } else {
4060 strbuf_addf(&buf, "Merge %s '%.*s'",
4061 to_merge->next ? "branches" : "branch",
4062 merge_arg_len, arg);
4063 p = buf.buf;
4064 len = buf.len;
4067 ret = write_message(p, len, git_path_merge_msg(r), 0);
4068 strbuf_release(&buf);
4069 if (ret) {
4070 error_errno(_("could not write '%s'"),
4071 git_path_merge_msg(r));
4072 goto leave_merge;
4076 if (strategy || to_merge->next) {
4077 /* Octopus merge */
4078 struct child_process cmd = CHILD_PROCESS_INIT;
4080 if (read_env_script(&cmd.env)) {
4081 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4083 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4084 goto leave_merge;
4087 if (opts->committer_date_is_author_date)
4088 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4089 opts->ignore_date ?
4090 "" :
4091 author_date_from_env(&cmd.env));
4092 if (opts->ignore_date)
4093 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4095 cmd.git_cmd = 1;
4096 strvec_push(&cmd.args, "merge");
4097 strvec_push(&cmd.args, "-s");
4098 if (!strategy)
4099 strvec_push(&cmd.args, "octopus");
4100 else {
4101 strvec_push(&cmd.args, strategy);
4102 for (k = 0; k < opts->xopts.nr; k++)
4103 strvec_pushf(&cmd.args,
4104 "-X%s", opts->xopts.v[k]);
4106 if (!(flags & TODO_EDIT_MERGE_MSG))
4107 strvec_push(&cmd.args, "--no-edit");
4108 else
4109 strvec_push(&cmd.args, "--edit");
4110 strvec_push(&cmd.args, "--no-ff");
4111 strvec_push(&cmd.args, "--no-log");
4112 strvec_push(&cmd.args, "--no-stat");
4113 strvec_push(&cmd.args, "-F");
4114 strvec_push(&cmd.args, git_path_merge_msg(r));
4115 if (opts->gpg_sign)
4116 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4117 else
4118 strvec_push(&cmd.args, "--no-gpg-sign");
4120 /* Add the tips to be merged */
4121 for (j = to_merge; j; j = j->next)
4122 strvec_push(&cmd.args,
4123 oid_to_hex(&j->item->object.oid));
4125 strbuf_release(&ref_name);
4126 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4127 NULL, 0);
4128 rollback_lock_file(&lock);
4130 ret = run_command(&cmd);
4132 /* force re-reading of the cache */
4133 if (!ret) {
4134 discard_index(r->index);
4135 if (repo_read_index(r) < 0)
4136 ret = error(_("could not read index"));
4138 goto leave_merge;
4141 merge_commit = to_merge->item;
4142 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4143 if (bases && oideq(&merge_commit->object.oid,
4144 &bases->item->object.oid)) {
4145 ret = 0;
4146 /* skip merging an ancestor of HEAD */
4147 goto leave_merge;
4150 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4151 git_path_merge_head(r), 0);
4152 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4154 bases = reverse_commit_list(bases);
4156 repo_read_index(r);
4157 init_merge_options(&o, r);
4158 o.branch1 = "HEAD";
4159 o.branch2 = ref_name.buf;
4160 o.buffer_output = 2;
4162 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4164 * TODO: Should use merge_incore_recursive() and
4165 * merge_switch_to_result(), skipping the call to
4166 * merge_switch_to_result() when we don't actually need to
4167 * update the index and working copy immediately.
4169 ret = merge_ort_recursive(&o,
4170 head_commit, merge_commit, bases,
4171 &i);
4172 } else {
4173 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4174 &i);
4176 if (ret <= 0)
4177 fputs(o.obuf.buf, stdout);
4178 strbuf_release(&o.obuf);
4179 if (ret < 0) {
4180 error(_("could not even attempt to merge '%.*s'"),
4181 merge_arg_len, arg);
4182 unlink(git_path_merge_msg(r));
4183 goto leave_merge;
4186 * The return value of merge_recursive() is 1 on clean, and 0 on
4187 * unclean merge.
4189 * Let's reverse that, so that do_merge() returns 0 upon success and
4190 * 1 upon failed merge (keeping the return value -1 for the cases where
4191 * we will want to reschedule the `merge` command).
4193 ret = !ret;
4195 if (r->index->cache_changed &&
4196 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4197 ret = error(_("merge: Unable to write new index file"));
4198 goto leave_merge;
4201 rollback_lock_file(&lock);
4202 if (ret)
4203 repo_rerere(r, opts->allow_rerere_auto);
4204 else
4206 * In case of problems, we now want to return a positive
4207 * value (a negative one would indicate that the `merge`
4208 * command needs to be rescheduled).
4210 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4211 run_commit_flags);
4213 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4214 fast_forward_edit:
4215 *check_todo = 1;
4216 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4217 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4221 leave_merge:
4222 strbuf_release(&ref_name);
4223 rollback_lock_file(&lock);
4224 free_commit_list(to_merge);
4225 return ret;
4228 static int write_update_refs_state(struct string_list *refs_to_oids)
4230 int result = 0;
4231 struct lock_file lock = LOCK_INIT;
4232 FILE *fp = NULL;
4233 struct string_list_item *item;
4234 char *path;
4236 path = rebase_path_update_refs(the_repository->gitdir);
4238 if (!refs_to_oids->nr) {
4239 if (unlink(path) && errno != ENOENT)
4240 result = error_errno(_("could not unlink: %s"), path);
4241 goto cleanup;
4244 if (safe_create_leading_directories(path)) {
4245 result = error(_("unable to create leading directories of %s"),
4246 path);
4247 goto cleanup;
4250 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4251 result = error(_("another 'rebase' process appears to be running; "
4252 "'%s.lock' already exists"),
4253 path);
4254 goto cleanup;
4257 fp = fdopen_lock_file(&lock, "w");
4258 if (!fp) {
4259 result = error_errno(_("could not open '%s' for writing"), path);
4260 rollback_lock_file(&lock);
4261 goto cleanup;
4264 for_each_string_list_item(item, refs_to_oids) {
4265 struct update_ref_record *rec = item->util;
4266 fprintf(fp, "%s\n%s\n%s\n", item->string,
4267 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4270 result = commit_lock_file(&lock);
4272 cleanup:
4273 free(path);
4274 return result;
4278 * Parse the update-refs file for the current rebase, then remove the
4279 * refs that do not appear in the todo_list (and have not had updated
4280 * values stored) and add refs that are in the todo_list but not
4281 * represented in the update-refs file.
4283 * If there are changes to the update-refs list, then write the new state
4284 * to disk.
4286 void todo_list_filter_update_refs(struct repository *r,
4287 struct todo_list *todo_list)
4289 int i;
4290 int updated = 0;
4291 struct string_list update_refs = STRING_LIST_INIT_DUP;
4293 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4296 * For each item in the update_refs list, if it has no updated
4297 * value and does not appear in the todo_list, then remove it
4298 * from the update_refs list.
4300 for (i = 0; i < update_refs.nr; i++) {
4301 int j;
4302 int found = 0;
4303 const char *ref = update_refs.items[i].string;
4304 size_t reflen = strlen(ref);
4305 struct update_ref_record *rec = update_refs.items[i].util;
4307 /* OID already stored as updated. */
4308 if (!is_null_oid(&rec->after))
4309 continue;
4311 for (j = 0; !found && j < todo_list->nr; j++) {
4312 struct todo_item *item = &todo_list->items[j];
4313 const char *arg = todo_list->buf.buf + item->arg_offset;
4315 if (item->command != TODO_UPDATE_REF)
4316 continue;
4318 if (item->arg_len != reflen ||
4319 strncmp(arg, ref, reflen))
4320 continue;
4322 found = 1;
4325 if (!found) {
4326 free(update_refs.items[i].string);
4327 free(update_refs.items[i].util);
4329 update_refs.nr--;
4330 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4332 updated = 1;
4333 i--;
4338 * For each todo_item, check if its ref is in the update_refs list.
4339 * If not, then add it as an un-updated ref.
4341 for (i = 0; i < todo_list->nr; i++) {
4342 struct todo_item *item = &todo_list->items[i];
4343 const char *arg = todo_list->buf.buf + item->arg_offset;
4344 int j, found = 0;
4346 if (item->command != TODO_UPDATE_REF)
4347 continue;
4349 for (j = 0; !found && j < update_refs.nr; j++) {
4350 const char *ref = update_refs.items[j].string;
4352 found = strlen(ref) == item->arg_len &&
4353 !strncmp(ref, arg, item->arg_len);
4356 if (!found) {
4357 struct string_list_item *inserted;
4358 struct strbuf argref = STRBUF_INIT;
4360 strbuf_add(&argref, arg, item->arg_len);
4361 inserted = string_list_insert(&update_refs, argref.buf);
4362 inserted->util = init_update_ref_record(argref.buf);
4363 strbuf_release(&argref);
4364 updated = 1;
4368 if (updated)
4369 write_update_refs_state(&update_refs);
4370 string_list_clear(&update_refs, 1);
4373 static int do_update_ref(struct repository *r, const char *refname)
4375 struct string_list_item *item;
4376 struct string_list list = STRING_LIST_INIT_DUP;
4378 if (sequencer_get_update_refs_state(r->gitdir, &list))
4379 return -1;
4381 for_each_string_list_item(item, &list) {
4382 if (!strcmp(item->string, refname)) {
4383 struct update_ref_record *rec = item->util;
4384 if (read_ref("HEAD", &rec->after))
4385 return -1;
4386 break;
4390 write_update_refs_state(&list);
4391 string_list_clear(&list, 1);
4392 return 0;
4395 static int do_update_refs(struct repository *r, int quiet)
4397 int res = 0;
4398 struct string_list_item *item;
4399 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4400 struct ref_store *refs = get_main_ref_store(r);
4401 struct strbuf update_msg = STRBUF_INIT;
4402 struct strbuf error_msg = STRBUF_INIT;
4404 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4405 return res;
4407 for_each_string_list_item(item, &refs_to_oids) {
4408 struct update_ref_record *rec = item->util;
4409 int loop_res;
4411 loop_res = refs_update_ref(refs, "rewritten during rebase",
4412 item->string,
4413 &rec->after, &rec->before,
4414 0, UPDATE_REFS_MSG_ON_ERR);
4415 res |= loop_res;
4417 if (quiet)
4418 continue;
4420 if (loop_res)
4421 strbuf_addf(&error_msg, "\t%s\n", item->string);
4422 else
4423 strbuf_addf(&update_msg, "\t%s\n", item->string);
4426 if (!quiet &&
4427 (update_msg.len || error_msg.len)) {
4428 fprintf(stderr,
4429 _("Updated the following refs with %s:\n%s"),
4430 "--update-refs",
4431 update_msg.buf);
4433 if (res)
4434 fprintf(stderr,
4435 _("Failed to update the following refs with %s:\n%s"),
4436 "--update-refs",
4437 error_msg.buf);
4440 string_list_clear(&refs_to_oids, 1);
4441 strbuf_release(&update_msg);
4442 strbuf_release(&error_msg);
4443 return res;
4446 static int is_final_fixup(struct todo_list *todo_list)
4448 int i = todo_list->current;
4450 if (!is_fixup(todo_list->items[i].command))
4451 return 0;
4453 while (++i < todo_list->nr)
4454 if (is_fixup(todo_list->items[i].command))
4455 return 0;
4456 else if (!is_noop(todo_list->items[i].command))
4457 break;
4458 return 1;
4461 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4463 int i;
4465 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4466 if (!is_noop(todo_list->items[i].command))
4467 return todo_list->items[i].command;
4469 return -1;
4472 void create_autostash(struct repository *r, const char *path)
4474 struct strbuf buf = STRBUF_INIT;
4475 struct lock_file lock_file = LOCK_INIT;
4476 int fd;
4478 fd = repo_hold_locked_index(r, &lock_file, 0);
4479 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4480 if (0 <= fd)
4481 repo_update_index_if_able(r, &lock_file);
4482 rollback_lock_file(&lock_file);
4484 if (has_unstaged_changes(r, 1) ||
4485 has_uncommitted_changes(r, 1)) {
4486 struct child_process stash = CHILD_PROCESS_INIT;
4487 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4488 struct object_id oid;
4490 strvec_pushl(&stash.args,
4491 "stash", "create", "autostash", NULL);
4492 stash.git_cmd = 1;
4493 stash.no_stdin = 1;
4494 strbuf_reset(&buf);
4495 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4496 die(_("Cannot autostash"));
4497 strbuf_trim_trailing_newline(&buf);
4498 if (repo_get_oid(r, buf.buf, &oid))
4499 die(_("Unexpected stash response: '%s'"),
4500 buf.buf);
4501 strbuf_reset(&buf);
4502 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4504 if (safe_create_leading_directories_const(path))
4505 die(_("Could not create directory for '%s'"),
4506 path);
4507 write_file(path, "%s", oid_to_hex(&oid));
4508 printf(_("Created autostash: %s\n"), buf.buf);
4509 if (reset_head(r, &ropts) < 0)
4510 die(_("could not reset --hard"));
4511 discard_index(r->index);
4512 if (repo_read_index(r) < 0)
4513 die(_("could not read index"));
4515 strbuf_release(&buf);
4518 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4520 struct child_process child = CHILD_PROCESS_INIT;
4521 int ret = 0;
4523 if (attempt_apply) {
4524 child.git_cmd = 1;
4525 child.no_stdout = 1;
4526 child.no_stderr = 1;
4527 strvec_push(&child.args, "stash");
4528 strvec_push(&child.args, "apply");
4529 strvec_push(&child.args, stash_oid);
4530 ret = run_command(&child);
4533 if (attempt_apply && !ret)
4534 fprintf(stderr, _("Applied autostash.\n"));
4535 else {
4536 struct child_process store = CHILD_PROCESS_INIT;
4538 store.git_cmd = 1;
4539 strvec_push(&store.args, "stash");
4540 strvec_push(&store.args, "store");
4541 strvec_push(&store.args, "-m");
4542 strvec_push(&store.args, "autostash");
4543 strvec_push(&store.args, "-q");
4544 strvec_push(&store.args, stash_oid);
4545 if (run_command(&store))
4546 ret = error(_("cannot store %s"), stash_oid);
4547 else
4548 fprintf(stderr,
4549 _("%s\n"
4550 "Your changes are safe in the stash.\n"
4551 "You can run \"git stash pop\" or"
4552 " \"git stash drop\" at any time.\n"),
4553 attempt_apply ?
4554 _("Applying autostash resulted in conflicts.") :
4555 _("Autostash exists; creating a new stash entry."));
4558 return ret;
4561 static int apply_save_autostash(const char *path, int attempt_apply)
4563 struct strbuf stash_oid = STRBUF_INIT;
4564 int ret = 0;
4566 if (!read_oneliner(&stash_oid, path,
4567 READ_ONELINER_SKIP_IF_EMPTY)) {
4568 strbuf_release(&stash_oid);
4569 return 0;
4571 strbuf_trim(&stash_oid);
4573 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4575 unlink(path);
4576 strbuf_release(&stash_oid);
4577 return ret;
4580 int save_autostash(const char *path)
4582 return apply_save_autostash(path, 0);
4585 int apply_autostash(const char *path)
4587 return apply_save_autostash(path, 1);
4590 int apply_autostash_oid(const char *stash_oid)
4592 return apply_save_autostash_oid(stash_oid, 1);
4595 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4596 const char *onto_name, const struct object_id *onto,
4597 const struct object_id *orig_head)
4599 struct reset_head_opts ropts = {
4600 .oid = onto,
4601 .orig_head = orig_head,
4602 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4603 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4604 .head_msg = reflog_message(opts, "start", "checkout %s",
4605 onto_name),
4606 .default_reflog_action = sequencer_reflog_action(opts)
4608 if (reset_head(r, &ropts)) {
4609 apply_autostash(rebase_path_autostash());
4610 sequencer_remove_state(opts);
4611 return error(_("could not detach HEAD"));
4614 return 0;
4617 static int stopped_at_head(struct repository *r)
4619 struct object_id head;
4620 struct commit *commit;
4621 struct commit_message message;
4623 if (repo_get_oid(r, "HEAD", &head) ||
4624 !(commit = lookup_commit(r, &head)) ||
4625 repo_parse_commit(r, commit) || get_message(commit, &message))
4626 fprintf(stderr, _("Stopped at HEAD\n"));
4627 else {
4628 fprintf(stderr, _("Stopped at %s\n"), message.label);
4629 free_message(commit, &message);
4631 return 0;
4635 static int reread_todo_if_changed(struct repository *r,
4636 struct todo_list *todo_list,
4637 struct replay_opts *opts)
4639 int offset;
4640 struct strbuf buf = STRBUF_INIT;
4642 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4643 return -1;
4644 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4645 if (buf.len != todo_list->buf.len - offset ||
4646 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4647 /* Reread the todo file if it has changed. */
4648 todo_list_release(todo_list);
4649 if (read_populate_todo(r, todo_list, opts))
4650 return -1; /* message was printed */
4651 /* `current` will be incremented on return */
4652 todo_list->current = -1;
4654 strbuf_release(&buf);
4656 return 0;
4659 static const char rescheduled_advice[] =
4660 N_("Could not execute the todo command\n"
4661 "\n"
4662 " %.*s"
4663 "\n"
4664 "It has been rescheduled; To edit the command before continuing, please\n"
4665 "edit the todo list first:\n"
4666 "\n"
4667 " git rebase --edit-todo\n"
4668 " git rebase --continue\n");
4670 static int pick_one_commit(struct repository *r,
4671 struct todo_list *todo_list,
4672 struct replay_opts *opts,
4673 int *check_todo, int* reschedule)
4675 int res;
4676 struct todo_item *item = todo_list->items + todo_list->current;
4677 const char *arg = todo_item_get_arg(todo_list, item);
4678 if (is_rebase_i(opts))
4679 opts->reflog_message = reflog_message(
4680 opts, command_to_string(item->command), NULL);
4682 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4683 check_todo);
4684 if (is_rebase_i(opts) && res < 0) {
4685 /* Reschedule */
4686 *reschedule = 1;
4687 return -1;
4689 if (item->command == TODO_EDIT) {
4690 struct commit *commit = item->commit;
4691 if (!res) {
4692 if (!opts->verbose)
4693 term_clear_line();
4694 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4695 short_commit_name(r, commit), item->arg_len, arg);
4697 return error_with_patch(r, commit,
4698 arg, item->arg_len, opts, res, !res);
4700 if (is_rebase_i(opts) && !res)
4701 record_in_rewritten(&item->commit->object.oid,
4702 peek_command(todo_list, 1));
4703 if (res && is_fixup(item->command)) {
4704 if (res == 1)
4705 intend_to_amend();
4706 return error_failed_squash(r, item->commit, opts,
4707 item->arg_len, arg);
4708 } else if (res && is_rebase_i(opts) && item->commit) {
4709 int to_amend = 0;
4710 struct object_id oid;
4713 * If we are rewording and have either
4714 * fast-forwarded already, or are about to
4715 * create a new root commit, we want to amend,
4716 * otherwise we do not.
4718 if (item->command == TODO_REWORD &&
4719 !repo_get_oid(r, "HEAD", &oid) &&
4720 (oideq(&item->commit->object.oid, &oid) ||
4721 (opts->have_squash_onto &&
4722 oideq(&opts->squash_onto, &oid))))
4723 to_amend = 1;
4725 return res | error_with_patch(r, item->commit,
4726 arg, item->arg_len, opts,
4727 res, to_amend);
4729 return res;
4732 static int pick_commits(struct repository *r,
4733 struct todo_list *todo_list,
4734 struct replay_opts *opts)
4736 int res = 0, reschedule = 0;
4738 opts->reflog_message = sequencer_reflog_action(opts);
4739 if (opts->allow_ff)
4740 assert(!(opts->signoff || opts->no_commit ||
4741 opts->record_origin || should_edit(opts) ||
4742 opts->committer_date_is_author_date ||
4743 opts->ignore_date));
4744 if (read_and_refresh_cache(r, opts))
4745 return -1;
4747 unlink(rebase_path_message());
4748 unlink(rebase_path_stopped_sha());
4749 unlink(rebase_path_amend());
4750 unlink(rebase_path_patch());
4752 while (todo_list->current < todo_list->nr) {
4753 struct todo_item *item = todo_list->items + todo_list->current;
4754 const char *arg = todo_item_get_arg(todo_list, item);
4755 int check_todo = 0;
4757 if (save_todo(todo_list, opts, reschedule))
4758 return -1;
4759 if (is_rebase_i(opts)) {
4760 if (item->command != TODO_COMMENT) {
4761 FILE *f = fopen(rebase_path_msgnum(), "w");
4763 todo_list->done_nr++;
4765 if (f) {
4766 fprintf(f, "%d\n", todo_list->done_nr);
4767 fclose(f);
4769 if (!opts->quiet)
4770 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4771 todo_list->done_nr,
4772 todo_list->total_nr,
4773 opts->verbose ? "\n" : "\r");
4775 unlink(rebase_path_author_script());
4776 unlink(git_path_merge_head(r));
4777 unlink(git_path_auto_merge(r));
4778 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4780 if (item->command == TODO_BREAK) {
4781 if (!opts->verbose)
4782 term_clear_line();
4783 return stopped_at_head(r);
4786 if (item->command <= TODO_SQUASH) {
4787 res = pick_one_commit(r, todo_list, opts, &check_todo,
4788 &reschedule);
4789 if (!res && item->command == TODO_EDIT)
4790 return 0;
4791 } else if (item->command == TODO_EXEC) {
4792 char *end_of_arg = (char *)(arg + item->arg_len);
4793 int saved = *end_of_arg;
4795 if (!opts->verbose)
4796 term_clear_line();
4797 *end_of_arg = '\0';
4798 res = do_exec(r, arg);
4799 *end_of_arg = saved;
4801 if (res) {
4802 if (opts->reschedule_failed_exec)
4803 reschedule = 1;
4805 check_todo = 1;
4806 } else if (item->command == TODO_LABEL) {
4807 if ((res = do_label(r, arg, item->arg_len)))
4808 reschedule = 1;
4809 } else if (item->command == TODO_RESET) {
4810 if ((res = do_reset(r, arg, item->arg_len, opts)))
4811 reschedule = 1;
4812 } else if (item->command == TODO_MERGE) {
4813 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4814 item->flags, &check_todo, opts)) < 0)
4815 reschedule = 1;
4816 else if (item->commit)
4817 record_in_rewritten(&item->commit->object.oid,
4818 peek_command(todo_list, 1));
4819 if (res > 0)
4820 /* failed with merge conflicts */
4821 return error_with_patch(r, item->commit,
4822 arg, item->arg_len,
4823 opts, res, 0);
4824 } else if (item->command == TODO_UPDATE_REF) {
4825 struct strbuf ref = STRBUF_INIT;
4826 strbuf_add(&ref, arg, item->arg_len);
4827 if ((res = do_update_ref(r, ref.buf)))
4828 reschedule = 1;
4829 strbuf_release(&ref);
4830 } else if (!is_noop(item->command))
4831 return error(_("unknown command %d"), item->command);
4833 if (reschedule) {
4834 advise(_(rescheduled_advice),
4835 get_item_line_length(todo_list,
4836 todo_list->current),
4837 get_item_line(todo_list, todo_list->current));
4838 if (save_todo(todo_list, opts, reschedule))
4839 return -1;
4840 if (item->commit)
4841 write_rebase_head(&item->commit->object.oid);
4842 } else if (is_rebase_i(opts) && check_todo && !res &&
4843 reread_todo_if_changed(r, todo_list, opts)) {
4844 return -1;
4847 if (res)
4848 return res;
4850 todo_list->current++;
4853 if (is_rebase_i(opts)) {
4854 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4855 struct stat st;
4857 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4858 starts_with(head_ref.buf, "refs/")) {
4859 const char *msg;
4860 struct object_id head, orig;
4861 int res;
4863 if (repo_get_oid(r, "HEAD", &head)) {
4864 res = error(_("cannot read HEAD"));
4865 cleanup_head_ref:
4866 strbuf_release(&head_ref);
4867 strbuf_release(&buf);
4868 return res;
4870 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4871 get_oid_hex(buf.buf, &orig)) {
4872 res = error(_("could not read orig-head"));
4873 goto cleanup_head_ref;
4875 strbuf_reset(&buf);
4876 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4877 res = error(_("could not read 'onto'"));
4878 goto cleanup_head_ref;
4880 msg = reflog_message(opts, "finish", "%s onto %s",
4881 head_ref.buf, buf.buf);
4882 if (update_ref(msg, head_ref.buf, &head, &orig,
4883 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4884 res = error(_("could not update %s"),
4885 head_ref.buf);
4886 goto cleanup_head_ref;
4888 msg = reflog_message(opts, "finish", "returning to %s",
4889 head_ref.buf);
4890 if (create_symref("HEAD", head_ref.buf, msg)) {
4891 res = error(_("could not update HEAD to %s"),
4892 head_ref.buf);
4893 goto cleanup_head_ref;
4895 strbuf_reset(&buf);
4898 if (opts->verbose) {
4899 struct rev_info log_tree_opt;
4900 struct object_id orig, head;
4902 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4903 repo_init_revisions(r, &log_tree_opt, NULL);
4904 log_tree_opt.diff = 1;
4905 log_tree_opt.diffopt.output_format =
4906 DIFF_FORMAT_DIFFSTAT;
4907 log_tree_opt.disable_stdin = 1;
4909 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4910 !repo_get_oid(r, buf.buf, &orig) &&
4911 !repo_get_oid(r, "HEAD", &head)) {
4912 diff_tree_oid(&orig, &head, "",
4913 &log_tree_opt.diffopt);
4914 log_tree_diff_flush(&log_tree_opt);
4916 release_revisions(&log_tree_opt);
4918 flush_rewritten_pending();
4919 if (!stat(rebase_path_rewritten_list(), &st) &&
4920 st.st_size > 0) {
4921 struct child_process child = CHILD_PROCESS_INIT;
4922 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4924 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4925 child.git_cmd = 1;
4926 strvec_push(&child.args, "notes");
4927 strvec_push(&child.args, "copy");
4928 strvec_push(&child.args, "--for-rewrite=rebase");
4929 /* we don't care if this copying failed */
4930 run_command(&child);
4932 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4933 strvec_push(&hook_opt.args, "rebase");
4934 run_hooks_opt("post-rewrite", &hook_opt);
4936 apply_autostash(rebase_path_autostash());
4938 if (!opts->quiet) {
4939 if (!opts->verbose)
4940 term_clear_line();
4941 fprintf(stderr,
4942 _("Successfully rebased and updated %s.\n"),
4943 head_ref.buf);
4946 strbuf_release(&buf);
4947 strbuf_release(&head_ref);
4949 if (do_update_refs(r, opts->quiet))
4950 return -1;
4954 * Sequence of picks finished successfully; cleanup by
4955 * removing the .git/sequencer directory
4957 return sequencer_remove_state(opts);
4960 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4962 struct child_process cmd = CHILD_PROCESS_INIT;
4964 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4965 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4966 return error(_("no cherry-pick or revert in progress"));
4968 cmd.git_cmd = 1;
4969 strvec_push(&cmd.args, "commit");
4972 * continue_single_pick() handles the case of recovering from a
4973 * conflict. should_edit() doesn't handle that case; for a conflict,
4974 * we want to edit if the user asked for it, or if they didn't specify
4975 * and stdin is a tty.
4977 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4979 * Include --cleanup=strip as well because we don't want the
4980 * "# Conflicts:" messages.
4982 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4984 return run_command(&cmd);
4987 static int commit_staged_changes(struct repository *r,
4988 struct replay_opts *opts,
4989 struct todo_list *todo_list)
4991 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4992 unsigned int final_fixup = 0, is_clean;
4994 if (has_unstaged_changes(r, 1))
4995 return error(_("cannot rebase: You have unstaged changes."));
4997 is_clean = !has_uncommitted_changes(r, 0);
4999 if (!is_clean && !file_exists(rebase_path_message())) {
5000 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5002 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5004 if (file_exists(rebase_path_amend())) {
5005 struct strbuf rev = STRBUF_INIT;
5006 struct object_id head, to_amend;
5008 if (repo_get_oid(r, "HEAD", &head))
5009 return error(_("cannot amend non-existing commit"));
5010 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5011 return error(_("invalid file: '%s'"), rebase_path_amend());
5012 if (get_oid_hex(rev.buf, &to_amend))
5013 return error(_("invalid contents: '%s'"),
5014 rebase_path_amend());
5015 if (!is_clean && !oideq(&head, &to_amend))
5016 return error(_("\nYou have uncommitted changes in your "
5017 "working tree. Please, commit them\n"
5018 "first and then run 'git rebase "
5019 "--continue' again."));
5021 * When skipping a failed fixup/squash, we need to edit the
5022 * commit message, the current fixup list and count, and if it
5023 * was the last fixup/squash in the chain, we need to clean up
5024 * the commit message and if there was a squash, let the user
5025 * edit it.
5027 if (!is_clean || !opts->current_fixup_count)
5028 ; /* this is not the final fixup */
5029 else if (!oideq(&head, &to_amend) ||
5030 !file_exists(rebase_path_stopped_sha())) {
5031 /* was a final fixup or squash done manually? */
5032 if (!is_fixup(peek_command(todo_list, 0))) {
5033 unlink(rebase_path_fixup_msg());
5034 unlink(rebase_path_squash_msg());
5035 unlink(rebase_path_current_fixups());
5036 strbuf_reset(&opts->current_fixups);
5037 opts->current_fixup_count = 0;
5039 } else {
5040 /* we are in a fixup/squash chain */
5041 const char *p = opts->current_fixups.buf;
5042 int len = opts->current_fixups.len;
5044 opts->current_fixup_count--;
5045 if (!len)
5046 BUG("Incorrect current_fixups:\n%s", p);
5047 while (len && p[len - 1] != '\n')
5048 len--;
5049 strbuf_setlen(&opts->current_fixups, len);
5050 if (write_message(p, len, rebase_path_current_fixups(),
5051 0) < 0)
5052 return error(_("could not write file: '%s'"),
5053 rebase_path_current_fixups());
5056 * If a fixup/squash in a fixup/squash chain failed, the
5057 * commit message is already correct, no need to commit
5058 * it again.
5060 * Only if it is the final command in the fixup/squash
5061 * chain, and only if the chain is longer than a single
5062 * fixup/squash command (which was just skipped), do we
5063 * actually need to re-commit with a cleaned up commit
5064 * message.
5066 if (opts->current_fixup_count > 0 &&
5067 !is_fixup(peek_command(todo_list, 0))) {
5068 final_fixup = 1;
5070 * If there was not a single "squash" in the
5071 * chain, we only need to clean up the commit
5072 * message, no need to bother the user with
5073 * opening the commit message in the editor.
5075 if (!starts_with(p, "squash ") &&
5076 !strstr(p, "\nsquash "))
5077 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5078 } else if (is_fixup(peek_command(todo_list, 0))) {
5080 * We need to update the squash message to skip
5081 * the latest commit message.
5083 int res = 0;
5084 struct commit *commit;
5085 const char *msg;
5086 const char *path = rebase_path_squash_msg();
5087 const char *encoding = get_commit_output_encoding();
5089 if (parse_head(r, &commit))
5090 return error(_("could not parse HEAD"));
5092 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5093 if (!p) {
5094 res = error(_("could not parse commit %s"),
5095 oid_to_hex(&commit->object.oid));
5096 goto unuse_commit_buffer;
5098 find_commit_subject(p, &msg);
5099 if (write_message(msg, strlen(msg), path, 0)) {
5100 res = error(_("could not write file: "
5101 "'%s'"), path);
5102 goto unuse_commit_buffer;
5104 unuse_commit_buffer:
5105 repo_unuse_commit_buffer(r, commit, p);
5106 if (res)
5107 return res;
5111 strbuf_release(&rev);
5112 flags |= AMEND_MSG;
5115 if (is_clean) {
5116 if (refs_ref_exists(get_main_ref_store(r),
5117 "CHERRY_PICK_HEAD") &&
5118 refs_delete_ref(get_main_ref_store(r), "",
5119 "CHERRY_PICK_HEAD", NULL, 0))
5120 return error(_("could not remove CHERRY_PICK_HEAD"));
5121 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5122 return error_errno(_("could not remove '%s'"),
5123 git_path_merge_msg(r));
5124 if (!final_fixup)
5125 return 0;
5128 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5129 opts, flags))
5130 return error(_("could not commit staged changes."));
5131 unlink(rebase_path_amend());
5132 unlink(git_path_merge_head(r));
5133 unlink(git_path_auto_merge(r));
5134 if (final_fixup) {
5135 unlink(rebase_path_fixup_msg());
5136 unlink(rebase_path_squash_msg());
5138 if (opts->current_fixup_count > 0) {
5140 * Whether final fixup or not, we just cleaned up the commit
5141 * message...
5143 unlink(rebase_path_current_fixups());
5144 strbuf_reset(&opts->current_fixups);
5145 opts->current_fixup_count = 0;
5147 return 0;
5150 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5152 struct todo_list todo_list = TODO_LIST_INIT;
5153 int res;
5155 if (read_and_refresh_cache(r, opts))
5156 return -1;
5158 if (read_populate_opts(opts))
5159 return -1;
5160 if (is_rebase_i(opts)) {
5161 if ((res = read_populate_todo(r, &todo_list, opts)))
5162 goto release_todo_list;
5164 if (file_exists(rebase_path_dropped())) {
5165 if ((res = todo_list_check_against_backup(r, &todo_list)))
5166 goto release_todo_list;
5168 unlink(rebase_path_dropped());
5171 opts->reflog_message = reflog_message(opts, "continue", NULL);
5172 if (commit_staged_changes(r, opts, &todo_list)) {
5173 res = -1;
5174 goto release_todo_list;
5176 } else if (!file_exists(get_todo_path(opts)))
5177 return continue_single_pick(r, opts);
5178 else if ((res = read_populate_todo(r, &todo_list, opts)))
5179 goto release_todo_list;
5181 if (!is_rebase_i(opts)) {
5182 /* Verify that the conflict has been resolved */
5183 if (refs_ref_exists(get_main_ref_store(r),
5184 "CHERRY_PICK_HEAD") ||
5185 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5186 res = continue_single_pick(r, opts);
5187 if (res)
5188 goto release_todo_list;
5190 if (index_differs_from(r, "HEAD", NULL, 0)) {
5191 res = error_dirty_index(r, opts);
5192 goto release_todo_list;
5194 todo_list.current++;
5195 } else if (file_exists(rebase_path_stopped_sha())) {
5196 struct strbuf buf = STRBUF_INIT;
5197 struct object_id oid;
5199 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5200 READ_ONELINER_SKIP_IF_EMPTY) &&
5201 !get_oid_hex(buf.buf, &oid))
5202 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5203 strbuf_release(&buf);
5206 res = pick_commits(r, &todo_list, opts);
5207 release_todo_list:
5208 todo_list_release(&todo_list);
5209 return res;
5212 static int single_pick(struct repository *r,
5213 struct commit *cmit,
5214 struct replay_opts *opts)
5216 int check_todo;
5217 struct todo_item item;
5219 item.command = opts->action == REPLAY_PICK ?
5220 TODO_PICK : TODO_REVERT;
5221 item.commit = cmit;
5223 opts->reflog_message = sequencer_reflog_action(opts);
5224 return do_pick_commit(r, &item, opts, 0, &check_todo);
5227 int sequencer_pick_revisions(struct repository *r,
5228 struct replay_opts *opts)
5230 struct todo_list todo_list = TODO_LIST_INIT;
5231 struct object_id oid;
5232 int i, res;
5234 assert(opts->revs);
5235 if (read_and_refresh_cache(r, opts))
5236 return -1;
5238 for (i = 0; i < opts->revs->pending.nr; i++) {
5239 struct object_id oid;
5240 const char *name = opts->revs->pending.objects[i].name;
5242 /* This happens when using --stdin. */
5243 if (!strlen(name))
5244 continue;
5246 if (!repo_get_oid(r, name, &oid)) {
5247 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5248 enum object_type type = oid_object_info(r,
5249 &oid,
5250 NULL);
5251 return error(_("%s: can't cherry-pick a %s"),
5252 name, type_name(type));
5254 } else
5255 return error(_("%s: bad revision"), name);
5259 * If we were called as "git cherry-pick <commit>", just
5260 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5261 * REVERT_HEAD, and don't touch the sequencer state.
5262 * This means it is possible to cherry-pick in the middle
5263 * of a cherry-pick sequence.
5265 if (opts->revs->cmdline.nr == 1 &&
5266 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5267 opts->revs->no_walk &&
5268 !opts->revs->cmdline.rev->flags) {
5269 struct commit *cmit;
5270 if (prepare_revision_walk(opts->revs))
5271 return error(_("revision walk setup failed"));
5272 cmit = get_revision(opts->revs);
5273 if (!cmit)
5274 return error(_("empty commit set passed"));
5275 if (get_revision(opts->revs))
5276 BUG("unexpected extra commit from walk");
5277 return single_pick(r, cmit, opts);
5281 * Start a new cherry-pick/ revert sequence; but
5282 * first, make sure that an existing one isn't in
5283 * progress
5286 if (walk_revs_populate_todo(&todo_list, opts) ||
5287 create_seq_dir(r) < 0)
5288 return -1;
5289 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5290 return error(_("can't revert as initial commit"));
5291 if (save_head(oid_to_hex(&oid)))
5292 return -1;
5293 if (save_opts(opts))
5294 return -1;
5295 update_abort_safety_file();
5296 res = pick_commits(r, &todo_list, opts);
5297 todo_list_release(&todo_list);
5298 return res;
5301 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5303 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5304 struct strbuf sob = STRBUF_INIT;
5305 int has_footer;
5307 strbuf_addstr(&sob, sign_off_header);
5308 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5309 strbuf_addch(&sob, '\n');
5311 if (!ignore_footer)
5312 strbuf_complete_line(msgbuf);
5315 * If the whole message buffer is equal to the sob, pretend that we
5316 * found a conforming footer with a matching sob
5318 if (msgbuf->len - ignore_footer == sob.len &&
5319 !strncmp(msgbuf->buf, sob.buf, sob.len))
5320 has_footer = 3;
5321 else
5322 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5324 if (!has_footer) {
5325 const char *append_newlines = NULL;
5326 size_t len = msgbuf->len - ignore_footer;
5328 if (!len) {
5330 * The buffer is completely empty. Leave foom for
5331 * the title and body to be filled in by the user.
5333 append_newlines = "\n\n";
5334 } else if (len == 1) {
5336 * Buffer contains a single newline. Add another
5337 * so that we leave room for the title and body.
5339 append_newlines = "\n";
5340 } else if (msgbuf->buf[len - 2] != '\n') {
5342 * Buffer ends with a single newline. Add another
5343 * so that there is an empty line between the message
5344 * body and the sob.
5346 append_newlines = "\n";
5347 } /* else, the buffer already ends with two newlines. */
5349 if (append_newlines)
5350 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5351 append_newlines, strlen(append_newlines));
5354 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5355 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5356 sob.buf, sob.len);
5358 strbuf_release(&sob);
5361 struct labels_entry {
5362 struct hashmap_entry entry;
5363 char label[FLEX_ARRAY];
5366 static int labels_cmp(const void *fndata UNUSED,
5367 const struct hashmap_entry *eptr,
5368 const struct hashmap_entry *entry_or_key, const void *key)
5370 const struct labels_entry *a, *b;
5372 a = container_of(eptr, const struct labels_entry, entry);
5373 b = container_of(entry_or_key, const struct labels_entry, entry);
5375 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5378 struct string_entry {
5379 struct oidmap_entry entry;
5380 char string[FLEX_ARRAY];
5383 struct label_state {
5384 struct oidmap commit2label;
5385 struct hashmap labels;
5386 struct strbuf buf;
5387 int max_label_length;
5390 static const char *label_oid(struct object_id *oid, const char *label,
5391 struct label_state *state)
5393 struct labels_entry *labels_entry;
5394 struct string_entry *string_entry;
5395 struct object_id dummy;
5396 int i;
5398 string_entry = oidmap_get(&state->commit2label, oid);
5399 if (string_entry)
5400 return string_entry->string;
5403 * For "uninteresting" commits, i.e. commits that are not to be
5404 * rebased, and which can therefore not be labeled, we use a unique
5405 * abbreviation of the commit name. This is slightly more complicated
5406 * than calling repo_find_unique_abbrev() because we also need to make
5407 * sure that the abbreviation does not conflict with any other
5408 * label.
5410 * We disallow "interesting" commits to be labeled by a string that
5411 * is a valid full-length hash, to ensure that we always can find an
5412 * abbreviation for any uninteresting commit's names that does not
5413 * clash with any other label.
5415 strbuf_reset(&state->buf);
5416 if (!label) {
5417 char *p;
5419 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5420 label = p = state->buf.buf;
5422 repo_find_unique_abbrev_r(the_repository, p, oid,
5423 default_abbrev);
5426 * We may need to extend the abbreviated hash so that there is
5427 * no conflicting label.
5429 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5430 size_t i = strlen(p) + 1;
5432 oid_to_hex_r(p, oid);
5433 for (; i < the_hash_algo->hexsz; i++) {
5434 char save = p[i];
5435 p[i] = '\0';
5436 if (!hashmap_get_from_hash(&state->labels,
5437 strihash(p), p))
5438 break;
5439 p[i] = save;
5442 } else {
5443 struct strbuf *buf = &state->buf;
5444 int label_is_utf8 = 1; /* start with this assumption */
5445 size_t max_len = buf->len + state->max_label_length;
5448 * Sanitize labels by replacing non-alpha-numeric characters
5449 * (including white-space ones) by dashes, as they might be
5450 * illegal in file names (and hence in ref names).
5452 * Note that we retain non-ASCII UTF-8 characters (identified
5453 * via the most significant bit). They should be all acceptable
5454 * in file names.
5456 * As we will use the labels as names of (loose) refs, it is
5457 * vital that the name not be longer than the maximum component
5458 * size of the file system (`NAME_MAX`). We are careful to
5459 * truncate the label accordingly, allowing for the `.lock`
5460 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5461 * truncating in the middle of a character).
5463 for (; *label && buf->len + 1 < max_len; label++)
5464 if (isalnum(*label) ||
5465 (!label_is_utf8 && (*label & 0x80)))
5466 strbuf_addch(buf, *label);
5467 else if (*label & 0x80) {
5468 const char *p = label;
5470 utf8_width(&p, NULL);
5471 if (p) {
5472 if (buf->len + (p - label) > max_len)
5473 break;
5474 strbuf_add(buf, label, p - label);
5475 label = p - 1;
5476 } else {
5477 label_is_utf8 = 0;
5478 strbuf_addch(buf, *label);
5480 /* avoid leading dash and double-dashes */
5481 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5482 strbuf_addch(buf, '-');
5483 if (!buf->len) {
5484 strbuf_addstr(buf, "rev-");
5485 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5487 label = buf->buf;
5489 if ((buf->len == the_hash_algo->hexsz &&
5490 !get_oid_hex(label, &dummy)) ||
5491 (buf->len == 1 && *label == '#') ||
5492 hashmap_get_from_hash(&state->labels,
5493 strihash(label), label)) {
5495 * If the label already exists, or if the label is a
5496 * valid full OID, or the label is a '#' (which we use
5497 * as a separator between merge heads and oneline), we
5498 * append a dash and a number to make it unique.
5500 size_t len = buf->len;
5502 for (i = 2; ; i++) {
5503 strbuf_setlen(buf, len);
5504 strbuf_addf(buf, "-%d", i);
5505 if (!hashmap_get_from_hash(&state->labels,
5506 strihash(buf->buf),
5507 buf->buf))
5508 break;
5511 label = buf->buf;
5515 FLEX_ALLOC_STR(labels_entry, label, label);
5516 hashmap_entry_init(&labels_entry->entry, strihash(label));
5517 hashmap_add(&state->labels, &labels_entry->entry);
5519 FLEX_ALLOC_STR(string_entry, string, label);
5520 oidcpy(&string_entry->entry.oid, oid);
5521 oidmap_put(&state->commit2label, string_entry);
5523 return string_entry->string;
5526 static int make_script_with_merges(struct pretty_print_context *pp,
5527 struct rev_info *revs, struct strbuf *out,
5528 unsigned flags)
5530 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5531 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5532 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5533 int skipped_commit = 0;
5534 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5535 struct strbuf label = STRBUF_INIT;
5536 struct commit_list *commits = NULL, **tail = &commits, *iter;
5537 struct commit_list *tips = NULL, **tips_tail = &tips;
5538 struct commit *commit;
5539 struct oidmap commit2todo = OIDMAP_INIT;
5540 struct string_entry *entry;
5541 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5542 shown = OIDSET_INIT;
5543 struct label_state state =
5544 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5546 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5547 const char *cmd_pick = abbr ? "p" : "pick",
5548 *cmd_label = abbr ? "l" : "label",
5549 *cmd_reset = abbr ? "t" : "reset",
5550 *cmd_merge = abbr ? "m" : "merge";
5552 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5554 oidmap_init(&commit2todo, 0);
5555 oidmap_init(&state.commit2label, 0);
5556 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5557 strbuf_init(&state.buf, 32);
5559 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5560 struct labels_entry *onto_label_entry;
5561 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5562 FLEX_ALLOC_STR(entry, string, "onto");
5563 oidcpy(&entry->entry.oid, oid);
5564 oidmap_put(&state.commit2label, entry);
5566 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5567 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5568 hashmap_add(&state.labels, &onto_label_entry->entry);
5572 * First phase:
5573 * - get onelines for all commits
5574 * - gather all branch tips (i.e. 2nd or later parents of merges)
5575 * - label all branch tips
5577 while ((commit = get_revision(revs))) {
5578 struct commit_list *to_merge;
5579 const char *p1, *p2;
5580 struct object_id *oid;
5581 int is_empty;
5583 tail = &commit_list_insert(commit, tail)->next;
5584 oidset_insert(&interesting, &commit->object.oid);
5586 is_empty = is_original_commit_empty(commit);
5587 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5588 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5589 warning(_("skipped previously applied commit %s"),
5590 short_commit_name(the_repository, commit));
5591 skipped_commit = 1;
5592 continue;
5594 if (is_empty && !keep_empty)
5595 continue;
5597 strbuf_reset(&oneline);
5598 pretty_print_commit(pp, commit, &oneline);
5600 to_merge = commit->parents ? commit->parents->next : NULL;
5601 if (!to_merge) {
5602 /* non-merge commit: easy case */
5603 strbuf_reset(&buf);
5604 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5605 oid_to_hex(&commit->object.oid),
5606 oneline.buf);
5607 if (is_empty)
5608 strbuf_addf(&buf, " %c empty",
5609 comment_line_char);
5611 FLEX_ALLOC_STR(entry, string, buf.buf);
5612 oidcpy(&entry->entry.oid, &commit->object.oid);
5613 oidmap_put(&commit2todo, entry);
5615 continue;
5618 /* Create a label */
5619 strbuf_reset(&label);
5620 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5621 (p1 = strchr(p1, '\'')) &&
5622 (p2 = strchr(++p1, '\'')))
5623 strbuf_add(&label, p1, p2 - p1);
5624 else if (skip_prefix(oneline.buf, "Merge pull request ",
5625 &p1) &&
5626 (p1 = strstr(p1, " from ")))
5627 strbuf_addstr(&label, p1 + strlen(" from "));
5628 else
5629 strbuf_addbuf(&label, &oneline);
5631 strbuf_reset(&buf);
5632 strbuf_addf(&buf, "%s -C %s",
5633 cmd_merge, oid_to_hex(&commit->object.oid));
5635 /* label the tips of merged branches */
5636 for (; to_merge; to_merge = to_merge->next) {
5637 oid = &to_merge->item->object.oid;
5638 strbuf_addch(&buf, ' ');
5640 if (!oidset_contains(&interesting, oid)) {
5641 strbuf_addstr(&buf, label_oid(oid, NULL,
5642 &state));
5643 continue;
5646 tips_tail = &commit_list_insert(to_merge->item,
5647 tips_tail)->next;
5649 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5651 strbuf_addf(&buf, " # %s", oneline.buf);
5653 FLEX_ALLOC_STR(entry, string, buf.buf);
5654 oidcpy(&entry->entry.oid, &commit->object.oid);
5655 oidmap_put(&commit2todo, entry);
5657 if (skipped_commit)
5658 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5659 _("use --reapply-cherry-picks to include skipped commits"));
5662 * Second phase:
5663 * - label branch points
5664 * - add HEAD to the branch tips
5666 for (iter = commits; iter; iter = iter->next) {
5667 struct commit_list *parent = iter->item->parents;
5668 for (; parent; parent = parent->next) {
5669 struct object_id *oid = &parent->item->object.oid;
5670 if (!oidset_contains(&interesting, oid))
5671 continue;
5672 if (oidset_insert(&child_seen, oid))
5673 label_oid(oid, "branch-point", &state);
5676 /* Add HEAD as implicit "tip of branch" */
5677 if (!iter->next)
5678 tips_tail = &commit_list_insert(iter->item,
5679 tips_tail)->next;
5683 * Third phase: output the todo list. This is a bit tricky, as we
5684 * want to avoid jumping back and forth between revisions. To
5685 * accomplish that goal, we walk backwards from the branch tips,
5686 * gathering commits not yet shown, reversing the list on the fly,
5687 * then outputting that list (labeling revisions as needed).
5689 strbuf_addf(out, "%s onto\n", cmd_label);
5690 for (iter = tips; iter; iter = iter->next) {
5691 struct commit_list *list = NULL, *iter2;
5693 commit = iter->item;
5694 if (oidset_contains(&shown, &commit->object.oid))
5695 continue;
5696 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5698 if (entry)
5699 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5700 else
5701 strbuf_addch(out, '\n');
5703 while (oidset_contains(&interesting, &commit->object.oid) &&
5704 !oidset_contains(&shown, &commit->object.oid)) {
5705 commit_list_insert(commit, &list);
5706 if (!commit->parents) {
5707 commit = NULL;
5708 break;
5710 commit = commit->parents->item;
5713 if (!commit)
5714 strbuf_addf(out, "%s %s\n", cmd_reset,
5715 rebase_cousins || root_with_onto ?
5716 "onto" : "[new root]");
5717 else {
5718 const char *to = NULL;
5720 entry = oidmap_get(&state.commit2label,
5721 &commit->object.oid);
5722 if (entry)
5723 to = entry->string;
5724 else if (!rebase_cousins)
5725 to = label_oid(&commit->object.oid, NULL,
5726 &state);
5728 if (!to || !strcmp(to, "onto"))
5729 strbuf_addf(out, "%s onto\n", cmd_reset);
5730 else {
5731 strbuf_reset(&oneline);
5732 pretty_print_commit(pp, commit, &oneline);
5733 strbuf_addf(out, "%s %s # %s\n",
5734 cmd_reset, to, oneline.buf);
5738 for (iter2 = list; iter2; iter2 = iter2->next) {
5739 struct object_id *oid = &iter2->item->object.oid;
5740 entry = oidmap_get(&commit2todo, oid);
5741 /* only show if not already upstream */
5742 if (entry)
5743 strbuf_addf(out, "%s\n", entry->string);
5744 entry = oidmap_get(&state.commit2label, oid);
5745 if (entry)
5746 strbuf_addf(out, "%s %s\n",
5747 cmd_label, entry->string);
5748 oidset_insert(&shown, oid);
5751 free_commit_list(list);
5754 free_commit_list(commits);
5755 free_commit_list(tips);
5757 strbuf_release(&label);
5758 strbuf_release(&oneline);
5759 strbuf_release(&buf);
5761 oidmap_free(&commit2todo, 1);
5762 oidmap_free(&state.commit2label, 1);
5763 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5764 strbuf_release(&state.buf);
5766 return 0;
5769 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5770 const char **argv, unsigned flags)
5772 char *format = NULL;
5773 struct pretty_print_context pp = {0};
5774 struct rev_info revs;
5775 struct commit *commit;
5776 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5777 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5778 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5779 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5780 int skipped_commit = 0;
5781 int ret = 0;
5783 repo_init_revisions(r, &revs, NULL);
5784 revs.verbose_header = 1;
5785 if (!rebase_merges)
5786 revs.max_parents = 1;
5787 revs.cherry_mark = !reapply_cherry_picks;
5788 revs.limited = 1;
5789 revs.reverse = 1;
5790 revs.right_only = 1;
5791 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5792 revs.topo_order = 1;
5794 revs.pretty_given = 1;
5795 git_config_get_string("rebase.instructionFormat", &format);
5796 if (!format || !*format) {
5797 free(format);
5798 format = xstrdup("%s");
5800 get_commit_format(format, &revs);
5801 free(format);
5802 pp.fmt = revs.commit_format;
5803 pp.output_encoding = get_log_output_encoding();
5805 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5806 ret = error(_("make_script: unhandled options"));
5807 goto cleanup;
5810 if (prepare_revision_walk(&revs) < 0) {
5811 ret = error(_("make_script: error preparing revisions"));
5812 goto cleanup;
5815 if (rebase_merges) {
5816 ret = make_script_with_merges(&pp, &revs, out, flags);
5817 goto cleanup;
5820 while ((commit = get_revision(&revs))) {
5821 int is_empty = is_original_commit_empty(commit);
5823 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5824 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5825 warning(_("skipped previously applied commit %s"),
5826 short_commit_name(r, commit));
5827 skipped_commit = 1;
5828 continue;
5830 if (is_empty && !keep_empty)
5831 continue;
5832 strbuf_addf(out, "%s %s ", insn,
5833 oid_to_hex(&commit->object.oid));
5834 pretty_print_commit(&pp, commit, out);
5835 if (is_empty)
5836 strbuf_addf(out, " %c empty", comment_line_char);
5837 strbuf_addch(out, '\n');
5839 if (skipped_commit)
5840 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5841 _("use --reapply-cherry-picks to include skipped commits"));
5842 cleanup:
5843 release_revisions(&revs);
5844 return ret;
5848 * Add commands after pick and (series of) squash/fixup commands
5849 * in the todo list.
5851 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5852 struct string_list *commands)
5854 struct strbuf *buf = &todo_list->buf;
5855 size_t base_offset = buf->len;
5856 int i, insert, nr = 0, alloc = 0;
5857 struct todo_item *items = NULL, *base_items = NULL;
5859 CALLOC_ARRAY(base_items, commands->nr);
5860 for (i = 0; i < commands->nr; i++) {
5861 size_t command_len = strlen(commands->items[i].string);
5863 strbuf_addstr(buf, commands->items[i].string);
5864 strbuf_addch(buf, '\n');
5866 base_items[i].command = TODO_EXEC;
5867 base_items[i].offset_in_buf = base_offset;
5868 base_items[i].arg_offset = base_offset;
5869 base_items[i].arg_len = command_len;
5871 base_offset += command_len + 1;
5875 * Insert <commands> after every pick. Here, fixup/squash chains
5876 * are considered part of the pick, so we insert the commands *after*
5877 * those chains if there are any.
5879 * As we insert the exec commands immediately after rearranging
5880 * any fixups and before the user edits the list, a fixup chain
5881 * can never contain comments (any comments are empty picks that
5882 * have been commented out because the user did not specify
5883 * --keep-empty). So, it is safe to insert an exec command
5884 * without looking at the command following a comment.
5886 insert = 0;
5887 for (i = 0; i < todo_list->nr; i++) {
5888 enum todo_command command = todo_list->items[i].command;
5889 if (insert && !is_fixup(command)) {
5890 ALLOC_GROW(items, nr + commands->nr, alloc);
5891 COPY_ARRAY(items + nr, base_items, commands->nr);
5892 nr += commands->nr;
5894 insert = 0;
5897 ALLOC_GROW(items, nr + 1, alloc);
5898 items[nr++] = todo_list->items[i];
5900 if (command == TODO_PICK || command == TODO_MERGE)
5901 insert = 1;
5904 /* insert or append final <commands> */
5905 if (insert) {
5906 ALLOC_GROW(items, nr + commands->nr, alloc);
5907 COPY_ARRAY(items + nr, base_items, commands->nr);
5908 nr += commands->nr;
5911 free(base_items);
5912 FREE_AND_NULL(todo_list->items);
5913 todo_list->items = items;
5914 todo_list->nr = nr;
5915 todo_list->alloc = alloc;
5918 static void todo_list_to_strbuf(struct repository *r,
5919 struct todo_list *todo_list,
5920 struct strbuf *buf, int num, unsigned flags)
5922 struct todo_item *item;
5923 int i, max = todo_list->nr;
5925 if (num > 0 && num < max)
5926 max = num;
5928 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5929 char cmd;
5931 /* if the item is not a command write it and continue */
5932 if (item->command >= TODO_COMMENT) {
5933 strbuf_addf(buf, "%.*s\n", item->arg_len,
5934 todo_item_get_arg(todo_list, item));
5935 continue;
5938 /* add command to the buffer */
5939 cmd = command_to_char(item->command);
5940 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5941 strbuf_addch(buf, cmd);
5942 else
5943 strbuf_addstr(buf, command_to_string(item->command));
5945 /* add commit id */
5946 if (item->commit) {
5947 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5948 short_commit_name(r, item->commit) :
5949 oid_to_hex(&item->commit->object.oid);
5951 if (item->command == TODO_FIXUP) {
5952 if (item->flags & TODO_EDIT_FIXUP_MSG)
5953 strbuf_addstr(buf, " -c");
5954 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5955 strbuf_addstr(buf, " -C");
5959 if (item->command == TODO_MERGE) {
5960 if (item->flags & TODO_EDIT_MERGE_MSG)
5961 strbuf_addstr(buf, " -c");
5962 else
5963 strbuf_addstr(buf, " -C");
5966 strbuf_addf(buf, " %s", oid);
5969 /* add all the rest */
5970 if (!item->arg_len)
5971 strbuf_addch(buf, '\n');
5972 else
5973 strbuf_addf(buf, " %.*s\n", item->arg_len,
5974 todo_item_get_arg(todo_list, item));
5978 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5979 const char *file, const char *shortrevisions,
5980 const char *shortonto, int num, unsigned flags)
5982 int res;
5983 struct strbuf buf = STRBUF_INIT;
5985 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5986 if (flags & TODO_LIST_APPEND_TODO_HELP)
5987 append_todo_help(count_commands(todo_list),
5988 shortrevisions, shortonto, &buf);
5990 res = write_message(buf.buf, buf.len, file, 0);
5991 strbuf_release(&buf);
5993 return res;
5996 /* skip picking commits whose parents are unchanged */
5997 static int skip_unnecessary_picks(struct repository *r,
5998 struct todo_list *todo_list,
5999 struct object_id *base_oid)
6001 struct object_id *parent_oid;
6002 int i;
6004 for (i = 0; i < todo_list->nr; i++) {
6005 struct todo_item *item = todo_list->items + i;
6007 if (item->command >= TODO_NOOP)
6008 continue;
6009 if (item->command != TODO_PICK)
6010 break;
6011 if (repo_parse_commit(r, item->commit)) {
6012 return error(_("could not parse commit '%s'"),
6013 oid_to_hex(&item->commit->object.oid));
6015 if (!item->commit->parents)
6016 break; /* root commit */
6017 if (item->commit->parents->next)
6018 break; /* merge commit */
6019 parent_oid = &item->commit->parents->item->object.oid;
6020 if (!oideq(parent_oid, base_oid))
6021 break;
6022 oidcpy(base_oid, &item->commit->object.oid);
6024 if (i > 0) {
6025 const char *done_path = rebase_path_done();
6027 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6028 error_errno(_("could not write to '%s'"), done_path);
6029 return -1;
6032 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6033 todo_list->nr -= i;
6034 todo_list->current = 0;
6035 todo_list->done_nr += i;
6037 if (is_fixup(peek_command(todo_list, 0)))
6038 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6041 return 0;
6044 struct todo_add_branch_context {
6045 struct todo_item *items;
6046 size_t items_nr;
6047 size_t items_alloc;
6048 struct strbuf *buf;
6049 struct commit *commit;
6050 struct string_list refs_to_oids;
6053 static int add_decorations_to_list(const struct commit *commit,
6054 struct todo_add_branch_context *ctx)
6056 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6057 const char *head_ref = resolve_ref_unsafe("HEAD",
6058 RESOLVE_REF_READING,
6059 NULL,
6060 NULL);
6062 while (decoration) {
6063 struct todo_item *item;
6064 const char *path;
6065 size_t base_offset = ctx->buf->len;
6068 * If the branch is the current HEAD, then it will be
6069 * updated by the default rebase behavior.
6071 if (head_ref && !strcmp(head_ref, decoration->name)) {
6072 decoration = decoration->next;
6073 continue;
6076 ALLOC_GROW(ctx->items,
6077 ctx->items_nr + 1,
6078 ctx->items_alloc);
6079 item = &ctx->items[ctx->items_nr];
6080 memset(item, 0, sizeof(*item));
6082 /* If the branch is checked out, then leave a comment instead. */
6083 if ((path = branch_checked_out(decoration->name))) {
6084 item->command = TODO_COMMENT;
6085 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6086 decoration->name, path);
6087 } else {
6088 struct string_list_item *sti;
6089 item->command = TODO_UPDATE_REF;
6090 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6092 sti = string_list_insert(&ctx->refs_to_oids,
6093 decoration->name);
6094 sti->util = init_update_ref_record(decoration->name);
6097 item->offset_in_buf = base_offset;
6098 item->arg_offset = base_offset;
6099 item->arg_len = ctx->buf->len - base_offset;
6100 ctx->items_nr++;
6102 decoration = decoration->next;
6105 return 0;
6109 * For each 'pick' command, find out if the commit has a decoration in
6110 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6112 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6114 int i, res;
6115 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6116 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6117 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6118 struct decoration_filter decoration_filter = {
6119 .include_ref_pattern = &decorate_refs_include,
6120 .exclude_ref_pattern = &decorate_refs_exclude,
6121 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6123 struct todo_add_branch_context ctx = {
6124 .buf = &todo_list->buf,
6125 .refs_to_oids = STRING_LIST_INIT_DUP,
6128 ctx.items_alloc = 2 * todo_list->nr + 1;
6129 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6131 string_list_append(&decorate_refs_include, "refs/heads/");
6132 load_ref_decorations(&decoration_filter, 0);
6134 for (i = 0; i < todo_list->nr; ) {
6135 struct todo_item *item = &todo_list->items[i];
6137 /* insert ith item into new list */
6138 ALLOC_GROW(ctx.items,
6139 ctx.items_nr + 1,
6140 ctx.items_alloc);
6142 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6144 if (item->commit) {
6145 ctx.commit = item->commit;
6146 add_decorations_to_list(item->commit, &ctx);
6150 res = write_update_refs_state(&ctx.refs_to_oids);
6152 string_list_clear(&ctx.refs_to_oids, 1);
6154 if (res) {
6155 /* we failed, so clean up the new list. */
6156 free(ctx.items);
6157 return res;
6160 free(todo_list->items);
6161 todo_list->items = ctx.items;
6162 todo_list->nr = ctx.items_nr;
6163 todo_list->alloc = ctx.items_alloc;
6165 return 0;
6168 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6169 const char *shortrevisions, const char *onto_name,
6170 struct commit *onto, const struct object_id *orig_head,
6171 struct string_list *commands, unsigned autosquash,
6172 unsigned update_refs,
6173 struct todo_list *todo_list)
6175 char shortonto[GIT_MAX_HEXSZ + 1];
6176 const char *todo_file = rebase_path_todo();
6177 struct todo_list new_todo = TODO_LIST_INIT;
6178 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6179 struct object_id oid = onto->object.oid;
6180 int res;
6182 repo_find_unique_abbrev_r(r, shortonto, &oid,
6183 DEFAULT_ABBREV);
6185 if (buf->len == 0) {
6186 struct todo_item *item = append_new_todo(todo_list);
6187 item->command = TODO_NOOP;
6188 item->commit = NULL;
6189 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6192 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6193 return -1;
6195 if (autosquash && todo_list_rearrange_squash(todo_list))
6196 return -1;
6198 if (commands->nr)
6199 todo_list_add_exec_commands(todo_list, commands);
6201 if (count_commands(todo_list) == 0) {
6202 apply_autostash(rebase_path_autostash());
6203 sequencer_remove_state(opts);
6205 return error(_("nothing to do"));
6208 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6209 shortonto, flags);
6210 if (res == -1)
6211 return -1;
6212 else if (res == -2) {
6213 apply_autostash(rebase_path_autostash());
6214 sequencer_remove_state(opts);
6216 return -1;
6217 } else if (res == -3) {
6218 apply_autostash(rebase_path_autostash());
6219 sequencer_remove_state(opts);
6220 todo_list_release(&new_todo);
6222 return error(_("nothing to do"));
6223 } else if (res == -4) {
6224 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6225 todo_list_release(&new_todo);
6227 return -1;
6230 /* Expand the commit IDs */
6231 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6232 strbuf_swap(&new_todo.buf, &buf2);
6233 strbuf_release(&buf2);
6234 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6235 new_todo.total_nr = 0;
6236 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6237 BUG("invalid todo list after expanding IDs:\n%s",
6238 new_todo.buf.buf);
6240 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6241 todo_list_release(&new_todo);
6242 return error(_("could not skip unnecessary pick commands"));
6245 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6246 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6247 todo_list_release(&new_todo);
6248 return error_errno(_("could not write '%s'"), todo_file);
6251 res = -1;
6253 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6254 goto cleanup;
6256 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6257 goto cleanup;
6259 todo_list_write_total_nr(&new_todo);
6260 res = pick_commits(r, &new_todo, opts);
6262 cleanup:
6263 todo_list_release(&new_todo);
6265 return res;
6268 struct subject2item_entry {
6269 struct hashmap_entry entry;
6270 int i;
6271 char subject[FLEX_ARRAY];
6274 static int subject2item_cmp(const void *fndata UNUSED,
6275 const struct hashmap_entry *eptr,
6276 const struct hashmap_entry *entry_or_key,
6277 const void *key)
6279 const struct subject2item_entry *a, *b;
6281 a = container_of(eptr, const struct subject2item_entry, entry);
6282 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6284 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6287 define_commit_slab(commit_todo_item, struct todo_item *);
6289 static int skip_fixupish(const char *subject, const char **p) {
6290 return skip_prefix(subject, "fixup! ", p) ||
6291 skip_prefix(subject, "amend! ", p) ||
6292 skip_prefix(subject, "squash! ", p);
6296 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6297 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6298 * after the former, and change "pick" to "fixup"/"squash".
6300 * Note that if the config has specified a custom instruction format, each log
6301 * message will have to be retrieved from the commit (as the oneline in the
6302 * script cannot be trusted) in order to normalize the autosquash arrangement.
6304 int todo_list_rearrange_squash(struct todo_list *todo_list)
6306 struct hashmap subject2item;
6307 int rearranged = 0, *next, *tail, i, nr = 0;
6308 char **subjects;
6309 struct commit_todo_item commit_todo;
6310 struct todo_item *items = NULL;
6312 init_commit_todo_item(&commit_todo);
6314 * The hashmap maps onelines to the respective todo list index.
6316 * If any items need to be rearranged, the next[i] value will indicate
6317 * which item was moved directly after the i'th.
6319 * In that case, last[i] will indicate the index of the latest item to
6320 * be moved to appear after the i'th.
6322 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6323 ALLOC_ARRAY(next, todo_list->nr);
6324 ALLOC_ARRAY(tail, todo_list->nr);
6325 ALLOC_ARRAY(subjects, todo_list->nr);
6326 for (i = 0; i < todo_list->nr; i++) {
6327 struct strbuf buf = STRBUF_INIT;
6328 struct todo_item *item = todo_list->items + i;
6329 const char *commit_buffer, *subject, *p;
6330 size_t subject_len;
6331 int i2 = -1;
6332 struct subject2item_entry *entry;
6334 next[i] = tail[i] = -1;
6335 if (!item->commit || item->command == TODO_DROP) {
6336 subjects[i] = NULL;
6337 continue;
6340 if (is_fixup(item->command)) {
6341 clear_commit_todo_item(&commit_todo);
6342 return error(_("the script was already rearranged."));
6345 repo_parse_commit(the_repository, item->commit);
6346 commit_buffer = repo_logmsg_reencode(the_repository,
6347 item->commit, NULL,
6348 "UTF-8");
6349 find_commit_subject(commit_buffer, &subject);
6350 format_subject(&buf, subject, " ");
6351 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6352 repo_unuse_commit_buffer(the_repository, item->commit,
6353 commit_buffer);
6354 if (skip_fixupish(subject, &p)) {
6355 struct commit *commit2;
6357 for (;;) {
6358 while (isspace(*p))
6359 p++;
6360 if (!skip_fixupish(p, &p))
6361 break;
6364 entry = hashmap_get_entry_from_hash(&subject2item,
6365 strhash(p), p,
6366 struct subject2item_entry,
6367 entry);
6368 if (entry)
6369 /* found by title */
6370 i2 = entry->i;
6371 else if (!strchr(p, ' ') &&
6372 (commit2 =
6373 lookup_commit_reference_by_name(p)) &&
6374 *commit_todo_item_at(&commit_todo, commit2))
6375 /* found by commit name */
6376 i2 = *commit_todo_item_at(&commit_todo, commit2)
6377 - todo_list->items;
6378 else {
6379 /* copy can be a prefix of the commit subject */
6380 for (i2 = 0; i2 < i; i2++)
6381 if (subjects[i2] &&
6382 starts_with(subjects[i2], p))
6383 break;
6384 if (i2 == i)
6385 i2 = -1;
6388 if (i2 >= 0) {
6389 rearranged = 1;
6390 if (starts_with(subject, "fixup!")) {
6391 todo_list->items[i].command = TODO_FIXUP;
6392 } else if (starts_with(subject, "amend!")) {
6393 todo_list->items[i].command = TODO_FIXUP;
6394 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6395 } else {
6396 todo_list->items[i].command = TODO_SQUASH;
6398 if (tail[i2] < 0) {
6399 next[i] = next[i2];
6400 next[i2] = i;
6401 } else {
6402 next[i] = next[tail[i2]];
6403 next[tail[i2]] = i;
6405 tail[i2] = i;
6406 } else if (!hashmap_get_from_hash(&subject2item,
6407 strhash(subject), subject)) {
6408 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6409 entry->i = i;
6410 hashmap_entry_init(&entry->entry,
6411 strhash(entry->subject));
6412 hashmap_put(&subject2item, &entry->entry);
6415 *commit_todo_item_at(&commit_todo, item->commit) = item;
6418 if (rearranged) {
6419 ALLOC_ARRAY(items, todo_list->nr);
6421 for (i = 0; i < todo_list->nr; i++) {
6422 enum todo_command command = todo_list->items[i].command;
6423 int cur = i;
6426 * Initially, all commands are 'pick's. If it is a
6427 * fixup or a squash now, we have rearranged it.
6429 if (is_fixup(command))
6430 continue;
6432 while (cur >= 0) {
6433 items[nr++] = todo_list->items[cur];
6434 cur = next[cur];
6438 assert(nr == todo_list->nr);
6439 todo_list->alloc = nr;
6440 FREE_AND_NULL(todo_list->items);
6441 todo_list->items = items;
6444 free(next);
6445 free(tail);
6446 for (i = 0; i < todo_list->nr; i++)
6447 free(subjects[i]);
6448 free(subjects);
6449 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6451 clear_commit_todo_item(&commit_todo);
6453 return 0;
6456 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6458 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6459 struct object_id cherry_pick_head, rebase_head;
6461 if (file_exists(git_path_seq_dir()))
6462 *whence = FROM_CHERRY_PICK_MULTI;
6463 if (file_exists(rebase_path()) &&
6464 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6465 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6466 oideq(&rebase_head, &cherry_pick_head))
6467 *whence = FROM_REBASE_PICK;
6468 else
6469 *whence = FROM_CHERRY_PICK_SINGLE;
6471 return 1;
6474 return 0;
6477 int sequencer_get_update_refs_state(const char *wt_dir,
6478 struct string_list *refs)
6480 int result = 0;
6481 FILE *fp = NULL;
6482 struct strbuf ref = STRBUF_INIT;
6483 struct strbuf hash = STRBUF_INIT;
6484 struct update_ref_record *rec = NULL;
6486 char *path = rebase_path_update_refs(wt_dir);
6488 fp = fopen(path, "r");
6489 if (!fp)
6490 goto cleanup;
6492 while (strbuf_getline(&ref, fp) != EOF) {
6493 struct string_list_item *item;
6495 CALLOC_ARRAY(rec, 1);
6497 if (strbuf_getline(&hash, fp) == EOF ||
6498 get_oid_hex(hash.buf, &rec->before)) {
6499 warning(_("update-refs file at '%s' is invalid"),
6500 path);
6501 result = -1;
6502 goto cleanup;
6505 if (strbuf_getline(&hash, fp) == EOF ||
6506 get_oid_hex(hash.buf, &rec->after)) {
6507 warning(_("update-refs file at '%s' is invalid"),
6508 path);
6509 result = -1;
6510 goto cleanup;
6513 item = string_list_insert(refs, ref.buf);
6514 item->util = rec;
6515 rec = NULL;
6518 cleanup:
6519 if (fp)
6520 fclose(fp);
6521 free(path);
6522 free(rec);
6523 strbuf_release(&ref);
6524 strbuf_release(&hash);
6525 return result;