merge-ort: drop unused parameters from detect_and_process_renames()
[git.git] / sequencer.c
blobafebf7e37c982973908e391e476ab876a8068e8d
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 * For the post-rewrite hook, we make a list of rewritten commits and
152 * their new sha1s. The rewritten-pending list keeps the sha1s of
153 * commits that have been processed, but not committed yet,
154 * e.g. because they are waiting for a 'squash' command.
156 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
157 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
158 "rebase-merge/rewritten-pending")
161 * The path of the file containing the OID of the "squash onto" commit, i.e.
162 * the dummy commit used for `reset [new root]`.
164 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
167 * The path of the file listing refs that need to be deleted after the rebase
168 * finishes. This is used by the `label` command to record the need for cleanup.
170 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
173 * The update-refs file stores a list of refs that will be updated at the end
174 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
175 * update the OIDs for the refs in this file, but the refs are not updated
176 * until the end of the rebase sequence.
178 * rebase_path_update_refs() returns the path to this file for a given
179 * worktree directory. For the current worktree, pass the_repository->gitdir.
181 static char *rebase_path_update_refs(const char *wt_git_dir)
183 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
187 * The following files are written by git-rebase just after parsing the
188 * command-line.
190 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
191 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
192 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
193 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
194 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
195 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
196 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
197 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
198 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
199 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
200 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
201 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
202 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
203 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
204 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
205 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
206 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
209 * A 'struct update_refs_record' represents a value in the update-refs
210 * list. We use a string_list to map refs to these (before, after) pairs.
212 struct update_ref_record {
213 struct object_id before;
214 struct object_id after;
217 static struct update_ref_record *init_update_ref_record(const char *ref)
219 struct update_ref_record *rec;
221 CALLOC_ARRAY(rec, 1);
223 oidcpy(&rec->before, null_oid());
224 oidcpy(&rec->after, null_oid());
226 /* This may fail, but that's fine, we will keep the null OID. */
227 read_ref(ref, &rec->before);
229 return rec;
232 static int git_sequencer_config(const char *k, const char *v,
233 const struct config_context *ctx, void *cb)
235 struct replay_opts *opts = cb;
236 int status;
238 if (!strcmp(k, "commit.cleanup")) {
239 const char *s;
241 status = git_config_string(&s, k, v);
242 if (status)
243 return status;
245 if (!strcmp(s, "verbatim")) {
246 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
247 opts->explicit_cleanup = 1;
248 } else if (!strcmp(s, "whitespace")) {
249 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
250 opts->explicit_cleanup = 1;
251 } else if (!strcmp(s, "strip")) {
252 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
253 opts->explicit_cleanup = 1;
254 } else if (!strcmp(s, "scissors")) {
255 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
256 opts->explicit_cleanup = 1;
257 } else {
258 warning(_("invalid commit message cleanup mode '%s'"),
262 free((char *)s);
263 return status;
266 if (!strcmp(k, "commit.gpgsign")) {
267 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
268 return 0;
271 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
272 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
273 if (ret == 0) {
275 * pull.twohead is allowed to be multi-valued; we only
276 * care about the first value.
278 char *tmp = strchr(opts->default_strategy, ' ');
279 if (tmp)
280 *tmp = '\0';
282 return ret;
285 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
286 opts->commit_use_reference = git_config_bool(k, v);
288 return git_diff_basic_config(k, v, ctx, NULL);
291 void sequencer_init_config(struct replay_opts *opts)
293 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
294 git_config(git_sequencer_config, opts);
297 static inline int is_rebase_i(const struct replay_opts *opts)
299 return opts->action == REPLAY_INTERACTIVE_REBASE;
302 static const char *get_dir(const struct replay_opts *opts)
304 if (is_rebase_i(opts))
305 return rebase_path();
306 return git_path_seq_dir();
309 static const char *get_todo_path(const struct replay_opts *opts)
311 if (is_rebase_i(opts))
312 return rebase_path_todo();
313 return git_path_todo_file();
317 * Returns 0 for non-conforming footer
318 * Returns 1 for conforming footer
319 * Returns 2 when sob exists within conforming footer
320 * Returns 3 when sob exists within conforming footer as last entry
322 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
323 size_t ignore_footer)
325 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
326 struct trailer_info info;
327 size_t i;
328 int found_sob = 0, found_sob_last = 0;
329 char saved_char;
331 opts.no_divider = 1;
333 if (ignore_footer) {
334 saved_char = sb->buf[sb->len - ignore_footer];
335 sb->buf[sb->len - ignore_footer] = '\0';
338 trailer_info_get(&info, sb->buf, &opts);
340 if (ignore_footer)
341 sb->buf[sb->len - ignore_footer] = saved_char;
343 if (info.trailer_start == info.trailer_end)
344 return 0;
346 for (i = 0; i < info.trailer_nr; i++)
347 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
348 found_sob = 1;
349 if (i == info.trailer_nr - 1)
350 found_sob_last = 1;
353 trailer_info_release(&info);
355 if (found_sob_last)
356 return 3;
357 if (found_sob)
358 return 2;
359 return 1;
362 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
364 static struct strbuf buf = STRBUF_INIT;
366 strbuf_reset(&buf);
367 if (opts->gpg_sign)
368 sq_quotef(&buf, "-S%s", opts->gpg_sign);
369 return buf.buf;
372 void replay_opts_release(struct replay_opts *opts)
374 free(opts->gpg_sign);
375 free(opts->reflog_action);
376 free(opts->default_strategy);
377 free(opts->strategy);
378 strvec_clear (&opts->xopts);
379 strbuf_release(&opts->current_fixups);
380 if (opts->revs)
381 release_revisions(opts->revs);
382 free(opts->revs);
385 int sequencer_remove_state(struct replay_opts *opts)
387 struct strbuf buf = STRBUF_INIT;
388 int ret = 0;
390 if (is_rebase_i(opts) &&
391 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
392 char *p = buf.buf;
393 while (*p) {
394 char *eol = strchr(p, '\n');
395 if (eol)
396 *eol = '\0';
397 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
398 warning(_("could not delete '%s'"), p);
399 ret = -1;
401 if (!eol)
402 break;
403 p = eol + 1;
407 strbuf_reset(&buf);
408 strbuf_addstr(&buf, get_dir(opts));
409 if (remove_dir_recursively(&buf, 0))
410 ret = error(_("could not remove '%s'"), buf.buf);
411 strbuf_release(&buf);
413 return ret;
416 static const char *action_name(const struct replay_opts *opts)
418 switch (opts->action) {
419 case REPLAY_REVERT:
420 return N_("revert");
421 case REPLAY_PICK:
422 return N_("cherry-pick");
423 case REPLAY_INTERACTIVE_REBASE:
424 return N_("rebase");
426 die(_("unknown action: %d"), opts->action);
429 struct commit_message {
430 char *parent_label;
431 char *label;
432 char *subject;
433 const char *message;
436 static const char *short_commit_name(struct repository *r, struct commit *commit)
438 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
441 static int get_message(struct commit *commit, struct commit_message *out)
443 const char *abbrev, *subject;
444 int subject_len;
446 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
447 get_commit_output_encoding());
448 abbrev = short_commit_name(the_repository, commit);
450 subject_len = find_commit_subject(out->message, &subject);
452 out->subject = xmemdupz(subject, subject_len);
453 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
454 out->parent_label = xstrfmt("parent of %s", out->label);
456 return 0;
459 static void free_message(struct commit *commit, struct commit_message *msg)
461 free(msg->parent_label);
462 free(msg->label);
463 free(msg->subject);
464 repo_unuse_commit_buffer(the_repository, commit, msg->message);
467 static void print_advice(struct repository *r, int show_hint,
468 struct replay_opts *opts)
470 char *msg = getenv("GIT_CHERRY_PICK_HELP");
472 if (msg) {
473 advise("%s\n", msg);
475 * A conflict has occurred but the porcelain
476 * (typically rebase --interactive) wants to take care
477 * of the commit itself so remove CHERRY_PICK_HEAD
479 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
480 NULL, 0);
481 return;
484 if (show_hint) {
485 if (opts->no_commit)
486 advise(_("after resolving the conflicts, mark the corrected paths\n"
487 "with 'git add <paths>' or 'git rm <paths>'"));
488 else if (opts->action == REPLAY_PICK)
489 advise(_("After resolving the conflicts, mark them with\n"
490 "\"git add/rm <pathspec>\", then run\n"
491 "\"git cherry-pick --continue\".\n"
492 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
493 "To abort and get back to the state before \"git cherry-pick\",\n"
494 "run \"git cherry-pick --abort\"."));
495 else if (opts->action == REPLAY_REVERT)
496 advise(_("After resolving the conflicts, mark them with\n"
497 "\"git add/rm <pathspec>\", then run\n"
498 "\"git revert --continue\".\n"
499 "You can instead skip this commit with \"git revert --skip\".\n"
500 "To abort and get back to the state before \"git revert\",\n"
501 "run \"git revert --abort\"."));
502 else
503 BUG("unexpected pick action in print_advice()");
507 static int write_message(const void *buf, size_t len, const char *filename,
508 int append_eol)
510 struct lock_file msg_file = LOCK_INIT;
512 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
513 if (msg_fd < 0)
514 return error_errno(_("could not lock '%s'"), filename);
515 if (write_in_full(msg_fd, buf, len) < 0) {
516 error_errno(_("could not write to '%s'"), filename);
517 rollback_lock_file(&msg_file);
518 return -1;
520 if (append_eol && write(msg_fd, "\n", 1) < 0) {
521 error_errno(_("could not write eol to '%s'"), filename);
522 rollback_lock_file(&msg_file);
523 return -1;
525 if (commit_lock_file(&msg_file) < 0)
526 return error(_("failed to finalize '%s'"), filename);
528 return 0;
531 int read_oneliner(struct strbuf *buf,
532 const char *path, unsigned flags)
534 int orig_len = buf->len;
536 if (strbuf_read_file(buf, path, 0) < 0) {
537 if ((flags & READ_ONELINER_WARN_MISSING) ||
538 (errno != ENOENT && errno != ENOTDIR))
539 warning_errno(_("could not read '%s'"), path);
540 return 0;
543 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
544 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
545 --buf->len;
546 buf->buf[buf->len] = '\0';
549 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
550 return 0;
552 return 1;
555 static struct tree *empty_tree(struct repository *r)
557 return lookup_tree(r, the_hash_algo->empty_tree);
560 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
562 if (repo_read_index_unmerged(repo))
563 return error_resolve_conflict(action_name(opts));
565 error(_("your local changes would be overwritten by %s."),
566 _(action_name(opts)));
568 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
569 advise(_("commit your changes or stash them to proceed."));
570 return -1;
573 static void update_abort_safety_file(void)
575 struct object_id head;
577 /* Do nothing on a single-pick */
578 if (!file_exists(git_path_seq_dir()))
579 return;
581 if (!repo_get_oid(the_repository, "HEAD", &head))
582 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
583 else
584 write_file(git_path_abort_safety_file(), "%s", "");
587 static int fast_forward_to(struct repository *r,
588 const struct object_id *to,
589 const struct object_id *from,
590 int unborn,
591 struct replay_opts *opts)
593 struct ref_transaction *transaction;
594 struct strbuf sb = STRBUF_INIT;
595 struct strbuf err = STRBUF_INIT;
597 repo_read_index(r);
598 if (checkout_fast_forward(r, from, to, 1))
599 return -1; /* the callee should have complained already */
601 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
603 transaction = ref_transaction_begin(&err);
604 if (!transaction ||
605 ref_transaction_update(transaction, "HEAD",
606 to, unborn && !is_rebase_i(opts) ?
607 null_oid() : from,
608 0, sb.buf, &err) ||
609 ref_transaction_commit(transaction, &err)) {
610 ref_transaction_free(transaction);
611 error("%s", err.buf);
612 strbuf_release(&sb);
613 strbuf_release(&err);
614 return -1;
617 strbuf_release(&sb);
618 strbuf_release(&err);
619 ref_transaction_free(transaction);
620 update_abort_safety_file();
621 return 0;
624 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
625 int use_editor)
627 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
628 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
629 COMMIT_MSG_CLEANUP_SPACE;
630 else if (!strcmp(cleanup_arg, "verbatim"))
631 return COMMIT_MSG_CLEANUP_NONE;
632 else if (!strcmp(cleanup_arg, "whitespace"))
633 return COMMIT_MSG_CLEANUP_SPACE;
634 else if (!strcmp(cleanup_arg, "strip"))
635 return COMMIT_MSG_CLEANUP_ALL;
636 else if (!strcmp(cleanup_arg, "scissors"))
637 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
638 COMMIT_MSG_CLEANUP_SPACE;
639 else
640 die(_("Invalid cleanup mode %s"), cleanup_arg);
644 * NB using int rather than enum cleanup_mode to stop clang's
645 * -Wtautological-constant-out-of-range-compare complaining that the comparison
646 * is always true.
648 static const char *describe_cleanup_mode(int cleanup_mode)
650 static const char *modes[] = { "whitespace",
651 "verbatim",
652 "scissors",
653 "strip" };
655 if (cleanup_mode < ARRAY_SIZE(modes))
656 return modes[cleanup_mode];
658 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
661 void append_conflicts_hint(struct index_state *istate,
662 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
664 int i;
666 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
667 strbuf_addch(msgbuf, '\n');
668 wt_status_append_cut_line(msgbuf);
669 strbuf_addch(msgbuf, comment_line_char);
672 strbuf_addch(msgbuf, '\n');
673 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
674 for (i = 0; i < istate->cache_nr;) {
675 const struct cache_entry *ce = istate->cache[i++];
676 if (ce_stage(ce)) {
677 strbuf_commented_addf(msgbuf, comment_line_char,
678 "\t%s\n", ce->name);
679 while (i < istate->cache_nr &&
680 !strcmp(ce->name, istate->cache[i]->name))
681 i++;
686 static int do_recursive_merge(struct repository *r,
687 struct commit *base, struct commit *next,
688 const char *base_label, const char *next_label,
689 struct object_id *head, struct strbuf *msgbuf,
690 struct replay_opts *opts)
692 struct merge_options o;
693 struct merge_result result;
694 struct tree *next_tree, *base_tree, *head_tree;
695 int clean, show_output;
696 int i;
697 struct lock_file index_lock = LOCK_INIT;
699 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
700 return -1;
702 repo_read_index(r);
704 init_merge_options(&o, r);
705 o.ancestor = base ? base_label : "(empty tree)";
706 o.branch1 = "HEAD";
707 o.branch2 = next ? next_label : "(empty tree)";
708 if (is_rebase_i(opts))
709 o.buffer_output = 2;
710 o.show_rename_progress = 1;
712 head_tree = parse_tree_indirect(head);
713 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
714 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
716 for (i = 0; i < opts->xopts.nr; i++)
717 parse_merge_opt(&o, opts->xopts.v[i]);
719 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
720 memset(&result, 0, sizeof(result));
721 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
722 &result);
723 show_output = !is_rebase_i(opts) || !result.clean;
725 * TODO: merge_switch_to_result will update index/working tree;
726 * we only really want to do that if !result.clean || this is
727 * the final patch to be picked. But determining this is the
728 * final patch would take some work, and "head_tree" would need
729 * to be replace with the tree the index matched before we
730 * started doing any picks.
732 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
733 clean = result.clean;
734 } else {
735 ensure_full_index(r->index);
736 clean = merge_trees(&o, head_tree, next_tree, base_tree);
737 if (is_rebase_i(opts) && clean <= 0)
738 fputs(o.obuf.buf, stdout);
739 strbuf_release(&o.obuf);
741 if (clean < 0) {
742 rollback_lock_file(&index_lock);
743 return clean;
746 if (write_locked_index(r->index, &index_lock,
747 COMMIT_LOCK | SKIP_IF_UNCHANGED))
749 * TRANSLATORS: %s will be "revert", "cherry-pick" or
750 * "rebase".
752 return error(_("%s: Unable to write new index file"),
753 _(action_name(opts)));
755 if (!clean)
756 append_conflicts_hint(r->index, msgbuf,
757 opts->default_msg_cleanup);
759 return !clean;
762 static struct object_id *get_cache_tree_oid(struct index_state *istate)
764 if (!cache_tree_fully_valid(istate->cache_tree))
765 if (cache_tree_update(istate, 0)) {
766 error(_("unable to update cache tree"));
767 return NULL;
770 return &istate->cache_tree->oid;
773 static int is_index_unchanged(struct repository *r)
775 struct object_id head_oid, *cache_tree_oid;
776 struct commit *head_commit;
777 struct index_state *istate = r->index;
779 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
780 return error(_("could not resolve HEAD commit"));
782 head_commit = lookup_commit(r, &head_oid);
785 * If head_commit is NULL, check_commit, called from
786 * lookup_commit, would have indicated that head_commit is not
787 * a commit object already. repo_parse_commit() will return failure
788 * without further complaints in such a case. Otherwise, if
789 * the commit is invalid, repo_parse_commit() will complain. So
790 * there is nothing for us to say here. Just return failure.
792 if (repo_parse_commit(r, head_commit))
793 return -1;
795 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
796 return -1;
798 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
801 static int write_author_script(const char *message)
803 struct strbuf buf = STRBUF_INIT;
804 const char *eol;
805 int res;
807 for (;;)
808 if (!*message || starts_with(message, "\n")) {
809 missing_author:
810 /* Missing 'author' line? */
811 unlink(rebase_path_author_script());
812 return 0;
813 } else if (skip_prefix(message, "author ", &message))
814 break;
815 else if ((eol = strchr(message, '\n')))
816 message = eol + 1;
817 else
818 goto missing_author;
820 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
821 while (*message && *message != '\n' && *message != '\r')
822 if (skip_prefix(message, " <", &message))
823 break;
824 else if (*message != '\'')
825 strbuf_addch(&buf, *(message++));
826 else
827 strbuf_addf(&buf, "'\\%c'", *(message++));
828 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
829 while (*message && *message != '\n' && *message != '\r')
830 if (skip_prefix(message, "> ", &message))
831 break;
832 else if (*message != '\'')
833 strbuf_addch(&buf, *(message++));
834 else
835 strbuf_addf(&buf, "'\\%c'", *(message++));
836 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
837 while (*message && *message != '\n' && *message != '\r')
838 if (*message != '\'')
839 strbuf_addch(&buf, *(message++));
840 else
841 strbuf_addf(&buf, "'\\%c'", *(message++));
842 strbuf_addch(&buf, '\'');
843 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
844 strbuf_release(&buf);
845 return res;
849 * Take a series of KEY='VALUE' lines where VALUE part is
850 * sq-quoted, and append <KEY, VALUE> at the end of the string list
852 static int parse_key_value_squoted(char *buf, struct string_list *list)
854 while (*buf) {
855 struct string_list_item *item;
856 char *np;
857 char *cp = strchr(buf, '=');
858 if (!cp) {
859 np = strchrnul(buf, '\n');
860 return error(_("no key present in '%.*s'"),
861 (int) (np - buf), buf);
863 np = strchrnul(cp, '\n');
864 *cp++ = '\0';
865 item = string_list_append(list, buf);
867 buf = np + (*np == '\n');
868 *np = '\0';
869 cp = sq_dequote(cp);
870 if (!cp)
871 return error(_("unable to dequote value of '%s'"),
872 item->string);
873 item->util = xstrdup(cp);
875 return 0;
879 * Reads and parses the state directory's "author-script" file, and sets name,
880 * email and date accordingly.
881 * Returns 0 on success, -1 if the file could not be parsed.
883 * The author script is of the format:
885 * GIT_AUTHOR_NAME='$author_name'
886 * GIT_AUTHOR_EMAIL='$author_email'
887 * GIT_AUTHOR_DATE='$author_date'
889 * where $author_name, $author_email and $author_date are quoted. We are strict
890 * with our parsing, as the file was meant to be eval'd in the now-removed
891 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
892 * from what this function expects, it is better to bail out than to do
893 * something that the user does not expect.
895 int read_author_script(const char *path, char **name, char **email, char **date,
896 int allow_missing)
898 struct strbuf buf = STRBUF_INIT;
899 struct string_list kv = STRING_LIST_INIT_DUP;
900 int retval = -1; /* assume failure */
901 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
903 if (strbuf_read_file(&buf, path, 256) <= 0) {
904 strbuf_release(&buf);
905 if (errno == ENOENT && allow_missing)
906 return 0;
907 else
908 return error_errno(_("could not open '%s' for reading"),
909 path);
912 if (parse_key_value_squoted(buf.buf, &kv))
913 goto finish;
915 for (i = 0; i < kv.nr; i++) {
916 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
917 if (name_i != -2)
918 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
919 else
920 name_i = i;
921 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
922 if (email_i != -2)
923 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
924 else
925 email_i = i;
926 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
927 if (date_i != -2)
928 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
929 else
930 date_i = i;
931 } else {
932 err = error(_("unknown variable '%s'"),
933 kv.items[i].string);
936 if (name_i == -2)
937 error(_("missing 'GIT_AUTHOR_NAME'"));
938 if (email_i == -2)
939 error(_("missing 'GIT_AUTHOR_EMAIL'"));
940 if (date_i == -2)
941 error(_("missing 'GIT_AUTHOR_DATE'"));
942 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
943 goto finish;
944 *name = kv.items[name_i].util;
945 *email = kv.items[email_i].util;
946 *date = kv.items[date_i].util;
947 retval = 0;
948 finish:
949 string_list_clear(&kv, !!retval);
950 strbuf_release(&buf);
951 return retval;
955 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
956 * file with shell quoting into struct strvec. Returns -1 on
957 * error, 0 otherwise.
959 static int read_env_script(struct strvec *env)
961 char *name, *email, *date;
963 if (read_author_script(rebase_path_author_script(),
964 &name, &email, &date, 0))
965 return -1;
967 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
968 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
969 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
970 free(name);
971 free(email);
972 free(date);
974 return 0;
977 static char *get_author(const char *message)
979 size_t len;
980 const char *a;
982 a = find_commit_header(message, "author", &len);
983 if (a)
984 return xmemdupz(a, len);
986 return NULL;
989 static const char *author_date_from_env(const struct strvec *env)
991 int i;
992 const char *date;
994 for (i = 0; i < env->nr; i++)
995 if (skip_prefix(env->v[i],
996 "GIT_AUTHOR_DATE=", &date))
997 return date;
999 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1000 * reading the script
1002 BUG("GIT_AUTHOR_DATE missing from author script");
1005 static const char staged_changes_advice[] =
1006 N_("you have staged changes in your working tree\n"
1007 "If these changes are meant to be squashed into the previous commit, run:\n"
1008 "\n"
1009 " git commit --amend %s\n"
1010 "\n"
1011 "If they are meant to go into a new commit, run:\n"
1012 "\n"
1013 " git commit %s\n"
1014 "\n"
1015 "In both cases, once you're done, continue with:\n"
1016 "\n"
1017 " git rebase --continue\n");
1019 #define ALLOW_EMPTY (1<<0)
1020 #define EDIT_MSG (1<<1)
1021 #define AMEND_MSG (1<<2)
1022 #define CLEANUP_MSG (1<<3)
1023 #define VERIFY_MSG (1<<4)
1024 #define CREATE_ROOT_COMMIT (1<<5)
1025 #define VERBATIM_MSG (1<<6)
1027 static int run_command_silent_on_success(struct child_process *cmd)
1029 struct strbuf buf = STRBUF_INIT;
1030 int rc;
1032 cmd->stdout_to_stderr = 1;
1033 rc = pipe_command(cmd,
1034 NULL, 0,
1035 NULL, 0,
1036 &buf, 0);
1038 if (rc)
1039 fputs(buf.buf, stderr);
1040 strbuf_release(&buf);
1041 return rc;
1045 * If we are cherry-pick, and if the merge did not result in
1046 * hand-editing, we will hit this commit and inherit the original
1047 * author date and name.
1049 * If we are revert, or if our cherry-pick results in a hand merge,
1050 * we had better say that the current user is responsible for that.
1052 * An exception is when run_git_commit() is called during an
1053 * interactive rebase: in that case, we will want to retain the
1054 * author metadata.
1056 static int run_git_commit(const char *defmsg,
1057 struct replay_opts *opts,
1058 unsigned int flags)
1060 struct child_process cmd = CHILD_PROCESS_INIT;
1062 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1063 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1065 cmd.git_cmd = 1;
1067 if (is_rebase_i(opts) &&
1068 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1069 !(!defmsg && (flags & AMEND_MSG))) &&
1070 read_env_script(&cmd.env)) {
1071 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1073 return error(_(staged_changes_advice),
1074 gpg_opt, gpg_opt);
1077 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1079 if (opts->committer_date_is_author_date)
1080 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1081 opts->ignore_date ?
1082 "" :
1083 author_date_from_env(&cmd.env));
1084 if (opts->ignore_date)
1085 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1087 strvec_push(&cmd.args, "commit");
1089 if (!(flags & VERIFY_MSG))
1090 strvec_push(&cmd.args, "-n");
1091 if ((flags & AMEND_MSG))
1092 strvec_push(&cmd.args, "--amend");
1093 if (opts->gpg_sign)
1094 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1095 else
1096 strvec_push(&cmd.args, "--no-gpg-sign");
1097 if (defmsg)
1098 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1099 else if (!(flags & EDIT_MSG))
1100 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1101 if ((flags & CLEANUP_MSG))
1102 strvec_push(&cmd.args, "--cleanup=strip");
1103 if ((flags & VERBATIM_MSG))
1104 strvec_push(&cmd.args, "--cleanup=verbatim");
1105 if ((flags & EDIT_MSG))
1106 strvec_push(&cmd.args, "-e");
1107 else if (!(flags & CLEANUP_MSG) &&
1108 !opts->signoff && !opts->record_origin &&
1109 !opts->explicit_cleanup)
1110 strvec_push(&cmd.args, "--cleanup=verbatim");
1112 if ((flags & ALLOW_EMPTY))
1113 strvec_push(&cmd.args, "--allow-empty");
1115 if (!(flags & EDIT_MSG))
1116 strvec_push(&cmd.args, "--allow-empty-message");
1118 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1119 return run_command_silent_on_success(&cmd);
1120 else
1121 return run_command(&cmd);
1124 static int rest_is_empty(const struct strbuf *sb, int start)
1126 int i, eol;
1127 const char *nl;
1129 /* Check if the rest is just whitespace and Signed-off-by's. */
1130 for (i = start; i < sb->len; i++) {
1131 nl = memchr(sb->buf + i, '\n', sb->len - i);
1132 if (nl)
1133 eol = nl - sb->buf;
1134 else
1135 eol = sb->len;
1137 if (strlen(sign_off_header) <= eol - i &&
1138 starts_with(sb->buf + i, sign_off_header)) {
1139 i = eol;
1140 continue;
1142 while (i < eol)
1143 if (!isspace(sb->buf[i++]))
1144 return 0;
1147 return 1;
1150 void cleanup_message(struct strbuf *msgbuf,
1151 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1153 if (verbose || /* Truncate the message just before the diff, if any. */
1154 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1155 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1156 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1157 strbuf_stripspace(msgbuf,
1158 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1162 * Find out if the message in the strbuf contains only whitespace and
1163 * Signed-off-by lines.
1165 int message_is_empty(const struct strbuf *sb,
1166 enum commit_msg_cleanup_mode cleanup_mode)
1168 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1169 return 0;
1170 return rest_is_empty(sb, 0);
1174 * See if the user edited the message in the editor or left what
1175 * was in the template intact
1177 int template_untouched(const struct strbuf *sb, const char *template_file,
1178 enum commit_msg_cleanup_mode cleanup_mode)
1180 struct strbuf tmpl = STRBUF_INIT;
1181 const char *start;
1183 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1184 return 0;
1186 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1187 return 0;
1189 strbuf_stripspace(&tmpl,
1190 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1191 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1192 start = sb->buf;
1193 strbuf_release(&tmpl);
1194 return rest_is_empty(sb, start - sb->buf);
1197 int update_head_with_reflog(const struct commit *old_head,
1198 const struct object_id *new_head,
1199 const char *action, const struct strbuf *msg,
1200 struct strbuf *err)
1202 struct ref_transaction *transaction;
1203 struct strbuf sb = STRBUF_INIT;
1204 const char *nl;
1205 int ret = 0;
1207 if (action) {
1208 strbuf_addstr(&sb, action);
1209 strbuf_addstr(&sb, ": ");
1212 nl = strchr(msg->buf, '\n');
1213 if (nl) {
1214 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1215 } else {
1216 strbuf_addbuf(&sb, msg);
1217 strbuf_addch(&sb, '\n');
1220 transaction = ref_transaction_begin(err);
1221 if (!transaction ||
1222 ref_transaction_update(transaction, "HEAD", new_head,
1223 old_head ? &old_head->object.oid : null_oid(),
1224 0, sb.buf, err) ||
1225 ref_transaction_commit(transaction, err)) {
1226 ret = -1;
1228 ref_transaction_free(transaction);
1229 strbuf_release(&sb);
1231 return ret;
1234 static int run_rewrite_hook(const struct object_id *oldoid,
1235 const struct object_id *newoid)
1237 struct child_process proc = CHILD_PROCESS_INIT;
1238 int code;
1239 struct strbuf sb = STRBUF_INIT;
1240 const char *hook_path = find_hook("post-rewrite");
1242 if (!hook_path)
1243 return 0;
1245 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1246 proc.in = -1;
1247 proc.stdout_to_stderr = 1;
1248 proc.trace2_hook_name = "post-rewrite";
1250 code = start_command(&proc);
1251 if (code)
1252 return code;
1253 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1254 sigchain_push(SIGPIPE, SIG_IGN);
1255 write_in_full(proc.in, sb.buf, sb.len);
1256 close(proc.in);
1257 strbuf_release(&sb);
1258 sigchain_pop(SIGPIPE);
1259 return finish_command(&proc);
1262 void commit_post_rewrite(struct repository *r,
1263 const struct commit *old_head,
1264 const struct object_id *new_head)
1266 struct notes_rewrite_cfg *cfg;
1268 cfg = init_copy_notes_for_rewrite("amend");
1269 if (cfg) {
1270 /* we are amending, so old_head is not NULL */
1271 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1272 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1274 run_rewrite_hook(&old_head->object.oid, new_head);
1277 static int run_prepare_commit_msg_hook(struct repository *r,
1278 struct strbuf *msg,
1279 const char *commit)
1281 int ret = 0;
1282 const char *name, *arg1 = NULL, *arg2 = NULL;
1284 name = git_path_commit_editmsg();
1285 if (write_message(msg->buf, msg->len, name, 0))
1286 return -1;
1288 if (commit) {
1289 arg1 = "commit";
1290 arg2 = commit;
1291 } else {
1292 arg1 = "message";
1294 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1295 arg1, arg2, NULL))
1296 ret = error(_("'prepare-commit-msg' hook failed"));
1298 return ret;
1301 static const char implicit_ident_advice_noconfig[] =
1302 N_("Your name and email address were configured automatically based\n"
1303 "on your username and hostname. Please check that they are accurate.\n"
1304 "You can suppress this message by setting them explicitly. Run the\n"
1305 "following command and follow the instructions in your editor to edit\n"
1306 "your configuration file:\n"
1307 "\n"
1308 " git config --global --edit\n"
1309 "\n"
1310 "After doing this, you may fix the identity used for this commit with:\n"
1311 "\n"
1312 " git commit --amend --reset-author\n");
1314 static const char implicit_ident_advice_config[] =
1315 N_("Your name and email address were configured automatically based\n"
1316 "on your username and hostname. Please check that they are accurate.\n"
1317 "You can suppress this message by setting them explicitly:\n"
1318 "\n"
1319 " git config --global user.name \"Your Name\"\n"
1320 " git config --global user.email you@example.com\n"
1321 "\n"
1322 "After doing this, you may fix the identity used for this commit with:\n"
1323 "\n"
1324 " git commit --amend --reset-author\n");
1326 static const char *implicit_ident_advice(void)
1328 char *user_config = interpolate_path("~/.gitconfig", 0);
1329 char *xdg_config = xdg_config_home("config");
1330 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1332 free(user_config);
1333 free(xdg_config);
1335 if (config_exists)
1336 return _(implicit_ident_advice_config);
1337 else
1338 return _(implicit_ident_advice_noconfig);
1342 void print_commit_summary(struct repository *r,
1343 const char *prefix,
1344 const struct object_id *oid,
1345 unsigned int flags)
1347 struct rev_info rev;
1348 struct commit *commit;
1349 struct strbuf format = STRBUF_INIT;
1350 const char *head;
1351 struct pretty_print_context pctx = {0};
1352 struct strbuf author_ident = STRBUF_INIT;
1353 struct strbuf committer_ident = STRBUF_INIT;
1354 struct ref_store *refs;
1356 commit = lookup_commit(r, oid);
1357 if (!commit)
1358 die(_("couldn't look up newly created commit"));
1359 if (repo_parse_commit(r, commit))
1360 die(_("could not parse newly created commit"));
1362 strbuf_addstr(&format, "format:%h] %s");
1364 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1365 &pctx);
1366 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1367 &pctx);
1368 if (strbuf_cmp(&author_ident, &committer_ident)) {
1369 strbuf_addstr(&format, "\n Author: ");
1370 strbuf_addbuf_percentquote(&format, &author_ident);
1372 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1373 struct strbuf date = STRBUF_INIT;
1375 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1376 strbuf_addstr(&format, "\n Date: ");
1377 strbuf_addbuf_percentquote(&format, &date);
1378 strbuf_release(&date);
1380 if (!committer_ident_sufficiently_given()) {
1381 strbuf_addstr(&format, "\n Committer: ");
1382 strbuf_addbuf_percentquote(&format, &committer_ident);
1383 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1384 strbuf_addch(&format, '\n');
1385 strbuf_addstr(&format, implicit_ident_advice());
1388 strbuf_release(&author_ident);
1389 strbuf_release(&committer_ident);
1391 repo_init_revisions(r, &rev, prefix);
1392 setup_revisions(0, NULL, &rev, NULL);
1394 rev.diff = 1;
1395 rev.diffopt.output_format =
1396 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1398 rev.verbose_header = 1;
1399 rev.show_root_diff = 1;
1400 get_commit_format(format.buf, &rev);
1401 rev.always_show_header = 0;
1402 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1403 diff_setup_done(&rev.diffopt);
1405 refs = get_main_ref_store(r);
1406 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1407 if (!head)
1408 die(_("unable to resolve HEAD after creating commit"));
1409 if (!strcmp(head, "HEAD"))
1410 head = _("detached HEAD");
1411 else
1412 skip_prefix(head, "refs/heads/", &head);
1413 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1414 _(" (root-commit)") : "");
1416 if (!log_tree_commit(&rev, commit)) {
1417 rev.always_show_header = 1;
1418 rev.use_terminator = 1;
1419 log_tree_commit(&rev, commit);
1422 release_revisions(&rev);
1423 strbuf_release(&format);
1426 static int parse_head(struct repository *r, struct commit **head)
1428 struct commit *current_head;
1429 struct object_id oid;
1431 if (repo_get_oid(r, "HEAD", &oid)) {
1432 current_head = NULL;
1433 } else {
1434 current_head = lookup_commit_reference(r, &oid);
1435 if (!current_head)
1436 return error(_("could not parse HEAD"));
1437 if (!oideq(&oid, &current_head->object.oid)) {
1438 warning(_("HEAD %s is not a commit!"),
1439 oid_to_hex(&oid));
1441 if (repo_parse_commit(r, current_head))
1442 return error(_("could not parse HEAD commit"));
1444 *head = current_head;
1446 return 0;
1450 * Try to commit without forking 'git commit'. In some cases we need
1451 * to run 'git commit' to display an error message
1453 * Returns:
1454 * -1 - error unable to commit
1455 * 0 - success
1456 * 1 - run 'git commit'
1458 static int try_to_commit(struct repository *r,
1459 struct strbuf *msg, const char *author,
1460 struct replay_opts *opts, unsigned int flags,
1461 struct object_id *oid)
1463 struct object_id tree;
1464 struct commit *current_head = NULL;
1465 struct commit_list *parents = NULL;
1466 struct commit_extra_header *extra = NULL;
1467 struct strbuf err = STRBUF_INIT;
1468 struct strbuf commit_msg = STRBUF_INIT;
1469 char *amend_author = NULL;
1470 const char *committer = NULL;
1471 const char *hook_commit = NULL;
1472 enum commit_msg_cleanup_mode cleanup;
1473 int res = 0;
1475 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1476 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1478 if (parse_head(r, &current_head))
1479 return -1;
1481 if (flags & AMEND_MSG) {
1482 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1483 const char *out_enc = get_commit_output_encoding();
1484 const char *message = repo_logmsg_reencode(r, current_head,
1485 NULL, out_enc);
1487 if (!msg) {
1488 const char *orig_message = NULL;
1490 find_commit_subject(message, &orig_message);
1491 msg = &commit_msg;
1492 strbuf_addstr(msg, orig_message);
1493 hook_commit = "HEAD";
1495 author = amend_author = get_author(message);
1496 repo_unuse_commit_buffer(r, current_head,
1497 message);
1498 if (!author) {
1499 res = error(_("unable to parse commit author"));
1500 goto out;
1502 parents = copy_commit_list(current_head->parents);
1503 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1504 } else if (current_head &&
1505 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1506 commit_list_insert(current_head, &parents);
1509 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1510 res = error(_("git write-tree failed to write a tree"));
1511 goto out;
1514 if (!(flags & ALLOW_EMPTY)) {
1515 struct commit *first_parent = current_head;
1517 if (flags & AMEND_MSG) {
1518 if (current_head->parents) {
1519 first_parent = current_head->parents->item;
1520 if (repo_parse_commit(r, first_parent)) {
1521 res = error(_("could not parse HEAD commit"));
1522 goto out;
1524 } else {
1525 first_parent = NULL;
1528 if (oideq(first_parent
1529 ? get_commit_tree_oid(first_parent)
1530 : the_hash_algo->empty_tree,
1531 &tree)) {
1532 res = 1; /* run 'git commit' to display error message */
1533 goto out;
1537 if (hook_exists("prepare-commit-msg")) {
1538 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1539 if (res)
1540 goto out;
1541 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1542 2048) < 0) {
1543 res = error_errno(_("unable to read commit message "
1544 "from '%s'"),
1545 git_path_commit_editmsg());
1546 goto out;
1548 msg = &commit_msg;
1551 if (flags & CLEANUP_MSG)
1552 cleanup = COMMIT_MSG_CLEANUP_ALL;
1553 else if (flags & VERBATIM_MSG)
1554 cleanup = COMMIT_MSG_CLEANUP_NONE;
1555 else if ((opts->signoff || opts->record_origin) &&
1556 !opts->explicit_cleanup)
1557 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1558 else
1559 cleanup = opts->default_msg_cleanup;
1561 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1562 strbuf_stripspace(msg,
1563 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1564 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1565 res = 1; /* run 'git commit' to display error message */
1566 goto out;
1569 if (opts->committer_date_is_author_date) {
1570 struct ident_split id;
1571 struct strbuf date = STRBUF_INIT;
1573 if (!opts->ignore_date) {
1574 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1575 res = error(_("invalid author identity '%s'"),
1576 author);
1577 goto out;
1579 if (!id.date_begin) {
1580 res = error(_(
1581 "corrupt author: missing date information"));
1582 goto out;
1584 strbuf_addf(&date, "@%.*s %.*s",
1585 (int)(id.date_end - id.date_begin),
1586 id.date_begin,
1587 (int)(id.tz_end - id.tz_begin),
1588 id.tz_begin);
1589 } else {
1590 reset_ident_date();
1592 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1593 getenv("GIT_COMMITTER_EMAIL"),
1594 WANT_COMMITTER_IDENT,
1595 opts->ignore_date ? NULL : date.buf,
1596 IDENT_STRICT);
1597 strbuf_release(&date);
1598 } else {
1599 reset_ident_date();
1602 if (opts->ignore_date) {
1603 struct ident_split id;
1604 char *name, *email;
1606 if (split_ident_line(&id, author, strlen(author)) < 0) {
1607 error(_("invalid author identity '%s'"), author);
1608 goto out;
1610 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1611 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1612 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1613 IDENT_STRICT);
1614 free(name);
1615 free(email);
1618 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1619 author, committer, opts->gpg_sign, extra)) {
1620 res = error(_("failed to write commit object"));
1621 goto out;
1624 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1625 msg, &err)) {
1626 res = error("%s", err.buf);
1627 goto out;
1630 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1631 if (flags & AMEND_MSG)
1632 commit_post_rewrite(r, current_head, oid);
1634 out:
1635 free_commit_extra_headers(extra);
1636 strbuf_release(&err);
1637 strbuf_release(&commit_msg);
1638 free(amend_author);
1640 return res;
1643 static int write_rebase_head(struct object_id *oid)
1645 if (update_ref("rebase", "REBASE_HEAD", oid,
1646 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1647 return error(_("could not update %s"), "REBASE_HEAD");
1649 return 0;
1652 static int do_commit(struct repository *r,
1653 const char *msg_file, const char *author,
1654 struct replay_opts *opts, unsigned int flags,
1655 struct object_id *oid)
1657 int res = 1;
1659 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1660 struct object_id oid;
1661 struct strbuf sb = STRBUF_INIT;
1663 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1664 return error_errno(_("unable to read commit message "
1665 "from '%s'"),
1666 msg_file);
1668 res = try_to_commit(r, msg_file ? &sb : NULL,
1669 author, opts, flags, &oid);
1670 strbuf_release(&sb);
1671 if (!res) {
1672 refs_delete_ref(get_main_ref_store(r), "",
1673 "CHERRY_PICK_HEAD", NULL, 0);
1674 unlink(git_path_merge_msg(r));
1675 if (!is_rebase_i(opts))
1676 print_commit_summary(r, NULL, &oid,
1677 SUMMARY_SHOW_AUTHOR_DATE);
1678 return res;
1681 if (res == 1) {
1682 if (is_rebase_i(opts) && oid)
1683 if (write_rebase_head(oid))
1684 return -1;
1685 return run_git_commit(msg_file, opts, flags);
1688 return res;
1691 static int is_original_commit_empty(struct commit *commit)
1693 const struct object_id *ptree_oid;
1695 if (repo_parse_commit(the_repository, commit))
1696 return error(_("could not parse commit %s"),
1697 oid_to_hex(&commit->object.oid));
1698 if (commit->parents) {
1699 struct commit *parent = commit->parents->item;
1700 if (repo_parse_commit(the_repository, parent))
1701 return error(_("could not parse parent commit %s"),
1702 oid_to_hex(&parent->object.oid));
1703 ptree_oid = get_commit_tree_oid(parent);
1704 } else {
1705 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1708 return oideq(ptree_oid, get_commit_tree_oid(commit));
1712 * Should empty commits be allowed? Return status:
1713 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1714 * 0: Halt on empty commit
1715 * 1: Allow empty commit
1716 * 2: Drop empty commit
1718 static int allow_empty(struct repository *r,
1719 struct replay_opts *opts,
1720 struct commit *commit)
1722 int index_unchanged, originally_empty;
1725 * Four cases:
1727 * (1) we do not allow empty at all and error out.
1729 * (2) we allow ones that were initially empty, and
1730 * just drop the ones that become empty
1732 * (3) we allow ones that were initially empty, but
1733 * halt for the ones that become empty;
1735 * (4) we allow both.
1737 if (!opts->allow_empty)
1738 return 0; /* let "git commit" barf as necessary */
1740 index_unchanged = is_index_unchanged(r);
1741 if (index_unchanged < 0)
1742 return index_unchanged;
1743 if (!index_unchanged)
1744 return 0; /* we do not have to say --allow-empty */
1746 if (opts->keep_redundant_commits)
1747 return 1;
1749 originally_empty = is_original_commit_empty(commit);
1750 if (originally_empty < 0)
1751 return originally_empty;
1752 if (originally_empty)
1753 return 1;
1754 else if (opts->drop_redundant_commits)
1755 return 2;
1756 else
1757 return 0;
1760 static struct {
1761 char c;
1762 const char *str;
1763 } todo_command_info[] = {
1764 [TODO_PICK] = { 'p', "pick" },
1765 [TODO_REVERT] = { 0, "revert" },
1766 [TODO_EDIT] = { 'e', "edit" },
1767 [TODO_REWORD] = { 'r', "reword" },
1768 [TODO_FIXUP] = { 'f', "fixup" },
1769 [TODO_SQUASH] = { 's', "squash" },
1770 [TODO_EXEC] = { 'x', "exec" },
1771 [TODO_BREAK] = { 'b', "break" },
1772 [TODO_LABEL] = { 'l', "label" },
1773 [TODO_RESET] = { 't', "reset" },
1774 [TODO_MERGE] = { 'm', "merge" },
1775 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1776 [TODO_NOOP] = { 0, "noop" },
1777 [TODO_DROP] = { 'd', "drop" },
1778 [TODO_COMMENT] = { 0, NULL },
1781 static const char *command_to_string(const enum todo_command command)
1783 if (command < TODO_COMMENT)
1784 return todo_command_info[command].str;
1785 die(_("unknown command: %d"), command);
1788 static char command_to_char(const enum todo_command command)
1790 if (command < TODO_COMMENT)
1791 return todo_command_info[command].c;
1792 return comment_line_char;
1795 static int is_noop(const enum todo_command command)
1797 return TODO_NOOP <= command;
1800 static int is_fixup(enum todo_command command)
1802 return command == TODO_FIXUP || command == TODO_SQUASH;
1805 /* Does this command create a (non-merge) commit? */
1806 static int is_pick_or_similar(enum todo_command command)
1808 switch (command) {
1809 case TODO_PICK:
1810 case TODO_REVERT:
1811 case TODO_EDIT:
1812 case TODO_REWORD:
1813 case TODO_FIXUP:
1814 case TODO_SQUASH:
1815 return 1;
1816 default:
1817 return 0;
1821 enum todo_item_flags {
1822 TODO_EDIT_MERGE_MSG = (1 << 0),
1823 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1824 TODO_EDIT_FIXUP_MSG = (1 << 2),
1827 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1828 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1829 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1830 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1831 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1833 static int is_fixup_flag(enum todo_command command, unsigned flag)
1835 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1836 (flag & TODO_EDIT_FIXUP_MSG));
1840 * Wrapper around strbuf_add_commented_lines() which avoids double
1841 * commenting commit subjects.
1843 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1845 const char *s = str;
1846 while (len > 0 && s[0] == comment_line_char) {
1847 size_t count;
1848 const char *n = memchr(s, '\n', len);
1849 if (!n)
1850 count = len;
1851 else
1852 count = n - s + 1;
1853 strbuf_add(buf, s, count);
1854 s += count;
1855 len -= count;
1857 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1860 /* Does the current fixup chain contain a squash command? */
1861 static int seen_squash(struct replay_opts *opts)
1863 return starts_with(opts->current_fixups.buf, "squash") ||
1864 strstr(opts->current_fixups.buf, "\nsquash");
1867 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1869 strbuf_setlen(buf1, 2);
1870 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1871 strbuf_addch(buf1, '\n');
1872 strbuf_setlen(buf2, 2);
1873 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1874 strbuf_addch(buf2, '\n');
1878 * Comment out any un-commented commit messages, updating the message comments
1879 * to say they will be skipped but do not comment out the empty lines that
1880 * surround commit messages and their comments.
1882 static void update_squash_message_for_fixup(struct strbuf *msg)
1884 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1885 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1886 const char *s, *start;
1887 char *orig_msg;
1888 size_t orig_msg_len;
1889 int i = 1;
1891 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1892 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1893 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1894 while (s) {
1895 const char *next;
1896 size_t off;
1897 if (skip_prefix(s, buf1.buf, &next)) {
1899 * Copy the last message, preserving the blank line
1900 * preceding the current line
1902 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1903 copy_lines(msg, start, s - start - off);
1904 if (off)
1905 strbuf_addch(msg, '\n');
1907 * The next message needs to be commented out but the
1908 * message header is already commented out so just copy
1909 * it and the blank line that follows it.
1911 strbuf_addbuf(msg, &buf2);
1912 if (*next == '\n')
1913 strbuf_addch(msg, *next++);
1914 start = s = next;
1915 copy_lines = add_commented_lines;
1916 update_comment_bufs(&buf1, &buf2, ++i);
1917 } else if (skip_prefix(s, buf2.buf, &next)) {
1918 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1919 copy_lines(msg, start, s - start - off);
1920 start = s - off;
1921 s = next;
1922 copy_lines = strbuf_add;
1923 update_comment_bufs(&buf1, &buf2, ++i);
1924 } else {
1925 s = strchr(s, '\n');
1926 if (s)
1927 s++;
1930 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1931 free(orig_msg);
1932 strbuf_release(&buf1);
1933 strbuf_release(&buf2);
1936 static int append_squash_message(struct strbuf *buf, const char *body,
1937 enum todo_command command, struct replay_opts *opts,
1938 unsigned flag)
1940 const char *fixup_msg;
1941 size_t commented_len = 0, fixup_off;
1943 * amend is non-interactive and not normally used with fixup!
1944 * or squash! commits, so only comment out those subjects when
1945 * squashing commit messages.
1947 if (starts_with(body, "amend!") ||
1948 ((command == TODO_SQUASH || seen_squash(opts)) &&
1949 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1950 commented_len = commit_subject_length(body);
1952 strbuf_addf(buf, "\n%c ", comment_line_char);
1953 strbuf_addf(buf, _(nth_commit_msg_fmt),
1954 ++opts->current_fixup_count + 1);
1955 strbuf_addstr(buf, "\n\n");
1956 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1957 /* buf->buf may be reallocated so store an offset into the buffer */
1958 fixup_off = buf->len;
1959 strbuf_addstr(buf, body + commented_len);
1961 /* fixup -C after squash behaves like squash */
1962 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1964 * We're replacing the commit message so we need to
1965 * append the Signed-off-by: trailer if the user
1966 * requested '--signoff'.
1968 if (opts->signoff)
1969 append_signoff(buf, 0, 0);
1971 if ((command == TODO_FIXUP) &&
1972 (flag & TODO_REPLACE_FIXUP_MSG) &&
1973 (file_exists(rebase_path_fixup_msg()) ||
1974 !file_exists(rebase_path_squash_msg()))) {
1975 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1976 if (write_message(fixup_msg, strlen(fixup_msg),
1977 rebase_path_fixup_msg(), 0) < 0)
1978 return error(_("cannot write '%s'"),
1979 rebase_path_fixup_msg());
1980 } else {
1981 unlink(rebase_path_fixup_msg());
1983 } else {
1984 unlink(rebase_path_fixup_msg());
1987 return 0;
1990 static int update_squash_messages(struct repository *r,
1991 enum todo_command command,
1992 struct commit *commit,
1993 struct replay_opts *opts,
1994 unsigned flag)
1996 struct strbuf buf = STRBUF_INIT;
1997 int res = 0;
1998 const char *message, *body;
1999 const char *encoding = get_commit_output_encoding();
2001 if (opts->current_fixup_count > 0) {
2002 struct strbuf header = STRBUF_INIT;
2003 char *eol;
2005 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2006 return error(_("could not read '%s'"),
2007 rebase_path_squash_msg());
2009 eol = buf.buf[0] != comment_line_char ?
2010 buf.buf : strchrnul(buf.buf, '\n');
2012 strbuf_addf(&header, "%c ", comment_line_char);
2013 strbuf_addf(&header, _(combined_commit_msg_fmt),
2014 opts->current_fixup_count + 2);
2015 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2016 strbuf_release(&header);
2017 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2018 update_squash_message_for_fixup(&buf);
2019 } else {
2020 struct object_id head;
2021 struct commit *head_commit;
2022 const char *head_message, *body;
2024 if (repo_get_oid(r, "HEAD", &head))
2025 return error(_("need a HEAD to fixup"));
2026 if (!(head_commit = lookup_commit_reference(r, &head)))
2027 return error(_("could not read HEAD"));
2028 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2029 encoding)))
2030 return error(_("could not read HEAD's commit message"));
2032 find_commit_subject(head_message, &body);
2033 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2034 rebase_path_fixup_msg(), 0) < 0) {
2035 repo_unuse_commit_buffer(r, head_commit, head_message);
2036 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2038 strbuf_addf(&buf, "%c ", comment_line_char);
2039 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2040 strbuf_addf(&buf, "\n%c ", comment_line_char);
2041 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2042 _(skip_first_commit_msg_str) :
2043 _(first_commit_msg_str));
2044 strbuf_addstr(&buf, "\n\n");
2045 if (is_fixup_flag(command, flag))
2046 strbuf_add_commented_lines(&buf, body, strlen(body),
2047 comment_line_char);
2048 else
2049 strbuf_addstr(&buf, body);
2051 repo_unuse_commit_buffer(r, head_commit, head_message);
2054 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2055 return error(_("could not read commit message of %s"),
2056 oid_to_hex(&commit->object.oid));
2057 find_commit_subject(message, &body);
2059 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2060 res = append_squash_message(&buf, body, command, opts, flag);
2061 } else if (command == TODO_FIXUP) {
2062 strbuf_addf(&buf, "\n%c ", comment_line_char);
2063 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2064 ++opts->current_fixup_count + 1);
2065 strbuf_addstr(&buf, "\n\n");
2066 strbuf_add_commented_lines(&buf, body, strlen(body),
2067 comment_line_char);
2068 } else
2069 return error(_("unknown command: %d"), command);
2070 repo_unuse_commit_buffer(r, commit, message);
2072 if (!res)
2073 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2075 strbuf_release(&buf);
2077 if (!res) {
2078 strbuf_addf(&opts->current_fixups, "%s%s %s",
2079 opts->current_fixups.len ? "\n" : "",
2080 command_to_string(command),
2081 oid_to_hex(&commit->object.oid));
2082 res = write_message(opts->current_fixups.buf,
2083 opts->current_fixups.len,
2084 rebase_path_current_fixups(), 0);
2087 return res;
2090 static void flush_rewritten_pending(void)
2092 struct strbuf buf = STRBUF_INIT;
2093 struct object_id newoid;
2094 FILE *out;
2096 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2097 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2098 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2099 char *bol = buf.buf, *eol;
2101 while (*bol) {
2102 eol = strchrnul(bol, '\n');
2103 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2104 bol, oid_to_hex(&newoid));
2105 if (!*eol)
2106 break;
2107 bol = eol + 1;
2109 fclose(out);
2110 unlink(rebase_path_rewritten_pending());
2112 strbuf_release(&buf);
2115 static void record_in_rewritten(struct object_id *oid,
2116 enum todo_command next_command)
2118 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2120 if (!out)
2121 return;
2123 fprintf(out, "%s\n", oid_to_hex(oid));
2124 fclose(out);
2126 if (!is_fixup(next_command))
2127 flush_rewritten_pending();
2130 static int should_edit(struct replay_opts *opts) {
2131 if (opts->edit < 0)
2133 * Note that we only handle the case of non-conflicted
2134 * commits; continue_single_pick() handles the conflicted
2135 * commits itself instead of calling this function.
2137 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2138 return opts->edit;
2141 static void refer_to_commit(struct replay_opts *opts,
2142 struct strbuf *msgbuf, struct commit *commit)
2144 if (opts->commit_use_reference) {
2145 struct pretty_print_context ctx = {
2146 .abbrev = DEFAULT_ABBREV,
2147 .date_mode.type = DATE_SHORT,
2149 repo_format_commit_message(the_repository, commit,
2150 "%h (%s, %ad)", msgbuf, &ctx);
2151 } else {
2152 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2156 static int do_pick_commit(struct repository *r,
2157 struct todo_item *item,
2158 struct replay_opts *opts,
2159 int final_fixup, int *check_todo)
2161 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2162 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2163 struct object_id head;
2164 struct commit *base, *next, *parent;
2165 const char *base_label, *next_label;
2166 char *author = NULL;
2167 struct commit_message msg = { NULL, NULL, NULL, NULL };
2168 struct strbuf msgbuf = STRBUF_INIT;
2169 int res, unborn = 0, reword = 0, allow, drop_commit;
2170 enum todo_command command = item->command;
2171 struct commit *commit = item->commit;
2173 if (opts->no_commit) {
2175 * We do not intend to commit immediately. We just want to
2176 * merge the differences in, so let's compute the tree
2177 * that represents the "current" state for the merge machinery
2178 * to work on.
2180 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2181 return error(_("your index file is unmerged."));
2182 } else {
2183 unborn = repo_get_oid(r, "HEAD", &head);
2184 /* Do we want to generate a root commit? */
2185 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2186 oideq(&head, &opts->squash_onto)) {
2187 if (is_fixup(command))
2188 return error(_("cannot fixup root commit"));
2189 flags |= CREATE_ROOT_COMMIT;
2190 unborn = 1;
2191 } else if (unborn)
2192 oidcpy(&head, the_hash_algo->empty_tree);
2193 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2194 NULL, 0))
2195 return error_dirty_index(r, opts);
2197 discard_index(r->index);
2199 if (!commit->parents)
2200 parent = NULL;
2201 else if (commit->parents->next) {
2202 /* Reverting or cherry-picking a merge commit */
2203 int cnt;
2204 struct commit_list *p;
2206 if (!opts->mainline)
2207 return error(_("commit %s is a merge but no -m option was given."),
2208 oid_to_hex(&commit->object.oid));
2210 for (cnt = 1, p = commit->parents;
2211 cnt != opts->mainline && p;
2212 cnt++)
2213 p = p->next;
2214 if (cnt != opts->mainline || !p)
2215 return error(_("commit %s does not have parent %d"),
2216 oid_to_hex(&commit->object.oid), opts->mainline);
2217 parent = p->item;
2218 } else if (1 < opts->mainline)
2220 * Non-first parent explicitly specified as mainline for
2221 * non-merge commit
2223 return error(_("commit %s does not have parent %d"),
2224 oid_to_hex(&commit->object.oid), opts->mainline);
2225 else
2226 parent = commit->parents->item;
2228 if (get_message(commit, &msg) != 0)
2229 return error(_("cannot get commit message for %s"),
2230 oid_to_hex(&commit->object.oid));
2232 if (opts->allow_ff && !is_fixup(command) &&
2233 ((parent && oideq(&parent->object.oid, &head)) ||
2234 (!parent && unborn))) {
2235 if (is_rebase_i(opts))
2236 write_author_script(msg.message);
2237 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2238 opts);
2239 if (res || command != TODO_REWORD)
2240 goto leave;
2241 reword = 1;
2242 msg_file = NULL;
2243 goto fast_forward_edit;
2245 if (parent && repo_parse_commit(r, parent) < 0)
2246 /* TRANSLATORS: The first %s will be a "todo" command like
2247 "revert" or "pick", the second %s a SHA1. */
2248 return error(_("%s: cannot parse parent commit %s"),
2249 command_to_string(command),
2250 oid_to_hex(&parent->object.oid));
2253 * "commit" is an existing commit. We would want to apply
2254 * the difference it introduces since its first parent "prev"
2255 * on top of the current HEAD if we are cherry-pick. Or the
2256 * reverse of it if we are revert.
2259 if (command == TODO_REVERT) {
2260 base = commit;
2261 base_label = msg.label;
2262 next = parent;
2263 next_label = msg.parent_label;
2264 if (opts->commit_use_reference) {
2265 strbuf_addstr(&msgbuf,
2266 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2267 } else {
2268 strbuf_addstr(&msgbuf, "Revert \"");
2269 strbuf_addstr(&msgbuf, msg.subject);
2270 strbuf_addstr(&msgbuf, "\"");
2272 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2273 refer_to_commit(opts, &msgbuf, commit);
2275 if (commit->parents && commit->parents->next) {
2276 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2277 refer_to_commit(opts, &msgbuf, parent);
2279 strbuf_addstr(&msgbuf, ".\n");
2280 } else {
2281 const char *p;
2283 base = parent;
2284 base_label = msg.parent_label;
2285 next = commit;
2286 next_label = msg.label;
2288 /* Append the commit log message to msgbuf. */
2289 if (find_commit_subject(msg.message, &p))
2290 strbuf_addstr(&msgbuf, p);
2292 if (opts->record_origin) {
2293 strbuf_complete_line(&msgbuf);
2294 if (!has_conforming_footer(&msgbuf, NULL, 0))
2295 strbuf_addch(&msgbuf, '\n');
2296 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2297 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2298 strbuf_addstr(&msgbuf, ")\n");
2300 if (!is_fixup(command))
2301 author = get_author(msg.message);
2304 if (command == TODO_REWORD)
2305 reword = 1;
2306 else if (is_fixup(command)) {
2307 if (update_squash_messages(r, command, commit,
2308 opts, item->flags)) {
2309 res = -1;
2310 goto leave;
2312 flags |= AMEND_MSG;
2313 if (!final_fixup)
2314 msg_file = rebase_path_squash_msg();
2315 else if (file_exists(rebase_path_fixup_msg())) {
2316 flags |= VERBATIM_MSG;
2317 msg_file = rebase_path_fixup_msg();
2318 } else {
2319 const char *dest = git_path_squash_msg(r);
2320 unlink(dest);
2321 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2322 res = error(_("could not copy '%s' to '%s'"),
2323 rebase_path_squash_msg(), dest);
2324 goto leave;
2326 unlink(git_path_merge_msg(r));
2327 msg_file = dest;
2328 flags |= EDIT_MSG;
2332 if (opts->signoff && !is_fixup(command))
2333 append_signoff(&msgbuf, 0, 0);
2335 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2336 res = -1;
2337 else if (!opts->strategy ||
2338 !strcmp(opts->strategy, "recursive") ||
2339 !strcmp(opts->strategy, "ort") ||
2340 command == TODO_REVERT) {
2341 res = do_recursive_merge(r, base, next, base_label, next_label,
2342 &head, &msgbuf, opts);
2343 if (res < 0)
2344 goto leave;
2346 res |= write_message(msgbuf.buf, msgbuf.len,
2347 git_path_merge_msg(r), 0);
2348 } else {
2349 struct commit_list *common = NULL;
2350 struct commit_list *remotes = NULL;
2352 res = write_message(msgbuf.buf, msgbuf.len,
2353 git_path_merge_msg(r), 0);
2355 commit_list_insert(base, &common);
2356 commit_list_insert(next, &remotes);
2357 res |= try_merge_command(r, opts->strategy,
2358 opts->xopts.nr, opts->xopts.v,
2359 common, oid_to_hex(&head), remotes);
2360 free_commit_list(common);
2361 free_commit_list(remotes);
2365 * If the merge was clean or if it failed due to conflict, we write
2366 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2367 * However, if the merge did not even start, then we don't want to
2368 * write it at all.
2370 if ((command == TODO_PICK || command == TODO_REWORD ||
2371 command == TODO_EDIT) && !opts->no_commit &&
2372 (res == 0 || res == 1) &&
2373 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2374 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2375 res = -1;
2376 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2377 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2378 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2379 res = -1;
2381 if (res) {
2382 error(command == TODO_REVERT
2383 ? _("could not revert %s... %s")
2384 : _("could not apply %s... %s"),
2385 short_commit_name(r, commit), msg.subject);
2386 print_advice(r, res == 1, opts);
2387 repo_rerere(r, opts->allow_rerere_auto);
2388 goto leave;
2391 drop_commit = 0;
2392 allow = allow_empty(r, opts, commit);
2393 if (allow < 0) {
2394 res = allow;
2395 goto leave;
2396 } else if (allow == 1) {
2397 flags |= ALLOW_EMPTY;
2398 } else if (allow == 2) {
2399 drop_commit = 1;
2400 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2401 NULL, 0);
2402 unlink(git_path_merge_msg(r));
2403 unlink(git_path_auto_merge(r));
2404 fprintf(stderr,
2405 _("dropping %s %s -- patch contents already upstream\n"),
2406 oid_to_hex(&commit->object.oid), msg.subject);
2407 } /* else allow == 0 and there's nothing special to do */
2408 if (!opts->no_commit && !drop_commit) {
2409 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2410 res = do_commit(r, msg_file, author, opts, flags,
2411 commit? &commit->object.oid : NULL);
2412 else
2413 res = error(_("unable to parse commit author"));
2414 *check_todo = !!(flags & EDIT_MSG);
2415 if (!res && reword) {
2416 fast_forward_edit:
2417 res = run_git_commit(NULL, opts, EDIT_MSG |
2418 VERIFY_MSG | AMEND_MSG |
2419 (flags & ALLOW_EMPTY));
2420 *check_todo = 1;
2425 if (!res && final_fixup) {
2426 unlink(rebase_path_fixup_msg());
2427 unlink(rebase_path_squash_msg());
2428 unlink(rebase_path_current_fixups());
2429 strbuf_reset(&opts->current_fixups);
2430 opts->current_fixup_count = 0;
2433 leave:
2434 free_message(commit, &msg);
2435 free(author);
2436 strbuf_release(&msgbuf);
2437 update_abort_safety_file();
2439 return res;
2442 static int prepare_revs(struct replay_opts *opts)
2445 * picking (but not reverting) ranges (but not individual revisions)
2446 * should be done in reverse
2448 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2449 opts->revs->reverse ^= 1;
2451 if (prepare_revision_walk(opts->revs))
2452 return error(_("revision walk setup failed"));
2454 return 0;
2457 static int read_and_refresh_cache(struct repository *r,
2458 struct replay_opts *opts)
2460 struct lock_file index_lock = LOCK_INIT;
2461 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2462 if (repo_read_index(r) < 0) {
2463 rollback_lock_file(&index_lock);
2464 return error(_("git %s: failed to read the index"),
2465 action_name(opts));
2467 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2469 if (index_fd >= 0) {
2470 if (write_locked_index(r->index, &index_lock,
2471 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2472 return error(_("git %s: failed to refresh the index"),
2473 action_name(opts));
2478 * If we are resolving merges in any way other than "ort", then
2479 * expand the sparse index.
2481 if (opts->strategy && strcmp(opts->strategy, "ort"))
2482 ensure_full_index(r->index);
2483 return 0;
2486 void todo_list_release(struct todo_list *todo_list)
2488 strbuf_release(&todo_list->buf);
2489 FREE_AND_NULL(todo_list->items);
2490 todo_list->nr = todo_list->alloc = 0;
2493 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2495 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2496 return todo_list->items + todo_list->nr++;
2499 const char *todo_item_get_arg(struct todo_list *todo_list,
2500 struct todo_item *item)
2502 return todo_list->buf.buf + item->arg_offset;
2505 static int is_command(enum todo_command command, const char **bol)
2507 const char *str = todo_command_info[command].str;
2508 const char nick = todo_command_info[command].c;
2509 const char *p = *bol;
2511 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2512 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2513 (*bol = p);
2516 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2518 switch (command) {
2519 case TODO_LABEL:
2521 * '#' is not a valid label as the merge command uses it to
2522 * separate merge parents from the commit subject.
2524 if (!strcmp(arg, "#") ||
2525 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2526 return error(_("'%s' is not a valid label"), arg);
2527 break;
2529 case TODO_UPDATE_REF:
2530 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2531 return error(_("'%s' is not a valid refname"), arg);
2532 if (check_refname_format(arg, 0))
2533 return error(_("update-ref requires a fully qualified "
2534 "refname e.g. refs/heads/%s"), arg);
2535 break;
2537 default:
2538 BUG("unexpected todo_command");
2541 return 0;
2544 static int parse_insn_line(struct repository *r, struct todo_item *item,
2545 const char *buf, const char *bol, char *eol)
2547 struct object_id commit_oid;
2548 char *end_of_object_name;
2549 int i, saved, status, padding;
2551 item->flags = 0;
2553 /* left-trim */
2554 bol += strspn(bol, " \t");
2556 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2557 item->command = TODO_COMMENT;
2558 item->commit = NULL;
2559 item->arg_offset = bol - buf;
2560 item->arg_len = eol - bol;
2561 return 0;
2564 for (i = 0; i < TODO_COMMENT; i++)
2565 if (is_command(i, &bol)) {
2566 item->command = i;
2567 break;
2569 if (i >= TODO_COMMENT)
2570 return error(_("invalid command '%.*s'"),
2571 (int)strcspn(bol, " \t\r\n"), bol);
2573 /* Eat up extra spaces/ tabs before object name */
2574 padding = strspn(bol, " \t");
2575 bol += padding;
2577 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2578 if (bol != eol)
2579 return error(_("%s does not accept arguments: '%s'"),
2580 command_to_string(item->command), bol);
2581 item->commit = NULL;
2582 item->arg_offset = bol - buf;
2583 item->arg_len = eol - bol;
2584 return 0;
2587 if (!padding)
2588 return error(_("missing arguments for %s"),
2589 command_to_string(item->command));
2591 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2592 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2593 int ret = 0;
2595 item->commit = NULL;
2596 item->arg_offset = bol - buf;
2597 item->arg_len = (int)(eol - bol);
2598 if (item->command == TODO_LABEL ||
2599 item->command == TODO_UPDATE_REF) {
2600 saved = *eol;
2601 *eol = '\0';
2602 ret = check_label_or_ref_arg(item->command, bol);
2603 *eol = saved;
2605 return ret;
2608 if (item->command == TODO_FIXUP) {
2609 if (skip_prefix(bol, "-C", &bol)) {
2610 bol += strspn(bol, " \t");
2611 item->flags |= TODO_REPLACE_FIXUP_MSG;
2612 } else if (skip_prefix(bol, "-c", &bol)) {
2613 bol += strspn(bol, " \t");
2614 item->flags |= TODO_EDIT_FIXUP_MSG;
2618 if (item->command == TODO_MERGE) {
2619 if (skip_prefix(bol, "-C", &bol))
2620 bol += strspn(bol, " \t");
2621 else if (skip_prefix(bol, "-c", &bol)) {
2622 bol += strspn(bol, " \t");
2623 item->flags |= TODO_EDIT_MERGE_MSG;
2624 } else {
2625 item->flags |= TODO_EDIT_MERGE_MSG;
2626 item->commit = NULL;
2627 item->arg_offset = bol - buf;
2628 item->arg_len = (int)(eol - bol);
2629 return 0;
2633 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2634 saved = *end_of_object_name;
2635 *end_of_object_name = '\0';
2636 status = repo_get_oid(r, bol, &commit_oid);
2637 if (status < 0)
2638 error(_("could not parse '%s'"), bol); /* return later */
2639 *end_of_object_name = saved;
2641 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2642 item->arg_offset = bol - buf;
2643 item->arg_len = (int)(eol - bol);
2645 if (status < 0)
2646 return status;
2648 item->commit = lookup_commit_reference(r, &commit_oid);
2649 return item->commit ? 0 : -1;
2652 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2654 const char *todo_file, *bol;
2655 struct strbuf buf = STRBUF_INIT;
2656 int ret = 0;
2658 todo_file = git_path_todo_file();
2659 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2660 if (errno == ENOENT || errno == ENOTDIR)
2661 return -1;
2662 else
2663 return error_errno("unable to open '%s'", todo_file);
2665 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2666 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2667 *action = REPLAY_PICK;
2668 else if (is_command(TODO_REVERT, &bol) &&
2669 (*bol == ' ' || *bol == '\t'))
2670 *action = REPLAY_REVERT;
2671 else
2672 ret = -1;
2674 strbuf_release(&buf);
2676 return ret;
2679 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2680 struct todo_list *todo_list)
2682 struct todo_item *item;
2683 char *p = buf, *next_p;
2684 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2686 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2688 for (i = 1; *p; i++, p = next_p) {
2689 char *eol = strchrnul(p, '\n');
2691 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2693 if (p != eol && eol[-1] == '\r')
2694 eol--; /* strip Carriage Return */
2696 item = append_new_todo(todo_list);
2697 item->offset_in_buf = p - todo_list->buf.buf;
2698 if (parse_insn_line(r, item, buf, p, eol)) {
2699 res = error(_("invalid line %d: %.*s"),
2700 i, (int)(eol - p), p);
2701 item->command = TODO_COMMENT + 1;
2702 item->arg_offset = p - buf;
2703 item->arg_len = (int)(eol - p);
2704 item->commit = NULL;
2707 if (item->command != TODO_COMMENT)
2708 todo_list->total_nr++;
2710 if (fixup_okay)
2711 ; /* do nothing */
2712 else if (is_fixup(item->command))
2713 res = error(_("cannot '%s' without a previous commit"),
2714 command_to_string(item->command));
2715 else if (!is_noop(item->command))
2716 fixup_okay = 1;
2719 return res;
2722 static int count_commands(struct todo_list *todo_list)
2724 int count = 0, i;
2726 for (i = 0; i < todo_list->nr; i++)
2727 if (todo_list->items[i].command != TODO_COMMENT)
2728 count++;
2730 return count;
2733 static int get_item_line_offset(struct todo_list *todo_list, int index)
2735 return index < todo_list->nr ?
2736 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2739 static const char *get_item_line(struct todo_list *todo_list, int index)
2741 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2744 static int get_item_line_length(struct todo_list *todo_list, int index)
2746 return get_item_line_offset(todo_list, index + 1)
2747 - get_item_line_offset(todo_list, index);
2750 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2752 int fd;
2753 ssize_t len;
2755 fd = open(path, O_RDONLY);
2756 if (fd < 0)
2757 return error_errno(_("could not open '%s'"), path);
2758 len = strbuf_read(sb, fd, 0);
2759 close(fd);
2760 if (len < 0)
2761 return error(_("could not read '%s'."), path);
2762 return len;
2765 static int have_finished_the_last_pick(void)
2767 struct strbuf buf = STRBUF_INIT;
2768 const char *eol;
2769 const char *todo_path = git_path_todo_file();
2770 int ret = 0;
2772 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2773 if (errno == ENOENT) {
2774 return 0;
2775 } else {
2776 error_errno("unable to open '%s'", todo_path);
2777 return 0;
2780 /* If there is only one line then we are done */
2781 eol = strchr(buf.buf, '\n');
2782 if (!eol || !eol[1])
2783 ret = 1;
2785 strbuf_release(&buf);
2787 return ret;
2790 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2792 struct replay_opts opts = REPLAY_OPTS_INIT;
2793 int need_cleanup = 0;
2795 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2796 if (!refs_delete_ref(get_main_ref_store(r), "",
2797 "CHERRY_PICK_HEAD", NULL, 0) &&
2798 verbose)
2799 warning(_("cancelling a cherry picking in progress"));
2800 opts.action = REPLAY_PICK;
2801 need_cleanup = 1;
2804 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2805 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2806 NULL, 0) &&
2807 verbose)
2808 warning(_("cancelling a revert in progress"));
2809 opts.action = REPLAY_REVERT;
2810 need_cleanup = 1;
2813 unlink(git_path_auto_merge(r));
2815 if (!need_cleanup)
2816 return;
2818 if (!have_finished_the_last_pick())
2819 return;
2821 sequencer_remove_state(&opts);
2824 static void todo_list_write_total_nr(struct todo_list *todo_list)
2826 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2828 if (f) {
2829 fprintf(f, "%d\n", todo_list->total_nr);
2830 fclose(f);
2834 static int read_populate_todo(struct repository *r,
2835 struct todo_list *todo_list,
2836 struct replay_opts *opts)
2838 const char *todo_file = get_todo_path(opts);
2839 int res;
2841 strbuf_reset(&todo_list->buf);
2842 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2843 return -1;
2845 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2846 if (res) {
2847 if (is_rebase_i(opts))
2848 return error(_("please fix this using "
2849 "'git rebase --edit-todo'."));
2850 return error(_("unusable instruction sheet: '%s'"), todo_file);
2853 if (!todo_list->nr &&
2854 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2855 return error(_("no commits parsed."));
2857 if (!is_rebase_i(opts)) {
2858 enum todo_command valid =
2859 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2860 int i;
2862 for (i = 0; i < todo_list->nr; i++)
2863 if (valid == todo_list->items[i].command)
2864 continue;
2865 else if (valid == TODO_PICK)
2866 return error(_("cannot cherry-pick during a revert."));
2867 else
2868 return error(_("cannot revert during a cherry-pick."));
2871 if (is_rebase_i(opts)) {
2872 struct todo_list done = TODO_LIST_INIT;
2874 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2875 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2876 todo_list->done_nr = count_commands(&done);
2877 else
2878 todo_list->done_nr = 0;
2880 todo_list->total_nr = todo_list->done_nr
2881 + count_commands(todo_list);
2882 todo_list_release(&done);
2884 todo_list_write_total_nr(todo_list);
2887 return 0;
2890 static int git_config_string_dup(char **dest,
2891 const char *var, const char *value)
2893 if (!value)
2894 return config_error_nonbool(var);
2895 free(*dest);
2896 *dest = xstrdup(value);
2897 return 0;
2900 static int populate_opts_cb(const char *key, const char *value,
2901 const struct config_context *ctx,
2902 void *data)
2904 struct replay_opts *opts = data;
2905 int error_flag = 1;
2907 if (!value)
2908 error_flag = 0;
2909 else if (!strcmp(key, "options.no-commit"))
2910 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2911 else if (!strcmp(key, "options.edit"))
2912 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2913 else if (!strcmp(key, "options.allow-empty"))
2914 opts->allow_empty =
2915 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2916 else if (!strcmp(key, "options.allow-empty-message"))
2917 opts->allow_empty_message =
2918 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2919 else if (!strcmp(key, "options.keep-redundant-commits"))
2920 opts->keep_redundant_commits =
2921 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2922 else if (!strcmp(key, "options.signoff"))
2923 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2924 else if (!strcmp(key, "options.record-origin"))
2925 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2926 else if (!strcmp(key, "options.allow-ff"))
2927 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2928 else if (!strcmp(key, "options.mainline"))
2929 opts->mainline = git_config_int(key, value, ctx->kvi);
2930 else if (!strcmp(key, "options.strategy"))
2931 git_config_string_dup(&opts->strategy, key, value);
2932 else if (!strcmp(key, "options.gpg-sign"))
2933 git_config_string_dup(&opts->gpg_sign, key, value);
2934 else if (!strcmp(key, "options.strategy-option")) {
2935 strvec_push(&opts->xopts, value);
2936 } else if (!strcmp(key, "options.allow-rerere-auto"))
2937 opts->allow_rerere_auto =
2938 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
2939 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2940 else if (!strcmp(key, "options.default-msg-cleanup")) {
2941 opts->explicit_cleanup = 1;
2942 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2943 } else
2944 return error(_("invalid key: %s"), key);
2946 if (!error_flag)
2947 return error(_("invalid value for '%s': '%s'"), key, value);
2949 return 0;
2952 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2954 int i;
2955 int count;
2956 const char **argv;
2957 char *strategy_opts_string = raw_opts;
2959 if (*strategy_opts_string == ' ')
2960 strategy_opts_string++;
2962 count = split_cmdline(strategy_opts_string, &argv);
2963 if (count < 0)
2964 BUG("could not split '%s': %s", strategy_opts_string,
2965 split_cmdline_strerror(count));
2966 for (i = 0; i < count; i++) {
2967 const char *arg = argv[i];
2969 skip_prefix(arg, "--", &arg);
2970 strvec_push(&opts->xopts, arg);
2972 free(argv);
2975 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2977 strbuf_reset(buf);
2978 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2979 return;
2980 opts->strategy = strbuf_detach(buf, NULL);
2981 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2982 return;
2984 parse_strategy_opts(opts, buf->buf);
2987 static int read_populate_opts(struct replay_opts *opts)
2989 if (is_rebase_i(opts)) {
2990 struct strbuf buf = STRBUF_INIT;
2991 int ret = 0;
2993 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2994 READ_ONELINER_SKIP_IF_EMPTY)) {
2995 if (!starts_with(buf.buf, "-S"))
2996 strbuf_reset(&buf);
2997 else {
2998 free(opts->gpg_sign);
2999 opts->gpg_sign = xstrdup(buf.buf + 2);
3001 strbuf_reset(&buf);
3004 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3005 READ_ONELINER_SKIP_IF_EMPTY)) {
3006 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3007 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3008 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3009 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3010 strbuf_reset(&buf);
3013 if (file_exists(rebase_path_verbose()))
3014 opts->verbose = 1;
3016 if (file_exists(rebase_path_quiet()))
3017 opts->quiet = 1;
3019 if (file_exists(rebase_path_signoff())) {
3020 opts->allow_ff = 0;
3021 opts->signoff = 1;
3024 if (file_exists(rebase_path_cdate_is_adate())) {
3025 opts->allow_ff = 0;
3026 opts->committer_date_is_author_date = 1;
3029 if (file_exists(rebase_path_ignore_date())) {
3030 opts->allow_ff = 0;
3031 opts->ignore_date = 1;
3034 if (file_exists(rebase_path_reschedule_failed_exec()))
3035 opts->reschedule_failed_exec = 1;
3036 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3037 opts->reschedule_failed_exec = 0;
3039 if (file_exists(rebase_path_drop_redundant_commits()))
3040 opts->drop_redundant_commits = 1;
3042 if (file_exists(rebase_path_keep_redundant_commits()))
3043 opts->keep_redundant_commits = 1;
3045 read_strategy_opts(opts, &buf);
3046 strbuf_reset(&buf);
3048 if (read_oneliner(&opts->current_fixups,
3049 rebase_path_current_fixups(),
3050 READ_ONELINER_SKIP_IF_EMPTY)) {
3051 const char *p = opts->current_fixups.buf;
3052 opts->current_fixup_count = 1;
3053 while ((p = strchr(p, '\n'))) {
3054 opts->current_fixup_count++;
3055 p++;
3059 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3060 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3061 ret = error(_("unusable squash-onto"));
3062 goto done_rebase_i;
3064 opts->have_squash_onto = 1;
3067 done_rebase_i:
3068 strbuf_release(&buf);
3069 return ret;
3072 if (!file_exists(git_path_opts_file()))
3073 return 0;
3075 * The function git_parse_source(), called from git_config_from_file(),
3076 * may die() in case of a syntactically incorrect file. We do not care
3077 * about this case, though, because we wrote that file ourselves, so we
3078 * are pretty certain that it is syntactically correct.
3080 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3081 return error(_("malformed options sheet: '%s'"),
3082 git_path_opts_file());
3083 return 0;
3086 static void write_strategy_opts(struct replay_opts *opts)
3088 struct strbuf buf = STRBUF_INIT;
3091 * Quote strategy options so that they can be read correctly
3092 * by split_cmdline().
3094 quote_cmdline(&buf, opts->xopts.v);
3095 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3096 strbuf_release(&buf);
3099 int write_basic_state(struct replay_opts *opts, const char *head_name,
3100 struct commit *onto, const struct object_id *orig_head)
3102 if (head_name)
3103 write_file(rebase_path_head_name(), "%s\n", head_name);
3104 if (onto)
3105 write_file(rebase_path_onto(), "%s\n",
3106 oid_to_hex(&onto->object.oid));
3107 if (orig_head)
3108 write_file(rebase_path_orig_head(), "%s\n",
3109 oid_to_hex(orig_head));
3111 if (opts->quiet)
3112 write_file(rebase_path_quiet(), "%s", "");
3113 if (opts->verbose)
3114 write_file(rebase_path_verbose(), "%s", "");
3115 if (opts->strategy)
3116 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3117 if (opts->xopts.nr > 0)
3118 write_strategy_opts(opts);
3120 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3121 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3122 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3123 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3125 if (opts->gpg_sign)
3126 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3127 if (opts->signoff)
3128 write_file(rebase_path_signoff(), "--signoff\n");
3129 if (opts->drop_redundant_commits)
3130 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3131 if (opts->keep_redundant_commits)
3132 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3133 if (opts->committer_date_is_author_date)
3134 write_file(rebase_path_cdate_is_adate(), "%s", "");
3135 if (opts->ignore_date)
3136 write_file(rebase_path_ignore_date(), "%s", "");
3137 if (opts->reschedule_failed_exec)
3138 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3139 else
3140 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3142 return 0;
3145 static int walk_revs_populate_todo(struct todo_list *todo_list,
3146 struct replay_opts *opts)
3148 enum todo_command command = opts->action == REPLAY_PICK ?
3149 TODO_PICK : TODO_REVERT;
3150 const char *command_string = todo_command_info[command].str;
3151 const char *encoding;
3152 struct commit *commit;
3154 if (prepare_revs(opts))
3155 return -1;
3157 encoding = get_log_output_encoding();
3159 while ((commit = get_revision(opts->revs))) {
3160 struct todo_item *item = append_new_todo(todo_list);
3161 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3162 commit, NULL,
3163 encoding);
3164 const char *subject;
3165 int subject_len;
3167 item->command = command;
3168 item->commit = commit;
3169 item->arg_offset = 0;
3170 item->arg_len = 0;
3171 item->offset_in_buf = todo_list->buf.len;
3172 subject_len = find_commit_subject(commit_buffer, &subject);
3173 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3174 short_commit_name(the_repository, commit),
3175 subject_len, subject);
3176 repo_unuse_commit_buffer(the_repository, commit,
3177 commit_buffer);
3180 if (!todo_list->nr)
3181 return error(_("empty commit set passed"));
3183 return 0;
3186 static int create_seq_dir(struct repository *r)
3188 enum replay_action action;
3189 const char *in_progress_error = NULL;
3190 const char *in_progress_advice = NULL;
3191 unsigned int advise_skip =
3192 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3193 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3195 if (!sequencer_get_last_command(r, &action)) {
3196 switch (action) {
3197 case REPLAY_REVERT:
3198 in_progress_error = _("revert is already in progress");
3199 in_progress_advice =
3200 _("try \"git revert (--continue | %s--abort | --quit)\"");
3201 break;
3202 case REPLAY_PICK:
3203 in_progress_error = _("cherry-pick is already in progress");
3204 in_progress_advice =
3205 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3206 break;
3207 default:
3208 BUG("unexpected action in create_seq_dir");
3211 if (in_progress_error) {
3212 error("%s", in_progress_error);
3213 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3214 advise(in_progress_advice,
3215 advise_skip ? "--skip | " : "");
3216 return -1;
3218 if (mkdir(git_path_seq_dir(), 0777) < 0)
3219 return error_errno(_("could not create sequencer directory '%s'"),
3220 git_path_seq_dir());
3222 return 0;
3225 static int save_head(const char *head)
3227 return write_message(head, strlen(head), git_path_head_file(), 1);
3230 static int rollback_is_safe(void)
3232 struct strbuf sb = STRBUF_INIT;
3233 struct object_id expected_head, actual_head;
3235 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3236 strbuf_trim(&sb);
3237 if (get_oid_hex(sb.buf, &expected_head)) {
3238 strbuf_release(&sb);
3239 die(_("could not parse %s"), git_path_abort_safety_file());
3241 strbuf_release(&sb);
3243 else if (errno == ENOENT)
3244 oidclr(&expected_head);
3245 else
3246 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3248 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3249 oidclr(&actual_head);
3251 return oideq(&actual_head, &expected_head);
3254 static int reset_merge(const struct object_id *oid)
3256 struct child_process cmd = CHILD_PROCESS_INIT;
3258 cmd.git_cmd = 1;
3259 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3261 if (!is_null_oid(oid))
3262 strvec_push(&cmd.args, oid_to_hex(oid));
3264 return run_command(&cmd);
3267 static int rollback_single_pick(struct repository *r)
3269 struct object_id head_oid;
3271 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3272 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3273 return error(_("no cherry-pick or revert in progress"));
3274 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3275 return error(_("cannot resolve HEAD"));
3276 if (is_null_oid(&head_oid))
3277 return error(_("cannot abort from a branch yet to be born"));
3278 return reset_merge(&head_oid);
3281 static int skip_single_pick(void)
3283 struct object_id head;
3285 if (read_ref_full("HEAD", 0, &head, NULL))
3286 return error(_("cannot resolve HEAD"));
3287 return reset_merge(&head);
3290 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3292 FILE *f;
3293 struct object_id oid;
3294 struct strbuf buf = STRBUF_INIT;
3295 const char *p;
3297 f = fopen(git_path_head_file(), "r");
3298 if (!f && errno == ENOENT) {
3300 * There is no multiple-cherry-pick in progress.
3301 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3302 * a single-cherry-pick in progress, abort that.
3304 return rollback_single_pick(r);
3306 if (!f)
3307 return error_errno(_("cannot open '%s'"), git_path_head_file());
3308 if (strbuf_getline_lf(&buf, f)) {
3309 error(_("cannot read '%s': %s"), git_path_head_file(),
3310 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3311 fclose(f);
3312 goto fail;
3314 fclose(f);
3315 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3316 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3317 git_path_head_file());
3318 goto fail;
3320 if (is_null_oid(&oid)) {
3321 error(_("cannot abort from a branch yet to be born"));
3322 goto fail;
3325 if (!rollback_is_safe()) {
3326 /* Do not error, just do not rollback */
3327 warning(_("You seem to have moved HEAD. "
3328 "Not rewinding, check your HEAD!"));
3329 } else
3330 if (reset_merge(&oid))
3331 goto fail;
3332 strbuf_release(&buf);
3333 return sequencer_remove_state(opts);
3334 fail:
3335 strbuf_release(&buf);
3336 return -1;
3339 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3341 enum replay_action action = -1;
3342 sequencer_get_last_command(r, &action);
3345 * Check whether the subcommand requested to skip the commit is actually
3346 * in progress and that it's safe to skip the commit.
3348 * opts->action tells us which subcommand requested to skip the commit.
3349 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3350 * action is in progress and we can skip the commit.
3352 * Otherwise we check that the last instruction was related to the
3353 * particular subcommand we're trying to execute and barf if that's not
3354 * the case.
3356 * Finally we check that the rollback is "safe", i.e., has the HEAD
3357 * moved? In this case, it doesn't make sense to "reset the merge" and
3358 * "skip the commit" as the user already handled this by committing. But
3359 * we'd not want to barf here, instead give advice on how to proceed. We
3360 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3361 * it gets removed when the user commits, so if it still exists we're
3362 * sure the user can't have committed before.
3364 switch (opts->action) {
3365 case REPLAY_REVERT:
3366 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3367 if (action != REPLAY_REVERT)
3368 return error(_("no revert in progress"));
3369 if (!rollback_is_safe())
3370 goto give_advice;
3372 break;
3373 case REPLAY_PICK:
3374 if (!refs_ref_exists(get_main_ref_store(r),
3375 "CHERRY_PICK_HEAD")) {
3376 if (action != REPLAY_PICK)
3377 return error(_("no cherry-pick in progress"));
3378 if (!rollback_is_safe())
3379 goto give_advice;
3381 break;
3382 default:
3383 BUG("unexpected action in sequencer_skip");
3386 if (skip_single_pick())
3387 return error(_("failed to skip the commit"));
3388 if (!is_directory(git_path_seq_dir()))
3389 return 0;
3391 return sequencer_continue(r, opts);
3393 give_advice:
3394 error(_("there is nothing to skip"));
3396 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3397 advise(_("have you committed already?\n"
3398 "try \"git %s --continue\""),
3399 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3401 return -1;
3404 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3406 struct lock_file todo_lock = LOCK_INIT;
3407 const char *todo_path = get_todo_path(opts);
3408 int next = todo_list->current, offset, fd;
3411 * rebase -i writes "git-rebase-todo" without the currently executing
3412 * command, appending it to "done" instead.
3414 if (is_rebase_i(opts))
3415 next++;
3417 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3418 if (fd < 0)
3419 return error_errno(_("could not lock '%s'"), todo_path);
3420 offset = get_item_line_offset(todo_list, next);
3421 if (write_in_full(fd, todo_list->buf.buf + offset,
3422 todo_list->buf.len - offset) < 0)
3423 return error_errno(_("could not write to '%s'"), todo_path);
3424 if (commit_lock_file(&todo_lock) < 0)
3425 return error(_("failed to finalize '%s'"), todo_path);
3427 if (is_rebase_i(opts) && next > 0) {
3428 const char *done = rebase_path_done();
3429 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3430 int ret = 0;
3432 if (fd < 0)
3433 return 0;
3434 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3435 get_item_line_length(todo_list, next - 1))
3436 < 0)
3437 ret = error_errno(_("could not write to '%s'"), done);
3438 if (close(fd) < 0)
3439 ret = error_errno(_("failed to finalize '%s'"), done);
3440 return ret;
3442 return 0;
3445 static int save_opts(struct replay_opts *opts)
3447 const char *opts_file = git_path_opts_file();
3448 int res = 0;
3450 if (opts->no_commit)
3451 res |= git_config_set_in_file_gently(opts_file,
3452 "options.no-commit", "true");
3453 if (opts->edit >= 0)
3454 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3455 opts->edit ? "true" : "false");
3456 if (opts->allow_empty)
3457 res |= git_config_set_in_file_gently(opts_file,
3458 "options.allow-empty", "true");
3459 if (opts->allow_empty_message)
3460 res |= git_config_set_in_file_gently(opts_file,
3461 "options.allow-empty-message", "true");
3462 if (opts->keep_redundant_commits)
3463 res |= git_config_set_in_file_gently(opts_file,
3464 "options.keep-redundant-commits", "true");
3465 if (opts->signoff)
3466 res |= git_config_set_in_file_gently(opts_file,
3467 "options.signoff", "true");
3468 if (opts->record_origin)
3469 res |= git_config_set_in_file_gently(opts_file,
3470 "options.record-origin", "true");
3471 if (opts->allow_ff)
3472 res |= git_config_set_in_file_gently(opts_file,
3473 "options.allow-ff", "true");
3474 if (opts->mainline) {
3475 struct strbuf buf = STRBUF_INIT;
3476 strbuf_addf(&buf, "%d", opts->mainline);
3477 res |= git_config_set_in_file_gently(opts_file,
3478 "options.mainline", buf.buf);
3479 strbuf_release(&buf);
3481 if (opts->strategy)
3482 res |= git_config_set_in_file_gently(opts_file,
3483 "options.strategy", opts->strategy);
3484 if (opts->gpg_sign)
3485 res |= git_config_set_in_file_gently(opts_file,
3486 "options.gpg-sign", opts->gpg_sign);
3487 for (size_t i = 0; i < opts->xopts.nr; i++)
3488 res |= git_config_set_multivar_in_file_gently(opts_file,
3489 "options.strategy-option",
3490 opts->xopts.v[i], "^$", 0);
3491 if (opts->allow_rerere_auto)
3492 res |= git_config_set_in_file_gently(opts_file,
3493 "options.allow-rerere-auto",
3494 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3495 "true" : "false");
3497 if (opts->explicit_cleanup)
3498 res |= git_config_set_in_file_gently(opts_file,
3499 "options.default-msg-cleanup",
3500 describe_cleanup_mode(opts->default_msg_cleanup));
3501 return res;
3504 static int make_patch(struct repository *r,
3505 struct commit *commit,
3506 struct replay_opts *opts)
3508 struct strbuf buf = STRBUF_INIT;
3509 struct rev_info log_tree_opt;
3510 const char *subject;
3511 char hex[GIT_MAX_HEXSZ + 1];
3512 int res = 0;
3514 oid_to_hex_r(hex, &commit->object.oid);
3515 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3516 return -1;
3517 res |= write_rebase_head(&commit->object.oid);
3519 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3520 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3521 repo_init_revisions(r, &log_tree_opt, NULL);
3522 log_tree_opt.abbrev = 0;
3523 log_tree_opt.diff = 1;
3524 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3525 log_tree_opt.disable_stdin = 1;
3526 log_tree_opt.no_commit_id = 1;
3527 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3528 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3529 if (!log_tree_opt.diffopt.file)
3530 res |= error_errno(_("could not open '%s'"), buf.buf);
3531 else {
3532 res |= log_tree_commit(&log_tree_opt, commit);
3533 fclose(log_tree_opt.diffopt.file);
3535 strbuf_reset(&buf);
3537 strbuf_addf(&buf, "%s/message", get_dir(opts));
3538 if (!file_exists(buf.buf)) {
3539 const char *encoding = get_commit_output_encoding();
3540 const char *commit_buffer = repo_logmsg_reencode(r,
3541 commit, NULL,
3542 encoding);
3543 find_commit_subject(commit_buffer, &subject);
3544 res |= write_message(subject, strlen(subject), buf.buf, 1);
3545 repo_unuse_commit_buffer(r, commit,
3546 commit_buffer);
3548 strbuf_release(&buf);
3549 release_revisions(&log_tree_opt);
3551 return res;
3554 static int intend_to_amend(void)
3556 struct object_id head;
3557 char *p;
3559 if (repo_get_oid(the_repository, "HEAD", &head))
3560 return error(_("cannot read HEAD"));
3562 p = oid_to_hex(&head);
3563 return write_message(p, strlen(p), rebase_path_amend(), 1);
3566 static int error_with_patch(struct repository *r,
3567 struct commit *commit,
3568 const char *subject, int subject_len,
3569 struct replay_opts *opts,
3570 int exit_code, int to_amend)
3572 if (commit) {
3573 if (make_patch(r, commit, opts))
3574 return -1;
3575 } else if (copy_file(rebase_path_message(),
3576 git_path_merge_msg(r), 0666))
3577 return error(_("unable to copy '%s' to '%s'"),
3578 git_path_merge_msg(r), rebase_path_message());
3580 if (to_amend) {
3581 if (intend_to_amend())
3582 return -1;
3584 fprintf(stderr,
3585 _("You can amend the commit now, with\n"
3586 "\n"
3587 " git commit --amend %s\n"
3588 "\n"
3589 "Once you are satisfied with your changes, run\n"
3590 "\n"
3591 " git rebase --continue\n"),
3592 gpg_sign_opt_quoted(opts));
3593 } else if (exit_code) {
3594 if (commit)
3595 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3596 short_commit_name(r, commit), subject_len, subject);
3597 else
3599 * We don't have the hash of the parent so
3600 * just print the line from the todo file.
3602 fprintf_ln(stderr, _("Could not merge %.*s"),
3603 subject_len, subject);
3606 return exit_code;
3609 static int error_failed_squash(struct repository *r,
3610 struct commit *commit,
3611 struct replay_opts *opts,
3612 int subject_len,
3613 const char *subject)
3615 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3616 return error(_("could not copy '%s' to '%s'"),
3617 rebase_path_squash_msg(), rebase_path_message());
3618 unlink(git_path_merge_msg(r));
3619 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3620 return error(_("could not copy '%s' to '%s'"),
3621 rebase_path_message(),
3622 git_path_merge_msg(r));
3623 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3626 static int do_exec(struct repository *r, const char *command_line)
3628 struct child_process cmd = CHILD_PROCESS_INIT;
3629 int dirty, status;
3631 fprintf(stderr, _("Executing: %s\n"), command_line);
3632 cmd.use_shell = 1;
3633 strvec_push(&cmd.args, command_line);
3634 status = run_command(&cmd);
3636 /* force re-reading of the cache */
3637 discard_index(r->index);
3638 if (repo_read_index(r) < 0)
3639 return error(_("could not read index"));
3641 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3643 if (status) {
3644 warning(_("execution failed: %s\n%s"
3645 "You can fix the problem, and then run\n"
3646 "\n"
3647 " git rebase --continue\n"
3648 "\n"),
3649 command_line,
3650 dirty ? _("and made changes to the index and/or the "
3651 "working tree.\n") : "");
3652 if (status == 127)
3653 /* command not found */
3654 status = 1;
3655 } else if (dirty) {
3656 warning(_("execution succeeded: %s\nbut "
3657 "left changes to the index and/or the working tree.\n"
3658 "Commit or stash your changes, and then run\n"
3659 "\n"
3660 " git rebase --continue\n"
3661 "\n"), command_line);
3662 status = 1;
3665 return status;
3668 __attribute__((format (printf, 2, 3)))
3669 static int safe_append(const char *filename, const char *fmt, ...)
3671 va_list ap;
3672 struct lock_file lock = LOCK_INIT;
3673 int fd = hold_lock_file_for_update(&lock, filename,
3674 LOCK_REPORT_ON_ERROR);
3675 struct strbuf buf = STRBUF_INIT;
3677 if (fd < 0)
3678 return -1;
3680 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3681 error_errno(_("could not read '%s'"), filename);
3682 rollback_lock_file(&lock);
3683 return -1;
3685 strbuf_complete(&buf, '\n');
3686 va_start(ap, fmt);
3687 strbuf_vaddf(&buf, fmt, ap);
3688 va_end(ap);
3690 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3691 error_errno(_("could not write to '%s'"), filename);
3692 strbuf_release(&buf);
3693 rollback_lock_file(&lock);
3694 return -1;
3696 if (commit_lock_file(&lock) < 0) {
3697 strbuf_release(&buf);
3698 return error(_("failed to finalize '%s'"), filename);
3701 strbuf_release(&buf);
3702 return 0;
3705 static int do_label(struct repository *r, const char *name, int len)
3707 struct ref_store *refs = get_main_ref_store(r);
3708 struct ref_transaction *transaction;
3709 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3710 struct strbuf msg = STRBUF_INIT;
3711 int ret = 0;
3712 struct object_id head_oid;
3714 if (len == 1 && *name == '#')
3715 return error(_("illegal label name: '%.*s'"), len, name);
3717 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3718 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3720 transaction = ref_store_transaction_begin(refs, &err);
3721 if (!transaction) {
3722 error("%s", err.buf);
3723 ret = -1;
3724 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3725 error(_("could not read HEAD"));
3726 ret = -1;
3727 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3728 NULL, 0, msg.buf, &err) < 0 ||
3729 ref_transaction_commit(transaction, &err)) {
3730 error("%s", err.buf);
3731 ret = -1;
3733 ref_transaction_free(transaction);
3734 strbuf_release(&err);
3735 strbuf_release(&msg);
3737 if (!ret)
3738 ret = safe_append(rebase_path_refs_to_delete(),
3739 "%s\n", ref_name.buf);
3740 strbuf_release(&ref_name);
3742 return ret;
3745 static const char *sequencer_reflog_action(struct replay_opts *opts)
3747 if (!opts->reflog_action) {
3748 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3749 opts->reflog_action =
3750 xstrdup(opts->reflog_action ? opts->reflog_action
3751 : action_name(opts));
3754 return opts->reflog_action;
3757 __attribute__((format (printf, 3, 4)))
3758 static const char *reflog_message(struct replay_opts *opts,
3759 const char *sub_action, const char *fmt, ...)
3761 va_list ap;
3762 static struct strbuf buf = STRBUF_INIT;
3764 va_start(ap, fmt);
3765 strbuf_reset(&buf);
3766 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3767 if (sub_action)
3768 strbuf_addf(&buf, " (%s)", sub_action);
3769 if (fmt) {
3770 strbuf_addstr(&buf, ": ");
3771 strbuf_vaddf(&buf, fmt, ap);
3773 va_end(ap);
3775 return buf.buf;
3778 static struct commit *lookup_label(struct repository *r, const char *label,
3779 int len, struct strbuf *buf)
3781 struct commit *commit;
3782 struct object_id oid;
3784 strbuf_reset(buf);
3785 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3786 if (!read_ref(buf->buf, &oid)) {
3787 commit = lookup_commit_object(r, &oid);
3788 } else {
3789 /* fall back to non-rewritten ref or commit */
3790 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3791 commit = lookup_commit_reference_by_name(buf->buf);
3794 if (!commit)
3795 error(_("could not resolve '%s'"), buf->buf);
3797 return commit;
3800 static int do_reset(struct repository *r,
3801 const char *name, int len,
3802 struct replay_opts *opts)
3804 struct strbuf ref_name = STRBUF_INIT;
3805 struct object_id oid;
3806 struct lock_file lock = LOCK_INIT;
3807 struct tree_desc desc = { 0 };
3808 struct tree *tree;
3809 struct unpack_trees_options unpack_tree_opts = { 0 };
3810 int ret = 0;
3812 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3813 return -1;
3815 if (len == 10 && !strncmp("[new root]", name, len)) {
3816 if (!opts->have_squash_onto) {
3817 const char *hex;
3818 if (commit_tree("", 0, the_hash_algo->empty_tree,
3819 NULL, &opts->squash_onto,
3820 NULL, NULL))
3821 return error(_("writing fake root commit"));
3822 opts->have_squash_onto = 1;
3823 hex = oid_to_hex(&opts->squash_onto);
3824 if (write_message(hex, strlen(hex),
3825 rebase_path_squash_onto(), 0))
3826 return error(_("writing squash-onto"));
3828 oidcpy(&oid, &opts->squash_onto);
3829 } else {
3830 int i;
3831 struct commit *commit;
3833 /* Determine the length of the label */
3834 for (i = 0; i < len; i++)
3835 if (isspace(name[i]))
3836 break;
3837 len = i;
3839 commit = lookup_label(r, name, len, &ref_name);
3840 if (!commit) {
3841 ret = -1;
3842 goto cleanup;
3844 oid = commit->object.oid;
3847 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3848 unpack_tree_opts.head_idx = 1;
3849 unpack_tree_opts.src_index = r->index;
3850 unpack_tree_opts.dst_index = r->index;
3851 unpack_tree_opts.fn = oneway_merge;
3852 unpack_tree_opts.merge = 1;
3853 unpack_tree_opts.update = 1;
3854 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3855 unpack_tree_opts.skip_cache_tree_update = 1;
3856 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3858 if (repo_read_index_unmerged(r)) {
3859 ret = error_resolve_conflict(action_name(opts));
3860 goto cleanup;
3863 if (!fill_tree_descriptor(r, &desc, &oid)) {
3864 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3865 goto cleanup;
3868 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3869 ret = -1;
3870 goto cleanup;
3873 tree = parse_tree_indirect(&oid);
3874 prime_cache_tree(r, r->index, tree);
3876 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3877 ret = error(_("could not write index"));
3879 if (!ret)
3880 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3881 len, name), "HEAD", &oid,
3882 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3883 cleanup:
3884 free((void *)desc.buffer);
3885 if (ret < 0)
3886 rollback_lock_file(&lock);
3887 strbuf_release(&ref_name);
3888 clear_unpack_trees_porcelain(&unpack_tree_opts);
3889 return ret;
3892 static int do_merge(struct repository *r,
3893 struct commit *commit,
3894 const char *arg, int arg_len,
3895 int flags, int *check_todo, struct replay_opts *opts)
3897 int run_commit_flags = 0;
3898 struct strbuf ref_name = STRBUF_INIT;
3899 struct commit *head_commit, *merge_commit, *i;
3900 struct commit_list *bases, *j;
3901 struct commit_list *to_merge = NULL, **tail = &to_merge;
3902 const char *strategy = !opts->xopts.nr &&
3903 (!opts->strategy ||
3904 !strcmp(opts->strategy, "recursive") ||
3905 !strcmp(opts->strategy, "ort")) ?
3906 NULL : opts->strategy;
3907 struct merge_options o;
3908 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3909 static struct lock_file lock;
3910 const char *p;
3912 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3913 ret = -1;
3914 goto leave_merge;
3917 head_commit = lookup_commit_reference_by_name("HEAD");
3918 if (!head_commit) {
3919 ret = error(_("cannot merge without a current revision"));
3920 goto leave_merge;
3924 * For octopus merges, the arg starts with the list of revisions to be
3925 * merged. The list is optionally followed by '#' and the oneline.
3927 merge_arg_len = oneline_offset = arg_len;
3928 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3929 if (!*p)
3930 break;
3931 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3932 p += 1 + strspn(p + 1, " \t\n");
3933 oneline_offset = p - arg;
3934 break;
3936 k = strcspn(p, " \t\n");
3937 if (!k)
3938 continue;
3939 merge_commit = lookup_label(r, p, k, &ref_name);
3940 if (!merge_commit) {
3941 ret = error(_("unable to parse '%.*s'"), k, p);
3942 goto leave_merge;
3944 tail = &commit_list_insert(merge_commit, tail)->next;
3945 p += k;
3946 merge_arg_len = p - arg;
3949 if (!to_merge) {
3950 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3951 goto leave_merge;
3954 if (opts->have_squash_onto &&
3955 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3957 * When the user tells us to "merge" something into a
3958 * "[new root]", let's simply fast-forward to the merge head.
3960 rollback_lock_file(&lock);
3961 if (to_merge->next)
3962 ret = error(_("octopus merge cannot be executed on "
3963 "top of a [new root]"));
3964 else
3965 ret = fast_forward_to(r, &to_merge->item->object.oid,
3966 &head_commit->object.oid, 0,
3967 opts);
3968 goto leave_merge;
3972 * If HEAD is not identical to the first parent of the original merge
3973 * commit, we cannot fast-forward.
3975 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3976 oideq(&commit->parents->item->object.oid,
3977 &head_commit->object.oid);
3980 * If any merge head is different from the original one, we cannot
3981 * fast-forward.
3983 if (can_fast_forward) {
3984 struct commit_list *p = commit->parents->next;
3986 for (j = to_merge; j && p; j = j->next, p = p->next)
3987 if (!oideq(&j->item->object.oid,
3988 &p->item->object.oid)) {
3989 can_fast_forward = 0;
3990 break;
3993 * If the number of merge heads differs from the original merge
3994 * commit, we cannot fast-forward.
3996 if (j || p)
3997 can_fast_forward = 0;
4000 if (can_fast_forward) {
4001 rollback_lock_file(&lock);
4002 ret = fast_forward_to(r, &commit->object.oid,
4003 &head_commit->object.oid, 0, opts);
4004 if (flags & TODO_EDIT_MERGE_MSG)
4005 goto fast_forward_edit;
4007 goto leave_merge;
4010 if (commit) {
4011 const char *encoding = get_commit_output_encoding();
4012 const char *message = repo_logmsg_reencode(r, commit, NULL,
4013 encoding);
4014 const char *body;
4015 int len;
4017 if (!message) {
4018 ret = error(_("could not get commit message of '%s'"),
4019 oid_to_hex(&commit->object.oid));
4020 goto leave_merge;
4022 write_author_script(message);
4023 find_commit_subject(message, &body);
4024 len = strlen(body);
4025 ret = write_message(body, len, git_path_merge_msg(r), 0);
4026 repo_unuse_commit_buffer(r, commit, message);
4027 if (ret) {
4028 error_errno(_("could not write '%s'"),
4029 git_path_merge_msg(r));
4030 goto leave_merge;
4032 } else {
4033 struct strbuf buf = STRBUF_INIT;
4034 int len;
4036 strbuf_addf(&buf, "author %s", git_author_info(0));
4037 write_author_script(buf.buf);
4038 strbuf_reset(&buf);
4040 if (oneline_offset < arg_len) {
4041 p = arg + oneline_offset;
4042 len = arg_len - oneline_offset;
4043 } else {
4044 strbuf_addf(&buf, "Merge %s '%.*s'",
4045 to_merge->next ? "branches" : "branch",
4046 merge_arg_len, arg);
4047 p = buf.buf;
4048 len = buf.len;
4051 ret = write_message(p, len, git_path_merge_msg(r), 0);
4052 strbuf_release(&buf);
4053 if (ret) {
4054 error_errno(_("could not write '%s'"),
4055 git_path_merge_msg(r));
4056 goto leave_merge;
4060 if (strategy || to_merge->next) {
4061 /* Octopus merge */
4062 struct child_process cmd = CHILD_PROCESS_INIT;
4064 if (read_env_script(&cmd.env)) {
4065 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4067 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4068 goto leave_merge;
4071 if (opts->committer_date_is_author_date)
4072 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4073 opts->ignore_date ?
4074 "" :
4075 author_date_from_env(&cmd.env));
4076 if (opts->ignore_date)
4077 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4079 cmd.git_cmd = 1;
4080 strvec_push(&cmd.args, "merge");
4081 strvec_push(&cmd.args, "-s");
4082 if (!strategy)
4083 strvec_push(&cmd.args, "octopus");
4084 else {
4085 strvec_push(&cmd.args, strategy);
4086 for (k = 0; k < opts->xopts.nr; k++)
4087 strvec_pushf(&cmd.args,
4088 "-X%s", opts->xopts.v[k]);
4090 if (!(flags & TODO_EDIT_MERGE_MSG))
4091 strvec_push(&cmd.args, "--no-edit");
4092 else
4093 strvec_push(&cmd.args, "--edit");
4094 strvec_push(&cmd.args, "--no-ff");
4095 strvec_push(&cmd.args, "--no-log");
4096 strvec_push(&cmd.args, "--no-stat");
4097 strvec_push(&cmd.args, "-F");
4098 strvec_push(&cmd.args, git_path_merge_msg(r));
4099 if (opts->gpg_sign)
4100 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4101 else
4102 strvec_push(&cmd.args, "--no-gpg-sign");
4104 /* Add the tips to be merged */
4105 for (j = to_merge; j; j = j->next)
4106 strvec_push(&cmd.args,
4107 oid_to_hex(&j->item->object.oid));
4109 strbuf_release(&ref_name);
4110 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4111 NULL, 0);
4112 rollback_lock_file(&lock);
4114 ret = run_command(&cmd);
4116 /* force re-reading of the cache */
4117 if (!ret) {
4118 discard_index(r->index);
4119 if (repo_read_index(r) < 0)
4120 ret = error(_("could not read index"));
4122 goto leave_merge;
4125 merge_commit = to_merge->item;
4126 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4127 if (bases && oideq(&merge_commit->object.oid,
4128 &bases->item->object.oid)) {
4129 ret = 0;
4130 /* skip merging an ancestor of HEAD */
4131 goto leave_merge;
4134 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4135 git_path_merge_head(r), 0);
4136 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4138 bases = reverse_commit_list(bases);
4140 repo_read_index(r);
4141 init_merge_options(&o, r);
4142 o.branch1 = "HEAD";
4143 o.branch2 = ref_name.buf;
4144 o.buffer_output = 2;
4146 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4148 * TODO: Should use merge_incore_recursive() and
4149 * merge_switch_to_result(), skipping the call to
4150 * merge_switch_to_result() when we don't actually need to
4151 * update the index and working copy immediately.
4153 ret = merge_ort_recursive(&o,
4154 head_commit, merge_commit, bases,
4155 &i);
4156 } else {
4157 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4158 &i);
4160 if (ret <= 0)
4161 fputs(o.obuf.buf, stdout);
4162 strbuf_release(&o.obuf);
4163 if (ret < 0) {
4164 error(_("could not even attempt to merge '%.*s'"),
4165 merge_arg_len, arg);
4166 goto leave_merge;
4169 * The return value of merge_recursive() is 1 on clean, and 0 on
4170 * unclean merge.
4172 * Let's reverse that, so that do_merge() returns 0 upon success and
4173 * 1 upon failed merge (keeping the return value -1 for the cases where
4174 * we will want to reschedule the `merge` command).
4176 ret = !ret;
4178 if (r->index->cache_changed &&
4179 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4180 ret = error(_("merge: Unable to write new index file"));
4181 goto leave_merge;
4184 rollback_lock_file(&lock);
4185 if (ret)
4186 repo_rerere(r, opts->allow_rerere_auto);
4187 else
4189 * In case of problems, we now want to return a positive
4190 * value (a negative one would indicate that the `merge`
4191 * command needs to be rescheduled).
4193 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4194 run_commit_flags);
4196 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4197 fast_forward_edit:
4198 *check_todo = 1;
4199 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4200 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4204 leave_merge:
4205 strbuf_release(&ref_name);
4206 rollback_lock_file(&lock);
4207 free_commit_list(to_merge);
4208 return ret;
4211 static int write_update_refs_state(struct string_list *refs_to_oids)
4213 int result = 0;
4214 struct lock_file lock = LOCK_INIT;
4215 FILE *fp = NULL;
4216 struct string_list_item *item;
4217 char *path;
4219 path = rebase_path_update_refs(the_repository->gitdir);
4221 if (!refs_to_oids->nr) {
4222 if (unlink(path) && errno != ENOENT)
4223 result = error_errno(_("could not unlink: %s"), path);
4224 goto cleanup;
4227 if (safe_create_leading_directories(path)) {
4228 result = error(_("unable to create leading directories of %s"),
4229 path);
4230 goto cleanup;
4233 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4234 result = error(_("another 'rebase' process appears to be running; "
4235 "'%s.lock' already exists"),
4236 path);
4237 goto cleanup;
4240 fp = fdopen_lock_file(&lock, "w");
4241 if (!fp) {
4242 result = error_errno(_("could not open '%s' for writing"), path);
4243 rollback_lock_file(&lock);
4244 goto cleanup;
4247 for_each_string_list_item(item, refs_to_oids) {
4248 struct update_ref_record *rec = item->util;
4249 fprintf(fp, "%s\n%s\n%s\n", item->string,
4250 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4253 result = commit_lock_file(&lock);
4255 cleanup:
4256 free(path);
4257 return result;
4261 * Parse the update-refs file for the current rebase, then remove the
4262 * refs that do not appear in the todo_list (and have not had updated
4263 * values stored) and add refs that are in the todo_list but not
4264 * represented in the update-refs file.
4266 * If there are changes to the update-refs list, then write the new state
4267 * to disk.
4269 void todo_list_filter_update_refs(struct repository *r,
4270 struct todo_list *todo_list)
4272 int i;
4273 int updated = 0;
4274 struct string_list update_refs = STRING_LIST_INIT_DUP;
4276 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4279 * For each item in the update_refs list, if it has no updated
4280 * value and does not appear in the todo_list, then remove it
4281 * from the update_refs list.
4283 for (i = 0; i < update_refs.nr; i++) {
4284 int j;
4285 int found = 0;
4286 const char *ref = update_refs.items[i].string;
4287 size_t reflen = strlen(ref);
4288 struct update_ref_record *rec = update_refs.items[i].util;
4290 /* OID already stored as updated. */
4291 if (!is_null_oid(&rec->after))
4292 continue;
4294 for (j = 0; !found && j < todo_list->nr; j++) {
4295 struct todo_item *item = &todo_list->items[j];
4296 const char *arg = todo_list->buf.buf + item->arg_offset;
4298 if (item->command != TODO_UPDATE_REF)
4299 continue;
4301 if (item->arg_len != reflen ||
4302 strncmp(arg, ref, reflen))
4303 continue;
4305 found = 1;
4308 if (!found) {
4309 free(update_refs.items[i].string);
4310 free(update_refs.items[i].util);
4312 update_refs.nr--;
4313 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4315 updated = 1;
4316 i--;
4321 * For each todo_item, check if its ref is in the update_refs list.
4322 * If not, then add it as an un-updated ref.
4324 for (i = 0; i < todo_list->nr; i++) {
4325 struct todo_item *item = &todo_list->items[i];
4326 const char *arg = todo_list->buf.buf + item->arg_offset;
4327 int j, found = 0;
4329 if (item->command != TODO_UPDATE_REF)
4330 continue;
4332 for (j = 0; !found && j < update_refs.nr; j++) {
4333 const char *ref = update_refs.items[j].string;
4335 found = strlen(ref) == item->arg_len &&
4336 !strncmp(ref, arg, item->arg_len);
4339 if (!found) {
4340 struct string_list_item *inserted;
4341 struct strbuf argref = STRBUF_INIT;
4343 strbuf_add(&argref, arg, item->arg_len);
4344 inserted = string_list_insert(&update_refs, argref.buf);
4345 inserted->util = init_update_ref_record(argref.buf);
4346 strbuf_release(&argref);
4347 updated = 1;
4351 if (updated)
4352 write_update_refs_state(&update_refs);
4353 string_list_clear(&update_refs, 1);
4356 static int do_update_ref(struct repository *r, const char *refname)
4358 struct string_list_item *item;
4359 struct string_list list = STRING_LIST_INIT_DUP;
4361 if (sequencer_get_update_refs_state(r->gitdir, &list))
4362 return -1;
4364 for_each_string_list_item(item, &list) {
4365 if (!strcmp(item->string, refname)) {
4366 struct update_ref_record *rec = item->util;
4367 if (read_ref("HEAD", &rec->after))
4368 return -1;
4369 break;
4373 write_update_refs_state(&list);
4374 string_list_clear(&list, 1);
4375 return 0;
4378 static int do_update_refs(struct repository *r, int quiet)
4380 int res = 0;
4381 struct string_list_item *item;
4382 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4383 struct ref_store *refs = get_main_ref_store(r);
4384 struct strbuf update_msg = STRBUF_INIT;
4385 struct strbuf error_msg = STRBUF_INIT;
4387 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4388 return res;
4390 for_each_string_list_item(item, &refs_to_oids) {
4391 struct update_ref_record *rec = item->util;
4392 int loop_res;
4394 loop_res = refs_update_ref(refs, "rewritten during rebase",
4395 item->string,
4396 &rec->after, &rec->before,
4397 0, UPDATE_REFS_MSG_ON_ERR);
4398 res |= loop_res;
4400 if (quiet)
4401 continue;
4403 if (loop_res)
4404 strbuf_addf(&error_msg, "\t%s\n", item->string);
4405 else
4406 strbuf_addf(&update_msg, "\t%s\n", item->string);
4409 if (!quiet &&
4410 (update_msg.len || error_msg.len)) {
4411 fprintf(stderr,
4412 _("Updated the following refs with %s:\n%s"),
4413 "--update-refs",
4414 update_msg.buf);
4416 if (res)
4417 fprintf(stderr,
4418 _("Failed to update the following refs with %s:\n%s"),
4419 "--update-refs",
4420 error_msg.buf);
4423 string_list_clear(&refs_to_oids, 1);
4424 strbuf_release(&update_msg);
4425 strbuf_release(&error_msg);
4426 return res;
4429 static int is_final_fixup(struct todo_list *todo_list)
4431 int i = todo_list->current;
4433 if (!is_fixup(todo_list->items[i].command))
4434 return 0;
4436 while (++i < todo_list->nr)
4437 if (is_fixup(todo_list->items[i].command))
4438 return 0;
4439 else if (!is_noop(todo_list->items[i].command))
4440 break;
4441 return 1;
4444 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4446 int i;
4448 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4449 if (!is_noop(todo_list->items[i].command))
4450 return todo_list->items[i].command;
4452 return -1;
4455 void create_autostash(struct repository *r, const char *path)
4457 struct strbuf buf = STRBUF_INIT;
4458 struct lock_file lock_file = LOCK_INIT;
4459 int fd;
4461 fd = repo_hold_locked_index(r, &lock_file, 0);
4462 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4463 if (0 <= fd)
4464 repo_update_index_if_able(r, &lock_file);
4465 rollback_lock_file(&lock_file);
4467 if (has_unstaged_changes(r, 1) ||
4468 has_uncommitted_changes(r, 1)) {
4469 struct child_process stash = CHILD_PROCESS_INIT;
4470 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4471 struct object_id oid;
4473 strvec_pushl(&stash.args,
4474 "stash", "create", "autostash", NULL);
4475 stash.git_cmd = 1;
4476 stash.no_stdin = 1;
4477 strbuf_reset(&buf);
4478 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4479 die(_("Cannot autostash"));
4480 strbuf_trim_trailing_newline(&buf);
4481 if (repo_get_oid(r, buf.buf, &oid))
4482 die(_("Unexpected stash response: '%s'"),
4483 buf.buf);
4484 strbuf_reset(&buf);
4485 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4487 if (safe_create_leading_directories_const(path))
4488 die(_("Could not create directory for '%s'"),
4489 path);
4490 write_file(path, "%s", oid_to_hex(&oid));
4491 printf(_("Created autostash: %s\n"), buf.buf);
4492 if (reset_head(r, &ropts) < 0)
4493 die(_("could not reset --hard"));
4494 discard_index(r->index);
4495 if (repo_read_index(r) < 0)
4496 die(_("could not read index"));
4498 strbuf_release(&buf);
4501 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4503 struct child_process child = CHILD_PROCESS_INIT;
4504 int ret = 0;
4506 if (attempt_apply) {
4507 child.git_cmd = 1;
4508 child.no_stdout = 1;
4509 child.no_stderr = 1;
4510 strvec_push(&child.args, "stash");
4511 strvec_push(&child.args, "apply");
4512 strvec_push(&child.args, stash_oid);
4513 ret = run_command(&child);
4516 if (attempt_apply && !ret)
4517 fprintf(stderr, _("Applied autostash.\n"));
4518 else {
4519 struct child_process store = CHILD_PROCESS_INIT;
4521 store.git_cmd = 1;
4522 strvec_push(&store.args, "stash");
4523 strvec_push(&store.args, "store");
4524 strvec_push(&store.args, "-m");
4525 strvec_push(&store.args, "autostash");
4526 strvec_push(&store.args, "-q");
4527 strvec_push(&store.args, stash_oid);
4528 if (run_command(&store))
4529 ret = error(_("cannot store %s"), stash_oid);
4530 else
4531 fprintf(stderr,
4532 _("%s\n"
4533 "Your changes are safe in the stash.\n"
4534 "You can run \"git stash pop\" or"
4535 " \"git stash drop\" at any time.\n"),
4536 attempt_apply ?
4537 _("Applying autostash resulted in conflicts.") :
4538 _("Autostash exists; creating a new stash entry."));
4541 return ret;
4544 static int apply_save_autostash(const char *path, int attempt_apply)
4546 struct strbuf stash_oid = STRBUF_INIT;
4547 int ret = 0;
4549 if (!read_oneliner(&stash_oid, path,
4550 READ_ONELINER_SKIP_IF_EMPTY)) {
4551 strbuf_release(&stash_oid);
4552 return 0;
4554 strbuf_trim(&stash_oid);
4556 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4558 unlink(path);
4559 strbuf_release(&stash_oid);
4560 return ret;
4563 int save_autostash(const char *path)
4565 return apply_save_autostash(path, 0);
4568 int apply_autostash(const char *path)
4570 return apply_save_autostash(path, 1);
4573 int apply_autostash_oid(const char *stash_oid)
4575 return apply_save_autostash_oid(stash_oid, 1);
4578 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4579 const char *onto_name, const struct object_id *onto,
4580 const struct object_id *orig_head)
4582 struct reset_head_opts ropts = {
4583 .oid = onto,
4584 .orig_head = orig_head,
4585 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4586 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4587 .head_msg = reflog_message(opts, "start", "checkout %s",
4588 onto_name),
4589 .default_reflog_action = sequencer_reflog_action(opts)
4591 if (reset_head(r, &ropts)) {
4592 apply_autostash(rebase_path_autostash());
4593 sequencer_remove_state(opts);
4594 return error(_("could not detach HEAD"));
4597 return 0;
4600 static int stopped_at_head(struct repository *r)
4602 struct object_id head;
4603 struct commit *commit;
4604 struct commit_message message;
4606 if (repo_get_oid(r, "HEAD", &head) ||
4607 !(commit = lookup_commit(r, &head)) ||
4608 repo_parse_commit(r, commit) || get_message(commit, &message))
4609 fprintf(stderr, _("Stopped at HEAD\n"));
4610 else {
4611 fprintf(stderr, _("Stopped at %s\n"), message.label);
4612 free_message(commit, &message);
4614 return 0;
4618 static int reread_todo_if_changed(struct repository *r,
4619 struct todo_list *todo_list,
4620 struct replay_opts *opts)
4622 int offset;
4623 struct strbuf buf = STRBUF_INIT;
4625 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4626 return -1;
4627 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4628 if (buf.len != todo_list->buf.len - offset ||
4629 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4630 /* Reread the todo file if it has changed. */
4631 todo_list_release(todo_list);
4632 if (read_populate_todo(r, todo_list, opts))
4633 return -1; /* message was printed */
4634 /* `current` will be incremented on return */
4635 todo_list->current = -1;
4637 strbuf_release(&buf);
4639 return 0;
4642 static const char rescheduled_advice[] =
4643 N_("Could not execute the todo command\n"
4644 "\n"
4645 " %.*s"
4646 "\n"
4647 "It has been rescheduled; To edit the command before continuing, please\n"
4648 "edit the todo list first:\n"
4649 "\n"
4650 " git rebase --edit-todo\n"
4651 " git rebase --continue\n");
4653 static int pick_commits(struct repository *r,
4654 struct todo_list *todo_list,
4655 struct replay_opts *opts)
4657 int res = 0, reschedule = 0;
4659 opts->reflog_message = sequencer_reflog_action(opts);
4660 if (opts->allow_ff)
4661 assert(!(opts->signoff || opts->no_commit ||
4662 opts->record_origin || should_edit(opts) ||
4663 opts->committer_date_is_author_date ||
4664 opts->ignore_date));
4665 if (read_and_refresh_cache(r, opts))
4666 return -1;
4668 while (todo_list->current < todo_list->nr) {
4669 struct todo_item *item = todo_list->items + todo_list->current;
4670 const char *arg = todo_item_get_arg(todo_list, item);
4671 int check_todo = 0;
4673 if (save_todo(todo_list, opts))
4674 return -1;
4675 if (is_rebase_i(opts)) {
4676 if (item->command != TODO_COMMENT) {
4677 FILE *f = fopen(rebase_path_msgnum(), "w");
4679 todo_list->done_nr++;
4681 if (f) {
4682 fprintf(f, "%d\n", todo_list->done_nr);
4683 fclose(f);
4685 if (!opts->quiet)
4686 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4687 todo_list->done_nr,
4688 todo_list->total_nr,
4689 opts->verbose ? "\n" : "\r");
4691 unlink(rebase_path_message());
4692 unlink(rebase_path_author_script());
4693 unlink(rebase_path_stopped_sha());
4694 unlink(rebase_path_amend());
4695 unlink(git_path_merge_head(r));
4696 unlink(git_path_auto_merge(r));
4697 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4699 if (item->command == TODO_BREAK) {
4700 if (!opts->verbose)
4701 term_clear_line();
4702 return stopped_at_head(r);
4705 if (item->command <= TODO_SQUASH) {
4706 if (is_rebase_i(opts))
4707 opts->reflog_message = reflog_message(opts,
4708 command_to_string(item->command), NULL);
4710 res = do_pick_commit(r, item, opts,
4711 is_final_fixup(todo_list),
4712 &check_todo);
4713 if (is_rebase_i(opts) && res < 0) {
4714 /* Reschedule */
4715 advise(_(rescheduled_advice),
4716 get_item_line_length(todo_list,
4717 todo_list->current),
4718 get_item_line(todo_list,
4719 todo_list->current));
4720 todo_list->current--;
4721 if (save_todo(todo_list, opts))
4722 return -1;
4724 if (item->command == TODO_EDIT) {
4725 struct commit *commit = item->commit;
4726 if (!res) {
4727 if (!opts->verbose)
4728 term_clear_line();
4729 fprintf(stderr,
4730 _("Stopped at %s... %.*s\n"),
4731 short_commit_name(r, commit),
4732 item->arg_len, arg);
4734 return error_with_patch(r, commit,
4735 arg, item->arg_len, opts, res, !res);
4737 if (is_rebase_i(opts) && !res)
4738 record_in_rewritten(&item->commit->object.oid,
4739 peek_command(todo_list, 1));
4740 if (res && is_fixup(item->command)) {
4741 if (res == 1)
4742 intend_to_amend();
4743 return error_failed_squash(r, item->commit, opts,
4744 item->arg_len, arg);
4745 } else if (res && is_rebase_i(opts) && item->commit) {
4746 int to_amend = 0;
4747 struct object_id oid;
4750 * If we are rewording and have either
4751 * fast-forwarded already, or are about to
4752 * create a new root commit, we want to amend,
4753 * otherwise we do not.
4755 if (item->command == TODO_REWORD &&
4756 !repo_get_oid(r, "HEAD", &oid) &&
4757 (oideq(&item->commit->object.oid, &oid) ||
4758 (opts->have_squash_onto &&
4759 oideq(&opts->squash_onto, &oid))))
4760 to_amend = 1;
4762 return res | error_with_patch(r, item->commit,
4763 arg, item->arg_len, opts,
4764 res, to_amend);
4766 } else if (item->command == TODO_EXEC) {
4767 char *end_of_arg = (char *)(arg + item->arg_len);
4768 int saved = *end_of_arg;
4770 if (!opts->verbose)
4771 term_clear_line();
4772 *end_of_arg = '\0';
4773 res = do_exec(r, arg);
4774 *end_of_arg = saved;
4776 if (res) {
4777 if (opts->reschedule_failed_exec)
4778 reschedule = 1;
4780 check_todo = 1;
4781 } else if (item->command == TODO_LABEL) {
4782 if ((res = do_label(r, arg, item->arg_len)))
4783 reschedule = 1;
4784 } else if (item->command == TODO_RESET) {
4785 if ((res = do_reset(r, arg, item->arg_len, opts)))
4786 reschedule = 1;
4787 } else if (item->command == TODO_MERGE) {
4788 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4789 item->flags, &check_todo, opts)) < 0)
4790 reschedule = 1;
4791 else if (item->commit)
4792 record_in_rewritten(&item->commit->object.oid,
4793 peek_command(todo_list, 1));
4794 if (res > 0)
4795 /* failed with merge conflicts */
4796 return error_with_patch(r, item->commit,
4797 arg, item->arg_len,
4798 opts, res, 0);
4799 } else if (item->command == TODO_UPDATE_REF) {
4800 struct strbuf ref = STRBUF_INIT;
4801 strbuf_add(&ref, arg, item->arg_len);
4802 if ((res = do_update_ref(r, ref.buf)))
4803 reschedule = 1;
4804 strbuf_release(&ref);
4805 } else if (!is_noop(item->command))
4806 return error(_("unknown command %d"), item->command);
4808 if (reschedule) {
4809 advise(_(rescheduled_advice),
4810 get_item_line_length(todo_list,
4811 todo_list->current),
4812 get_item_line(todo_list, todo_list->current));
4813 todo_list->current--;
4814 if (save_todo(todo_list, opts))
4815 return -1;
4816 if (item->commit)
4817 return error_with_patch(r,
4818 item->commit,
4819 arg, item->arg_len,
4820 opts, res, 0);
4821 } else if (is_rebase_i(opts) && check_todo && !res &&
4822 reread_todo_if_changed(r, todo_list, opts)) {
4823 return -1;
4826 todo_list->current++;
4827 if (res)
4828 return res;
4831 if (is_rebase_i(opts)) {
4832 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4833 struct stat st;
4835 /* Stopped in the middle, as planned? */
4836 if (todo_list->current < todo_list->nr)
4837 return 0;
4839 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4840 starts_with(head_ref.buf, "refs/")) {
4841 const char *msg;
4842 struct object_id head, orig;
4843 int res;
4845 if (repo_get_oid(r, "HEAD", &head)) {
4846 res = error(_("cannot read HEAD"));
4847 cleanup_head_ref:
4848 strbuf_release(&head_ref);
4849 strbuf_release(&buf);
4850 return res;
4852 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4853 get_oid_hex(buf.buf, &orig)) {
4854 res = error(_("could not read orig-head"));
4855 goto cleanup_head_ref;
4857 strbuf_reset(&buf);
4858 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4859 res = error(_("could not read 'onto'"));
4860 goto cleanup_head_ref;
4862 msg = reflog_message(opts, "finish", "%s onto %s",
4863 head_ref.buf, buf.buf);
4864 if (update_ref(msg, head_ref.buf, &head, &orig,
4865 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4866 res = error(_("could not update %s"),
4867 head_ref.buf);
4868 goto cleanup_head_ref;
4870 msg = reflog_message(opts, "finish", "returning to %s",
4871 head_ref.buf);
4872 if (create_symref("HEAD", head_ref.buf, msg)) {
4873 res = error(_("could not update HEAD to %s"),
4874 head_ref.buf);
4875 goto cleanup_head_ref;
4877 strbuf_reset(&buf);
4880 if (opts->verbose) {
4881 struct rev_info log_tree_opt;
4882 struct object_id orig, head;
4884 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4885 repo_init_revisions(r, &log_tree_opt, NULL);
4886 log_tree_opt.diff = 1;
4887 log_tree_opt.diffopt.output_format =
4888 DIFF_FORMAT_DIFFSTAT;
4889 log_tree_opt.disable_stdin = 1;
4891 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4892 !repo_get_oid(r, buf.buf, &orig) &&
4893 !repo_get_oid(r, "HEAD", &head)) {
4894 diff_tree_oid(&orig, &head, "",
4895 &log_tree_opt.diffopt);
4896 log_tree_diff_flush(&log_tree_opt);
4898 release_revisions(&log_tree_opt);
4900 flush_rewritten_pending();
4901 if (!stat(rebase_path_rewritten_list(), &st) &&
4902 st.st_size > 0) {
4903 struct child_process child = CHILD_PROCESS_INIT;
4904 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4906 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4907 child.git_cmd = 1;
4908 strvec_push(&child.args, "notes");
4909 strvec_push(&child.args, "copy");
4910 strvec_push(&child.args, "--for-rewrite=rebase");
4911 /* we don't care if this copying failed */
4912 run_command(&child);
4914 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4915 strvec_push(&hook_opt.args, "rebase");
4916 run_hooks_opt("post-rewrite", &hook_opt);
4918 apply_autostash(rebase_path_autostash());
4920 if (!opts->quiet) {
4921 if (!opts->verbose)
4922 term_clear_line();
4923 fprintf(stderr,
4924 _("Successfully rebased and updated %s.\n"),
4925 head_ref.buf);
4928 strbuf_release(&buf);
4929 strbuf_release(&head_ref);
4931 if (do_update_refs(r, opts->quiet))
4932 return -1;
4936 * Sequence of picks finished successfully; cleanup by
4937 * removing the .git/sequencer directory
4939 return sequencer_remove_state(opts);
4942 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4944 struct child_process cmd = CHILD_PROCESS_INIT;
4946 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4947 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4948 return error(_("no cherry-pick or revert in progress"));
4950 cmd.git_cmd = 1;
4951 strvec_push(&cmd.args, "commit");
4954 * continue_single_pick() handles the case of recovering from a
4955 * conflict. should_edit() doesn't handle that case; for a conflict,
4956 * we want to edit if the user asked for it, or if they didn't specify
4957 * and stdin is a tty.
4959 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4961 * Include --cleanup=strip as well because we don't want the
4962 * "# Conflicts:" messages.
4964 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4966 return run_command(&cmd);
4969 static int commit_staged_changes(struct repository *r,
4970 struct replay_opts *opts,
4971 struct todo_list *todo_list)
4973 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4974 unsigned int final_fixup = 0, is_clean;
4976 if (has_unstaged_changes(r, 1))
4977 return error(_("cannot rebase: You have unstaged changes."));
4979 is_clean = !has_uncommitted_changes(r, 0);
4981 if (file_exists(rebase_path_amend())) {
4982 struct strbuf rev = STRBUF_INIT;
4983 struct object_id head, to_amend;
4985 if (repo_get_oid(r, "HEAD", &head))
4986 return error(_("cannot amend non-existing commit"));
4987 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4988 return error(_("invalid file: '%s'"), rebase_path_amend());
4989 if (get_oid_hex(rev.buf, &to_amend))
4990 return error(_("invalid contents: '%s'"),
4991 rebase_path_amend());
4992 if (!is_clean && !oideq(&head, &to_amend))
4993 return error(_("\nYou have uncommitted changes in your "
4994 "working tree. Please, commit them\n"
4995 "first and then run 'git rebase "
4996 "--continue' again."));
4998 * When skipping a failed fixup/squash, we need to edit the
4999 * commit message, the current fixup list and count, and if it
5000 * was the last fixup/squash in the chain, we need to clean up
5001 * the commit message and if there was a squash, let the user
5002 * edit it.
5004 if (!is_clean || !opts->current_fixup_count)
5005 ; /* this is not the final fixup */
5006 else if (!oideq(&head, &to_amend) ||
5007 !file_exists(rebase_path_stopped_sha())) {
5008 /* was a final fixup or squash done manually? */
5009 if (!is_fixup(peek_command(todo_list, 0))) {
5010 unlink(rebase_path_fixup_msg());
5011 unlink(rebase_path_squash_msg());
5012 unlink(rebase_path_current_fixups());
5013 strbuf_reset(&opts->current_fixups);
5014 opts->current_fixup_count = 0;
5016 } else {
5017 /* we are in a fixup/squash chain */
5018 const char *p = opts->current_fixups.buf;
5019 int len = opts->current_fixups.len;
5021 opts->current_fixup_count--;
5022 if (!len)
5023 BUG("Incorrect current_fixups:\n%s", p);
5024 while (len && p[len - 1] != '\n')
5025 len--;
5026 strbuf_setlen(&opts->current_fixups, len);
5027 if (write_message(p, len, rebase_path_current_fixups(),
5028 0) < 0)
5029 return error(_("could not write file: '%s'"),
5030 rebase_path_current_fixups());
5033 * If a fixup/squash in a fixup/squash chain failed, the
5034 * commit message is already correct, no need to commit
5035 * it again.
5037 * Only if it is the final command in the fixup/squash
5038 * chain, and only if the chain is longer than a single
5039 * fixup/squash command (which was just skipped), do we
5040 * actually need to re-commit with a cleaned up commit
5041 * message.
5043 if (opts->current_fixup_count > 0 &&
5044 !is_fixup(peek_command(todo_list, 0))) {
5045 final_fixup = 1;
5047 * If there was not a single "squash" in the
5048 * chain, we only need to clean up the commit
5049 * message, no need to bother the user with
5050 * opening the commit message in the editor.
5052 if (!starts_with(p, "squash ") &&
5053 !strstr(p, "\nsquash "))
5054 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5055 } else if (is_fixup(peek_command(todo_list, 0))) {
5057 * We need to update the squash message to skip
5058 * the latest commit message.
5060 int res = 0;
5061 struct commit *commit;
5062 const char *msg;
5063 const char *path = rebase_path_squash_msg();
5064 const char *encoding = get_commit_output_encoding();
5066 if (parse_head(r, &commit))
5067 return error(_("could not parse HEAD"));
5069 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5070 if (!p) {
5071 res = error(_("could not parse commit %s"),
5072 oid_to_hex(&commit->object.oid));
5073 goto unuse_commit_buffer;
5075 find_commit_subject(p, &msg);
5076 if (write_message(msg, strlen(msg), path, 0)) {
5077 res = error(_("could not write file: "
5078 "'%s'"), path);
5079 goto unuse_commit_buffer;
5081 unuse_commit_buffer:
5082 repo_unuse_commit_buffer(r, commit, p);
5083 if (res)
5084 return res;
5088 strbuf_release(&rev);
5089 flags |= AMEND_MSG;
5092 if (is_clean) {
5093 if (refs_ref_exists(get_main_ref_store(r),
5094 "CHERRY_PICK_HEAD") &&
5095 refs_delete_ref(get_main_ref_store(r), "",
5096 "CHERRY_PICK_HEAD", NULL, 0))
5097 return error(_("could not remove CHERRY_PICK_HEAD"));
5098 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5099 return error_errno(_("could not remove '%s'"),
5100 git_path_merge_msg(r));
5101 if (!final_fixup)
5102 return 0;
5105 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5106 opts, flags))
5107 return error(_("could not commit staged changes."));
5108 unlink(rebase_path_amend());
5109 unlink(git_path_merge_head(r));
5110 unlink(git_path_auto_merge(r));
5111 if (final_fixup) {
5112 unlink(rebase_path_fixup_msg());
5113 unlink(rebase_path_squash_msg());
5115 if (opts->current_fixup_count > 0) {
5117 * Whether final fixup or not, we just cleaned up the commit
5118 * message...
5120 unlink(rebase_path_current_fixups());
5121 strbuf_reset(&opts->current_fixups);
5122 opts->current_fixup_count = 0;
5124 return 0;
5127 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5129 struct todo_list todo_list = TODO_LIST_INIT;
5130 int res;
5132 if (read_and_refresh_cache(r, opts))
5133 return -1;
5135 if (read_populate_opts(opts))
5136 return -1;
5137 if (is_rebase_i(opts)) {
5138 if ((res = read_populate_todo(r, &todo_list, opts)))
5139 goto release_todo_list;
5141 if (file_exists(rebase_path_dropped())) {
5142 if ((res = todo_list_check_against_backup(r, &todo_list)))
5143 goto release_todo_list;
5145 unlink(rebase_path_dropped());
5148 opts->reflog_message = reflog_message(opts, "continue", NULL);
5149 if (commit_staged_changes(r, opts, &todo_list)) {
5150 res = -1;
5151 goto release_todo_list;
5153 } else if (!file_exists(get_todo_path(opts)))
5154 return continue_single_pick(r, opts);
5155 else if ((res = read_populate_todo(r, &todo_list, opts)))
5156 goto release_todo_list;
5158 if (!is_rebase_i(opts)) {
5159 /* Verify that the conflict has been resolved */
5160 if (refs_ref_exists(get_main_ref_store(r),
5161 "CHERRY_PICK_HEAD") ||
5162 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5163 res = continue_single_pick(r, opts);
5164 if (res)
5165 goto release_todo_list;
5167 if (index_differs_from(r, "HEAD", NULL, 0)) {
5168 res = error_dirty_index(r, opts);
5169 goto release_todo_list;
5171 todo_list.current++;
5172 } else if (file_exists(rebase_path_stopped_sha())) {
5173 struct strbuf buf = STRBUF_INIT;
5174 struct object_id oid;
5176 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5177 READ_ONELINER_SKIP_IF_EMPTY) &&
5178 !get_oid_hex(buf.buf, &oid))
5179 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5180 strbuf_release(&buf);
5183 res = pick_commits(r, &todo_list, opts);
5184 release_todo_list:
5185 todo_list_release(&todo_list);
5186 return res;
5189 static int single_pick(struct repository *r,
5190 struct commit *cmit,
5191 struct replay_opts *opts)
5193 int check_todo;
5194 struct todo_item item;
5196 item.command = opts->action == REPLAY_PICK ?
5197 TODO_PICK : TODO_REVERT;
5198 item.commit = cmit;
5200 opts->reflog_message = sequencer_reflog_action(opts);
5201 return do_pick_commit(r, &item, opts, 0, &check_todo);
5204 int sequencer_pick_revisions(struct repository *r,
5205 struct replay_opts *opts)
5207 struct todo_list todo_list = TODO_LIST_INIT;
5208 struct object_id oid;
5209 int i, res;
5211 assert(opts->revs);
5212 if (read_and_refresh_cache(r, opts))
5213 return -1;
5215 for (i = 0; i < opts->revs->pending.nr; i++) {
5216 struct object_id oid;
5217 const char *name = opts->revs->pending.objects[i].name;
5219 /* This happens when using --stdin. */
5220 if (!strlen(name))
5221 continue;
5223 if (!repo_get_oid(r, name, &oid)) {
5224 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5225 enum object_type type = oid_object_info(r,
5226 &oid,
5227 NULL);
5228 return error(_("%s: can't cherry-pick a %s"),
5229 name, type_name(type));
5231 } else
5232 return error(_("%s: bad revision"), name);
5236 * If we were called as "git cherry-pick <commit>", just
5237 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5238 * REVERT_HEAD, and don't touch the sequencer state.
5239 * This means it is possible to cherry-pick in the middle
5240 * of a cherry-pick sequence.
5242 if (opts->revs->cmdline.nr == 1 &&
5243 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5244 opts->revs->no_walk &&
5245 !opts->revs->cmdline.rev->flags) {
5246 struct commit *cmit;
5247 if (prepare_revision_walk(opts->revs))
5248 return error(_("revision walk setup failed"));
5249 cmit = get_revision(opts->revs);
5250 if (!cmit)
5251 return error(_("empty commit set passed"));
5252 if (get_revision(opts->revs))
5253 BUG("unexpected extra commit from walk");
5254 return single_pick(r, cmit, opts);
5258 * Start a new cherry-pick/ revert sequence; but
5259 * first, make sure that an existing one isn't in
5260 * progress
5263 if (walk_revs_populate_todo(&todo_list, opts) ||
5264 create_seq_dir(r) < 0)
5265 return -1;
5266 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5267 return error(_("can't revert as initial commit"));
5268 if (save_head(oid_to_hex(&oid)))
5269 return -1;
5270 if (save_opts(opts))
5271 return -1;
5272 update_abort_safety_file();
5273 res = pick_commits(r, &todo_list, opts);
5274 todo_list_release(&todo_list);
5275 return res;
5278 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5280 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5281 struct strbuf sob = STRBUF_INIT;
5282 int has_footer;
5284 strbuf_addstr(&sob, sign_off_header);
5285 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5286 strbuf_addch(&sob, '\n');
5288 if (!ignore_footer)
5289 strbuf_complete_line(msgbuf);
5292 * If the whole message buffer is equal to the sob, pretend that we
5293 * found a conforming footer with a matching sob
5295 if (msgbuf->len - ignore_footer == sob.len &&
5296 !strncmp(msgbuf->buf, sob.buf, sob.len))
5297 has_footer = 3;
5298 else
5299 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5301 if (!has_footer) {
5302 const char *append_newlines = NULL;
5303 size_t len = msgbuf->len - ignore_footer;
5305 if (!len) {
5307 * The buffer is completely empty. Leave foom for
5308 * the title and body to be filled in by the user.
5310 append_newlines = "\n\n";
5311 } else if (len == 1) {
5313 * Buffer contains a single newline. Add another
5314 * so that we leave room for the title and body.
5316 append_newlines = "\n";
5317 } else if (msgbuf->buf[len - 2] != '\n') {
5319 * Buffer ends with a single newline. Add another
5320 * so that there is an empty line between the message
5321 * body and the sob.
5323 append_newlines = "\n";
5324 } /* else, the buffer already ends with two newlines. */
5326 if (append_newlines)
5327 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5328 append_newlines, strlen(append_newlines));
5331 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5332 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5333 sob.buf, sob.len);
5335 strbuf_release(&sob);
5338 struct labels_entry {
5339 struct hashmap_entry entry;
5340 char label[FLEX_ARRAY];
5343 static int labels_cmp(const void *fndata UNUSED,
5344 const struct hashmap_entry *eptr,
5345 const struct hashmap_entry *entry_or_key, const void *key)
5347 const struct labels_entry *a, *b;
5349 a = container_of(eptr, const struct labels_entry, entry);
5350 b = container_of(entry_or_key, const struct labels_entry, entry);
5352 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5355 struct string_entry {
5356 struct oidmap_entry entry;
5357 char string[FLEX_ARRAY];
5360 struct label_state {
5361 struct oidmap commit2label;
5362 struct hashmap labels;
5363 struct strbuf buf;
5364 int max_label_length;
5367 static const char *label_oid(struct object_id *oid, const char *label,
5368 struct label_state *state)
5370 struct labels_entry *labels_entry;
5371 struct string_entry *string_entry;
5372 struct object_id dummy;
5373 int i;
5375 string_entry = oidmap_get(&state->commit2label, oid);
5376 if (string_entry)
5377 return string_entry->string;
5380 * For "uninteresting" commits, i.e. commits that are not to be
5381 * rebased, and which can therefore not be labeled, we use a unique
5382 * abbreviation of the commit name. This is slightly more complicated
5383 * than calling repo_find_unique_abbrev() because we also need to make
5384 * sure that the abbreviation does not conflict with any other
5385 * label.
5387 * We disallow "interesting" commits to be labeled by a string that
5388 * is a valid full-length hash, to ensure that we always can find an
5389 * abbreviation for any uninteresting commit's names that does not
5390 * clash with any other label.
5392 strbuf_reset(&state->buf);
5393 if (!label) {
5394 char *p;
5396 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5397 label = p = state->buf.buf;
5399 repo_find_unique_abbrev_r(the_repository, p, oid,
5400 default_abbrev);
5403 * We may need to extend the abbreviated hash so that there is
5404 * no conflicting label.
5406 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5407 size_t i = strlen(p) + 1;
5409 oid_to_hex_r(p, oid);
5410 for (; i < the_hash_algo->hexsz; i++) {
5411 char save = p[i];
5412 p[i] = '\0';
5413 if (!hashmap_get_from_hash(&state->labels,
5414 strihash(p), p))
5415 break;
5416 p[i] = save;
5419 } else {
5420 struct strbuf *buf = &state->buf;
5421 int label_is_utf8 = 1; /* start with this assumption */
5422 size_t max_len = buf->len + state->max_label_length;
5425 * Sanitize labels by replacing non-alpha-numeric characters
5426 * (including white-space ones) by dashes, as they might be
5427 * illegal in file names (and hence in ref names).
5429 * Note that we retain non-ASCII UTF-8 characters (identified
5430 * via the most significant bit). They should be all acceptable
5431 * in file names.
5433 * As we will use the labels as names of (loose) refs, it is
5434 * vital that the name not be longer than the maximum component
5435 * size of the file system (`NAME_MAX`). We are careful to
5436 * truncate the label accordingly, allowing for the `.lock`
5437 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5438 * truncating in the middle of a character).
5440 for (; *label && buf->len + 1 < max_len; label++)
5441 if (isalnum(*label) ||
5442 (!label_is_utf8 && (*label & 0x80)))
5443 strbuf_addch(buf, *label);
5444 else if (*label & 0x80) {
5445 const char *p = label;
5447 utf8_width(&p, NULL);
5448 if (p) {
5449 if (buf->len + (p - label) > max_len)
5450 break;
5451 strbuf_add(buf, label, p - label);
5452 label = p - 1;
5453 } else {
5454 label_is_utf8 = 0;
5455 strbuf_addch(buf, *label);
5457 /* avoid leading dash and double-dashes */
5458 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5459 strbuf_addch(buf, '-');
5460 if (!buf->len) {
5461 strbuf_addstr(buf, "rev-");
5462 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5464 label = buf->buf;
5466 if ((buf->len == the_hash_algo->hexsz &&
5467 !get_oid_hex(label, &dummy)) ||
5468 (buf->len == 1 && *label == '#') ||
5469 hashmap_get_from_hash(&state->labels,
5470 strihash(label), label)) {
5472 * If the label already exists, or if the label is a
5473 * valid full OID, or the label is a '#' (which we use
5474 * as a separator between merge heads and oneline), we
5475 * append a dash and a number to make it unique.
5477 size_t len = buf->len;
5479 for (i = 2; ; i++) {
5480 strbuf_setlen(buf, len);
5481 strbuf_addf(buf, "-%d", i);
5482 if (!hashmap_get_from_hash(&state->labels,
5483 strihash(buf->buf),
5484 buf->buf))
5485 break;
5488 label = buf->buf;
5492 FLEX_ALLOC_STR(labels_entry, label, label);
5493 hashmap_entry_init(&labels_entry->entry, strihash(label));
5494 hashmap_add(&state->labels, &labels_entry->entry);
5496 FLEX_ALLOC_STR(string_entry, string, label);
5497 oidcpy(&string_entry->entry.oid, oid);
5498 oidmap_put(&state->commit2label, string_entry);
5500 return string_entry->string;
5503 static int make_script_with_merges(struct pretty_print_context *pp,
5504 struct rev_info *revs, struct strbuf *out,
5505 unsigned flags)
5507 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5508 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5509 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5510 int skipped_commit = 0;
5511 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5512 struct strbuf label = STRBUF_INIT;
5513 struct commit_list *commits = NULL, **tail = &commits, *iter;
5514 struct commit_list *tips = NULL, **tips_tail = &tips;
5515 struct commit *commit;
5516 struct oidmap commit2todo = OIDMAP_INIT;
5517 struct string_entry *entry;
5518 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5519 shown = OIDSET_INIT;
5520 struct label_state state =
5521 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5523 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5524 const char *cmd_pick = abbr ? "p" : "pick",
5525 *cmd_label = abbr ? "l" : "label",
5526 *cmd_reset = abbr ? "t" : "reset",
5527 *cmd_merge = abbr ? "m" : "merge";
5529 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5531 oidmap_init(&commit2todo, 0);
5532 oidmap_init(&state.commit2label, 0);
5533 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5534 strbuf_init(&state.buf, 32);
5536 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5537 struct labels_entry *onto_label_entry;
5538 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5539 FLEX_ALLOC_STR(entry, string, "onto");
5540 oidcpy(&entry->entry.oid, oid);
5541 oidmap_put(&state.commit2label, entry);
5543 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5544 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5545 hashmap_add(&state.labels, &onto_label_entry->entry);
5549 * First phase:
5550 * - get onelines for all commits
5551 * - gather all branch tips (i.e. 2nd or later parents of merges)
5552 * - label all branch tips
5554 while ((commit = get_revision(revs))) {
5555 struct commit_list *to_merge;
5556 const char *p1, *p2;
5557 struct object_id *oid;
5558 int is_empty;
5560 tail = &commit_list_insert(commit, tail)->next;
5561 oidset_insert(&interesting, &commit->object.oid);
5563 is_empty = is_original_commit_empty(commit);
5564 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5565 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5566 warning(_("skipped previously applied commit %s"),
5567 short_commit_name(the_repository, commit));
5568 skipped_commit = 1;
5569 continue;
5571 if (is_empty && !keep_empty)
5572 continue;
5574 strbuf_reset(&oneline);
5575 pretty_print_commit(pp, commit, &oneline);
5577 to_merge = commit->parents ? commit->parents->next : NULL;
5578 if (!to_merge) {
5579 /* non-merge commit: easy case */
5580 strbuf_reset(&buf);
5581 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5582 oid_to_hex(&commit->object.oid),
5583 oneline.buf);
5584 if (is_empty)
5585 strbuf_addf(&buf, " %c empty",
5586 comment_line_char);
5588 FLEX_ALLOC_STR(entry, string, buf.buf);
5589 oidcpy(&entry->entry.oid, &commit->object.oid);
5590 oidmap_put(&commit2todo, entry);
5592 continue;
5595 /* Create a label */
5596 strbuf_reset(&label);
5597 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5598 (p1 = strchr(p1, '\'')) &&
5599 (p2 = strchr(++p1, '\'')))
5600 strbuf_add(&label, p1, p2 - p1);
5601 else if (skip_prefix(oneline.buf, "Merge pull request ",
5602 &p1) &&
5603 (p1 = strstr(p1, " from ")))
5604 strbuf_addstr(&label, p1 + strlen(" from "));
5605 else
5606 strbuf_addbuf(&label, &oneline);
5608 strbuf_reset(&buf);
5609 strbuf_addf(&buf, "%s -C %s",
5610 cmd_merge, oid_to_hex(&commit->object.oid));
5612 /* label the tips of merged branches */
5613 for (; to_merge; to_merge = to_merge->next) {
5614 oid = &to_merge->item->object.oid;
5615 strbuf_addch(&buf, ' ');
5617 if (!oidset_contains(&interesting, oid)) {
5618 strbuf_addstr(&buf, label_oid(oid, NULL,
5619 &state));
5620 continue;
5623 tips_tail = &commit_list_insert(to_merge->item,
5624 tips_tail)->next;
5626 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5628 strbuf_addf(&buf, " # %s", oneline.buf);
5630 FLEX_ALLOC_STR(entry, string, buf.buf);
5631 oidcpy(&entry->entry.oid, &commit->object.oid);
5632 oidmap_put(&commit2todo, entry);
5634 if (skipped_commit)
5635 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5636 _("use --reapply-cherry-picks to include skipped commits"));
5639 * Second phase:
5640 * - label branch points
5641 * - add HEAD to the branch tips
5643 for (iter = commits; iter; iter = iter->next) {
5644 struct commit_list *parent = iter->item->parents;
5645 for (; parent; parent = parent->next) {
5646 struct object_id *oid = &parent->item->object.oid;
5647 if (!oidset_contains(&interesting, oid))
5648 continue;
5649 if (oidset_insert(&child_seen, oid))
5650 label_oid(oid, "branch-point", &state);
5653 /* Add HEAD as implicit "tip of branch" */
5654 if (!iter->next)
5655 tips_tail = &commit_list_insert(iter->item,
5656 tips_tail)->next;
5660 * Third phase: output the todo list. This is a bit tricky, as we
5661 * want to avoid jumping back and forth between revisions. To
5662 * accomplish that goal, we walk backwards from the branch tips,
5663 * gathering commits not yet shown, reversing the list on the fly,
5664 * then outputting that list (labeling revisions as needed).
5666 strbuf_addf(out, "%s onto\n", cmd_label);
5667 for (iter = tips; iter; iter = iter->next) {
5668 struct commit_list *list = NULL, *iter2;
5670 commit = iter->item;
5671 if (oidset_contains(&shown, &commit->object.oid))
5672 continue;
5673 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5675 if (entry)
5676 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5677 else
5678 strbuf_addch(out, '\n');
5680 while (oidset_contains(&interesting, &commit->object.oid) &&
5681 !oidset_contains(&shown, &commit->object.oid)) {
5682 commit_list_insert(commit, &list);
5683 if (!commit->parents) {
5684 commit = NULL;
5685 break;
5687 commit = commit->parents->item;
5690 if (!commit)
5691 strbuf_addf(out, "%s %s\n", cmd_reset,
5692 rebase_cousins || root_with_onto ?
5693 "onto" : "[new root]");
5694 else {
5695 const char *to = NULL;
5697 entry = oidmap_get(&state.commit2label,
5698 &commit->object.oid);
5699 if (entry)
5700 to = entry->string;
5701 else if (!rebase_cousins)
5702 to = label_oid(&commit->object.oid, NULL,
5703 &state);
5705 if (!to || !strcmp(to, "onto"))
5706 strbuf_addf(out, "%s onto\n", cmd_reset);
5707 else {
5708 strbuf_reset(&oneline);
5709 pretty_print_commit(pp, commit, &oneline);
5710 strbuf_addf(out, "%s %s # %s\n",
5711 cmd_reset, to, oneline.buf);
5715 for (iter2 = list; iter2; iter2 = iter2->next) {
5716 struct object_id *oid = &iter2->item->object.oid;
5717 entry = oidmap_get(&commit2todo, oid);
5718 /* only show if not already upstream */
5719 if (entry)
5720 strbuf_addf(out, "%s\n", entry->string);
5721 entry = oidmap_get(&state.commit2label, oid);
5722 if (entry)
5723 strbuf_addf(out, "%s %s\n",
5724 cmd_label, entry->string);
5725 oidset_insert(&shown, oid);
5728 free_commit_list(list);
5731 free_commit_list(commits);
5732 free_commit_list(tips);
5734 strbuf_release(&label);
5735 strbuf_release(&oneline);
5736 strbuf_release(&buf);
5738 oidmap_free(&commit2todo, 1);
5739 oidmap_free(&state.commit2label, 1);
5740 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5741 strbuf_release(&state.buf);
5743 return 0;
5746 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5747 const char **argv, unsigned flags)
5749 char *format = NULL;
5750 struct pretty_print_context pp = {0};
5751 struct rev_info revs;
5752 struct commit *commit;
5753 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5754 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5755 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5756 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5757 int skipped_commit = 0;
5758 int ret = 0;
5760 repo_init_revisions(r, &revs, NULL);
5761 revs.verbose_header = 1;
5762 if (!rebase_merges)
5763 revs.max_parents = 1;
5764 revs.cherry_mark = !reapply_cherry_picks;
5765 revs.limited = 1;
5766 revs.reverse = 1;
5767 revs.right_only = 1;
5768 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5769 revs.topo_order = 1;
5771 revs.pretty_given = 1;
5772 git_config_get_string("rebase.instructionFormat", &format);
5773 if (!format || !*format) {
5774 free(format);
5775 format = xstrdup("%s");
5777 get_commit_format(format, &revs);
5778 free(format);
5779 pp.fmt = revs.commit_format;
5780 pp.output_encoding = get_log_output_encoding();
5782 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5783 ret = error(_("make_script: unhandled options"));
5784 goto cleanup;
5787 if (prepare_revision_walk(&revs) < 0) {
5788 ret = error(_("make_script: error preparing revisions"));
5789 goto cleanup;
5792 if (rebase_merges) {
5793 ret = make_script_with_merges(&pp, &revs, out, flags);
5794 goto cleanup;
5797 while ((commit = get_revision(&revs))) {
5798 int is_empty = is_original_commit_empty(commit);
5800 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5801 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5802 warning(_("skipped previously applied commit %s"),
5803 short_commit_name(r, commit));
5804 skipped_commit = 1;
5805 continue;
5807 if (is_empty && !keep_empty)
5808 continue;
5809 strbuf_addf(out, "%s %s ", insn,
5810 oid_to_hex(&commit->object.oid));
5811 pretty_print_commit(&pp, commit, out);
5812 if (is_empty)
5813 strbuf_addf(out, " %c empty", comment_line_char);
5814 strbuf_addch(out, '\n');
5816 if (skipped_commit)
5817 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5818 _("use --reapply-cherry-picks to include skipped commits"));
5819 cleanup:
5820 release_revisions(&revs);
5821 return ret;
5825 * Add commands after pick and (series of) squash/fixup commands
5826 * in the todo list.
5828 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5829 struct string_list *commands)
5831 struct strbuf *buf = &todo_list->buf;
5832 size_t base_offset = buf->len;
5833 int i, insert, nr = 0, alloc = 0;
5834 struct todo_item *items = NULL, *base_items = NULL;
5836 CALLOC_ARRAY(base_items, commands->nr);
5837 for (i = 0; i < commands->nr; i++) {
5838 size_t command_len = strlen(commands->items[i].string);
5840 strbuf_addstr(buf, commands->items[i].string);
5841 strbuf_addch(buf, '\n');
5843 base_items[i].command = TODO_EXEC;
5844 base_items[i].offset_in_buf = base_offset;
5845 base_items[i].arg_offset = base_offset;
5846 base_items[i].arg_len = command_len;
5848 base_offset += command_len + 1;
5852 * Insert <commands> after every pick. Here, fixup/squash chains
5853 * are considered part of the pick, so we insert the commands *after*
5854 * those chains if there are any.
5856 * As we insert the exec commands immediately after rearranging
5857 * any fixups and before the user edits the list, a fixup chain
5858 * can never contain comments (any comments are empty picks that
5859 * have been commented out because the user did not specify
5860 * --keep-empty). So, it is safe to insert an exec command
5861 * without looking at the command following a comment.
5863 insert = 0;
5864 for (i = 0; i < todo_list->nr; i++) {
5865 enum todo_command command = todo_list->items[i].command;
5866 if (insert && !is_fixup(command)) {
5867 ALLOC_GROW(items, nr + commands->nr, alloc);
5868 COPY_ARRAY(items + nr, base_items, commands->nr);
5869 nr += commands->nr;
5871 insert = 0;
5874 ALLOC_GROW(items, nr + 1, alloc);
5875 items[nr++] = todo_list->items[i];
5877 if (command == TODO_PICK || command == TODO_MERGE)
5878 insert = 1;
5881 /* insert or append final <commands> */
5882 if (insert) {
5883 ALLOC_GROW(items, nr + commands->nr, alloc);
5884 COPY_ARRAY(items + nr, base_items, commands->nr);
5885 nr += commands->nr;
5888 free(base_items);
5889 FREE_AND_NULL(todo_list->items);
5890 todo_list->items = items;
5891 todo_list->nr = nr;
5892 todo_list->alloc = alloc;
5895 static void todo_list_to_strbuf(struct repository *r,
5896 struct todo_list *todo_list,
5897 struct strbuf *buf, int num, unsigned flags)
5899 struct todo_item *item;
5900 int i, max = todo_list->nr;
5902 if (num > 0 && num < max)
5903 max = num;
5905 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5906 char cmd;
5908 /* if the item is not a command write it and continue */
5909 if (item->command >= TODO_COMMENT) {
5910 strbuf_addf(buf, "%.*s\n", item->arg_len,
5911 todo_item_get_arg(todo_list, item));
5912 continue;
5915 /* add command to the buffer */
5916 cmd = command_to_char(item->command);
5917 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5918 strbuf_addch(buf, cmd);
5919 else
5920 strbuf_addstr(buf, command_to_string(item->command));
5922 /* add commit id */
5923 if (item->commit) {
5924 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5925 short_commit_name(r, item->commit) :
5926 oid_to_hex(&item->commit->object.oid);
5928 if (item->command == TODO_FIXUP) {
5929 if (item->flags & TODO_EDIT_FIXUP_MSG)
5930 strbuf_addstr(buf, " -c");
5931 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5932 strbuf_addstr(buf, " -C");
5936 if (item->command == TODO_MERGE) {
5937 if (item->flags & TODO_EDIT_MERGE_MSG)
5938 strbuf_addstr(buf, " -c");
5939 else
5940 strbuf_addstr(buf, " -C");
5943 strbuf_addf(buf, " %s", oid);
5946 /* add all the rest */
5947 if (!item->arg_len)
5948 strbuf_addch(buf, '\n');
5949 else
5950 strbuf_addf(buf, " %.*s\n", item->arg_len,
5951 todo_item_get_arg(todo_list, item));
5955 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5956 const char *file, const char *shortrevisions,
5957 const char *shortonto, int num, unsigned flags)
5959 int res;
5960 struct strbuf buf = STRBUF_INIT;
5962 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5963 if (flags & TODO_LIST_APPEND_TODO_HELP)
5964 append_todo_help(count_commands(todo_list),
5965 shortrevisions, shortonto, &buf);
5967 res = write_message(buf.buf, buf.len, file, 0);
5968 strbuf_release(&buf);
5970 return res;
5973 /* skip picking commits whose parents are unchanged */
5974 static int skip_unnecessary_picks(struct repository *r,
5975 struct todo_list *todo_list,
5976 struct object_id *base_oid)
5978 struct object_id *parent_oid;
5979 int i;
5981 for (i = 0; i < todo_list->nr; i++) {
5982 struct todo_item *item = todo_list->items + i;
5984 if (item->command >= TODO_NOOP)
5985 continue;
5986 if (item->command != TODO_PICK)
5987 break;
5988 if (repo_parse_commit(r, item->commit)) {
5989 return error(_("could not parse commit '%s'"),
5990 oid_to_hex(&item->commit->object.oid));
5992 if (!item->commit->parents)
5993 break; /* root commit */
5994 if (item->commit->parents->next)
5995 break; /* merge commit */
5996 parent_oid = &item->commit->parents->item->object.oid;
5997 if (!oideq(parent_oid, base_oid))
5998 break;
5999 oidcpy(base_oid, &item->commit->object.oid);
6001 if (i > 0) {
6002 const char *done_path = rebase_path_done();
6004 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6005 error_errno(_("could not write to '%s'"), done_path);
6006 return -1;
6009 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6010 todo_list->nr -= i;
6011 todo_list->current = 0;
6012 todo_list->done_nr += i;
6014 if (is_fixup(peek_command(todo_list, 0)))
6015 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6018 return 0;
6021 struct todo_add_branch_context {
6022 struct todo_item *items;
6023 size_t items_nr;
6024 size_t items_alloc;
6025 struct strbuf *buf;
6026 struct commit *commit;
6027 struct string_list refs_to_oids;
6030 static int add_decorations_to_list(const struct commit *commit,
6031 struct todo_add_branch_context *ctx)
6033 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6034 const char *head_ref = resolve_ref_unsafe("HEAD",
6035 RESOLVE_REF_READING,
6036 NULL,
6037 NULL);
6039 while (decoration) {
6040 struct todo_item *item;
6041 const char *path;
6042 size_t base_offset = ctx->buf->len;
6045 * If the branch is the current HEAD, then it will be
6046 * updated by the default rebase behavior.
6048 if (head_ref && !strcmp(head_ref, decoration->name)) {
6049 decoration = decoration->next;
6050 continue;
6053 ALLOC_GROW(ctx->items,
6054 ctx->items_nr + 1,
6055 ctx->items_alloc);
6056 item = &ctx->items[ctx->items_nr];
6057 memset(item, 0, sizeof(*item));
6059 /* If the branch is checked out, then leave a comment instead. */
6060 if ((path = branch_checked_out(decoration->name))) {
6061 item->command = TODO_COMMENT;
6062 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6063 decoration->name, path);
6064 } else {
6065 struct string_list_item *sti;
6066 item->command = TODO_UPDATE_REF;
6067 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6069 sti = string_list_insert(&ctx->refs_to_oids,
6070 decoration->name);
6071 sti->util = init_update_ref_record(decoration->name);
6074 item->offset_in_buf = base_offset;
6075 item->arg_offset = base_offset;
6076 item->arg_len = ctx->buf->len - base_offset;
6077 ctx->items_nr++;
6079 decoration = decoration->next;
6082 return 0;
6086 * For each 'pick' command, find out if the commit has a decoration in
6087 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6089 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6091 int i, res;
6092 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6093 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6094 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6095 struct decoration_filter decoration_filter = {
6096 .include_ref_pattern = &decorate_refs_include,
6097 .exclude_ref_pattern = &decorate_refs_exclude,
6098 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6100 struct todo_add_branch_context ctx = {
6101 .buf = &todo_list->buf,
6102 .refs_to_oids = STRING_LIST_INIT_DUP,
6105 ctx.items_alloc = 2 * todo_list->nr + 1;
6106 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6108 string_list_append(&decorate_refs_include, "refs/heads/");
6109 load_ref_decorations(&decoration_filter, 0);
6111 for (i = 0; i < todo_list->nr; ) {
6112 struct todo_item *item = &todo_list->items[i];
6114 /* insert ith item into new list */
6115 ALLOC_GROW(ctx.items,
6116 ctx.items_nr + 1,
6117 ctx.items_alloc);
6119 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6121 if (item->commit) {
6122 ctx.commit = item->commit;
6123 add_decorations_to_list(item->commit, &ctx);
6127 res = write_update_refs_state(&ctx.refs_to_oids);
6129 string_list_clear(&ctx.refs_to_oids, 1);
6131 if (res) {
6132 /* we failed, so clean up the new list. */
6133 free(ctx.items);
6134 return res;
6137 free(todo_list->items);
6138 todo_list->items = ctx.items;
6139 todo_list->nr = ctx.items_nr;
6140 todo_list->alloc = ctx.items_alloc;
6142 return 0;
6145 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6146 const char *shortrevisions, const char *onto_name,
6147 struct commit *onto, const struct object_id *orig_head,
6148 struct string_list *commands, unsigned autosquash,
6149 unsigned update_refs,
6150 struct todo_list *todo_list)
6152 char shortonto[GIT_MAX_HEXSZ + 1];
6153 const char *todo_file = rebase_path_todo();
6154 struct todo_list new_todo = TODO_LIST_INIT;
6155 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6156 struct object_id oid = onto->object.oid;
6157 int res;
6159 repo_find_unique_abbrev_r(r, shortonto, &oid,
6160 DEFAULT_ABBREV);
6162 if (buf->len == 0) {
6163 struct todo_item *item = append_new_todo(todo_list);
6164 item->command = TODO_NOOP;
6165 item->commit = NULL;
6166 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6169 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6170 return -1;
6172 if (autosquash && todo_list_rearrange_squash(todo_list))
6173 return -1;
6175 if (commands->nr)
6176 todo_list_add_exec_commands(todo_list, commands);
6178 if (count_commands(todo_list) == 0) {
6179 apply_autostash(rebase_path_autostash());
6180 sequencer_remove_state(opts);
6182 return error(_("nothing to do"));
6185 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6186 shortonto, flags);
6187 if (res == -1)
6188 return -1;
6189 else if (res == -2) {
6190 apply_autostash(rebase_path_autostash());
6191 sequencer_remove_state(opts);
6193 return -1;
6194 } else if (res == -3) {
6195 apply_autostash(rebase_path_autostash());
6196 sequencer_remove_state(opts);
6197 todo_list_release(&new_todo);
6199 return error(_("nothing to do"));
6200 } else if (res == -4) {
6201 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6202 todo_list_release(&new_todo);
6204 return -1;
6207 /* Expand the commit IDs */
6208 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6209 strbuf_swap(&new_todo.buf, &buf2);
6210 strbuf_release(&buf2);
6211 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6212 new_todo.total_nr = 0;
6213 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6214 BUG("invalid todo list after expanding IDs:\n%s",
6215 new_todo.buf.buf);
6217 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6218 todo_list_release(&new_todo);
6219 return error(_("could not skip unnecessary pick commands"));
6222 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6223 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6224 todo_list_release(&new_todo);
6225 return error_errno(_("could not write '%s'"), todo_file);
6228 res = -1;
6230 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6231 goto cleanup;
6233 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6234 goto cleanup;
6236 todo_list_write_total_nr(&new_todo);
6237 res = pick_commits(r, &new_todo, opts);
6239 cleanup:
6240 todo_list_release(&new_todo);
6242 return res;
6245 struct subject2item_entry {
6246 struct hashmap_entry entry;
6247 int i;
6248 char subject[FLEX_ARRAY];
6251 static int subject2item_cmp(const void *fndata UNUSED,
6252 const struct hashmap_entry *eptr,
6253 const struct hashmap_entry *entry_or_key,
6254 const void *key)
6256 const struct subject2item_entry *a, *b;
6258 a = container_of(eptr, const struct subject2item_entry, entry);
6259 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6261 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6264 define_commit_slab(commit_todo_item, struct todo_item *);
6266 static int skip_fixupish(const char *subject, const char **p) {
6267 return skip_prefix(subject, "fixup! ", p) ||
6268 skip_prefix(subject, "amend! ", p) ||
6269 skip_prefix(subject, "squash! ", p);
6273 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6274 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6275 * after the former, and change "pick" to "fixup"/"squash".
6277 * Note that if the config has specified a custom instruction format, each log
6278 * message will have to be retrieved from the commit (as the oneline in the
6279 * script cannot be trusted) in order to normalize the autosquash arrangement.
6281 int todo_list_rearrange_squash(struct todo_list *todo_list)
6283 struct hashmap subject2item;
6284 int rearranged = 0, *next, *tail, i, nr = 0;
6285 char **subjects;
6286 struct commit_todo_item commit_todo;
6287 struct todo_item *items = NULL;
6289 init_commit_todo_item(&commit_todo);
6291 * The hashmap maps onelines to the respective todo list index.
6293 * If any items need to be rearranged, the next[i] value will indicate
6294 * which item was moved directly after the i'th.
6296 * In that case, last[i] will indicate the index of the latest item to
6297 * be moved to appear after the i'th.
6299 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6300 ALLOC_ARRAY(next, todo_list->nr);
6301 ALLOC_ARRAY(tail, todo_list->nr);
6302 ALLOC_ARRAY(subjects, todo_list->nr);
6303 for (i = 0; i < todo_list->nr; i++) {
6304 struct strbuf buf = STRBUF_INIT;
6305 struct todo_item *item = todo_list->items + i;
6306 const char *commit_buffer, *subject, *p;
6307 size_t subject_len;
6308 int i2 = -1;
6309 struct subject2item_entry *entry;
6311 next[i] = tail[i] = -1;
6312 if (!item->commit || item->command == TODO_DROP) {
6313 subjects[i] = NULL;
6314 continue;
6317 if (is_fixup(item->command)) {
6318 clear_commit_todo_item(&commit_todo);
6319 return error(_("the script was already rearranged."));
6322 repo_parse_commit(the_repository, item->commit);
6323 commit_buffer = repo_logmsg_reencode(the_repository,
6324 item->commit, NULL,
6325 "UTF-8");
6326 find_commit_subject(commit_buffer, &subject);
6327 format_subject(&buf, subject, " ");
6328 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6329 repo_unuse_commit_buffer(the_repository, item->commit,
6330 commit_buffer);
6331 if (skip_fixupish(subject, &p)) {
6332 struct commit *commit2;
6334 for (;;) {
6335 while (isspace(*p))
6336 p++;
6337 if (!skip_fixupish(p, &p))
6338 break;
6341 entry = hashmap_get_entry_from_hash(&subject2item,
6342 strhash(p), p,
6343 struct subject2item_entry,
6344 entry);
6345 if (entry)
6346 /* found by title */
6347 i2 = entry->i;
6348 else if (!strchr(p, ' ') &&
6349 (commit2 =
6350 lookup_commit_reference_by_name(p)) &&
6351 *commit_todo_item_at(&commit_todo, commit2))
6352 /* found by commit name */
6353 i2 = *commit_todo_item_at(&commit_todo, commit2)
6354 - todo_list->items;
6355 else {
6356 /* copy can be a prefix of the commit subject */
6357 for (i2 = 0; i2 < i; i2++)
6358 if (subjects[i2] &&
6359 starts_with(subjects[i2], p))
6360 break;
6361 if (i2 == i)
6362 i2 = -1;
6365 if (i2 >= 0) {
6366 rearranged = 1;
6367 if (starts_with(subject, "fixup!")) {
6368 todo_list->items[i].command = TODO_FIXUP;
6369 } else if (starts_with(subject, "amend!")) {
6370 todo_list->items[i].command = TODO_FIXUP;
6371 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6372 } else {
6373 todo_list->items[i].command = TODO_SQUASH;
6375 if (tail[i2] < 0) {
6376 next[i] = next[i2];
6377 next[i2] = i;
6378 } else {
6379 next[i] = next[tail[i2]];
6380 next[tail[i2]] = i;
6382 tail[i2] = i;
6383 } else if (!hashmap_get_from_hash(&subject2item,
6384 strhash(subject), subject)) {
6385 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6386 entry->i = i;
6387 hashmap_entry_init(&entry->entry,
6388 strhash(entry->subject));
6389 hashmap_put(&subject2item, &entry->entry);
6392 *commit_todo_item_at(&commit_todo, item->commit) = item;
6395 if (rearranged) {
6396 ALLOC_ARRAY(items, todo_list->nr);
6398 for (i = 0; i < todo_list->nr; i++) {
6399 enum todo_command command = todo_list->items[i].command;
6400 int cur = i;
6403 * Initially, all commands are 'pick's. If it is a
6404 * fixup or a squash now, we have rearranged it.
6406 if (is_fixup(command))
6407 continue;
6409 while (cur >= 0) {
6410 items[nr++] = todo_list->items[cur];
6411 cur = next[cur];
6415 assert(nr == todo_list->nr);
6416 todo_list->alloc = nr;
6417 FREE_AND_NULL(todo_list->items);
6418 todo_list->items = items;
6421 free(next);
6422 free(tail);
6423 for (i = 0; i < todo_list->nr; i++)
6424 free(subjects[i]);
6425 free(subjects);
6426 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6428 clear_commit_todo_item(&commit_todo);
6430 return 0;
6433 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6435 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6436 struct object_id cherry_pick_head, rebase_head;
6438 if (file_exists(git_path_seq_dir()))
6439 *whence = FROM_CHERRY_PICK_MULTI;
6440 if (file_exists(rebase_path()) &&
6441 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6442 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6443 oideq(&rebase_head, &cherry_pick_head))
6444 *whence = FROM_REBASE_PICK;
6445 else
6446 *whence = FROM_CHERRY_PICK_SINGLE;
6448 return 1;
6451 return 0;
6454 int sequencer_get_update_refs_state(const char *wt_dir,
6455 struct string_list *refs)
6457 int result = 0;
6458 FILE *fp = NULL;
6459 struct strbuf ref = STRBUF_INIT;
6460 struct strbuf hash = STRBUF_INIT;
6461 struct update_ref_record *rec = NULL;
6463 char *path = rebase_path_update_refs(wt_dir);
6465 fp = fopen(path, "r");
6466 if (!fp)
6467 goto cleanup;
6469 while (strbuf_getline(&ref, fp) != EOF) {
6470 struct string_list_item *item;
6472 CALLOC_ARRAY(rec, 1);
6474 if (strbuf_getline(&hash, fp) == EOF ||
6475 get_oid_hex(hash.buf, &rec->before)) {
6476 warning(_("update-refs file at '%s' is invalid"),
6477 path);
6478 result = -1;
6479 goto cleanup;
6482 if (strbuf_getline(&hash, fp) == EOF ||
6483 get_oid_hex(hash.buf, &rec->after)) {
6484 warning(_("update-refs file at '%s' is invalid"),
6485 path);
6486 result = -1;
6487 goto cleanup;
6490 item = string_list_insert(refs, ref.buf);
6491 item->util = rec;
6492 rec = NULL;
6495 cleanup:
6496 if (fp)
6497 fclose(fp);
6498 free(path);
6499 free(rec);
6500 strbuf_release(&ref);
6501 strbuf_release(&hash);
6502 return result;