Merge branch 'fc/completion-colors-do-not-need-prompt-command'
[git.git] / sequencer.c
blob3be23d7ca20510179664fcc58c4a6856e0cbd776
1 #include "cache.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "hex.h"
5 #include "lockfile.h"
6 #include "dir.h"
7 #include "object-store.h"
8 #include "object.h"
9 #include "commit.h"
10 #include "sequencer.h"
11 #include "tag.h"
12 #include "run-command.h"
13 #include "hook.h"
14 #include "exec-cmd.h"
15 #include "utf8.h"
16 #include "cache-tree.h"
17 #include "diff.h"
18 #include "revision.h"
19 #include "rerere.h"
20 #include "merge-ort.h"
21 #include "merge-ort-wrappers.h"
22 #include "refs.h"
23 #include "strvec.h"
24 #include "quote.h"
25 #include "trailer.h"
26 #include "log-tree.h"
27 #include "wt-status.h"
28 #include "hashmap.h"
29 #include "notes-utils.h"
30 #include "sigchain.h"
31 #include "unpack-trees.h"
32 #include "worktree.h"
33 #include "oidmap.h"
34 #include "oidset.h"
35 #include "commit-slab.h"
36 #include "alias.h"
37 #include "commit-reach.h"
38 #include "rebase-interactive.h"
39 #include "reset.h"
40 #include "branch.h"
42 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
44 static const char sign_off_header[] = "Signed-off-by: ";
45 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
47 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
49 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
51 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
52 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
53 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
54 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
56 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
58 * The file containing rebase commands, comments, and empty lines.
59 * This file is created by "git rebase -i" then edited by the user. As
60 * the lines are processed, they are removed from the front of this
61 * file and written to the tail of 'done'.
63 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
64 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
66 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
69 * The rebase command lines that have already been processed. A line
70 * is moved here when it is first handled, before any associated user
71 * actions.
73 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
75 * The file to keep track of how many commands were already processed (e.g.
76 * for the prompt).
78 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
80 * The file to keep track of how many commands are to be processed in total
81 * (e.g. for the prompt).
83 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
85 * The commit message that is planned to be used for any changes that
86 * need to be committed following a user interaction.
88 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
90 * The file into which is accumulated the suggested commit message for
91 * squash/fixup commands. When the first of a series of squash/fixups
92 * is seen, the file is created and the commit message from the
93 * previous commit and from the first squash/fixup commit are written
94 * to it. The commit message for each subsequent squash/fixup commit
95 * is appended to the file as it is processed.
97 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
99 * If the current series of squash/fixups has not yet included a squash
100 * command, then this file exists and holds the commit message of the
101 * original "pick" commit. (If the series ends without a "squash"
102 * command, then this can be used as the commit message of the combined
103 * commit without opening the editor.)
105 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
107 * This file contains the list fixup/squash commands that have been
108 * accumulated into message-fixup or message-squash so far.
110 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
112 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
113 * GIT_AUTHOR_DATE that will be used for the commit that is currently
114 * being rebased.
116 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
118 * When an "edit" rebase command is being processed, the SHA1 of the
119 * commit to be edited is recorded in this file. When "git rebase
120 * --continue" is executed, if there are any staged changes then they
121 * will be amended to the HEAD commit, but only provided the HEAD
122 * commit is still the commit to be edited. When any other rebase
123 * command is processed, this file is deleted.
125 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
127 * When we stop at a given patch via the "edit" command, this file contains
128 * the commit object name of the corresponding patch.
130 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
132 * For the post-rewrite hook, we make a list of rewritten commits and
133 * their new sha1s. The rewritten-pending list keeps the sha1s of
134 * commits that have been processed, but not committed yet,
135 * e.g. because they are waiting for a 'squash' command.
137 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
138 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
139 "rebase-merge/rewritten-pending")
142 * The path of the file containing the OID of the "squash onto" commit, i.e.
143 * the dummy commit used for `reset [new root]`.
145 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
148 * The path of the file listing refs that need to be deleted after the rebase
149 * finishes. This is used by the `label` command to record the need for cleanup.
151 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
154 * The update-refs file stores a list of refs that will be updated at the end
155 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
156 * update the OIDs for the refs in this file, but the refs are not updated
157 * until the end of the rebase sequence.
159 * rebase_path_update_refs() returns the path to this file for a given
160 * worktree directory. For the current worktree, pass the_repository->gitdir.
162 static char *rebase_path_update_refs(const char *wt_git_dir)
164 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
168 * The following files are written by git-rebase just after parsing the
169 * command-line.
171 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
172 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
173 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
174 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
175 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
176 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
177 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
178 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
179 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
180 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
181 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
182 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
183 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
184 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
185 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
186 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
187 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
190 * A 'struct update_refs_record' represents a value in the update-refs
191 * list. We use a string_list to map refs to these (before, after) pairs.
193 struct update_ref_record {
194 struct object_id before;
195 struct object_id after;
198 static struct update_ref_record *init_update_ref_record(const char *ref)
200 struct update_ref_record *rec;
202 CALLOC_ARRAY(rec, 1);
204 oidcpy(&rec->before, null_oid());
205 oidcpy(&rec->after, null_oid());
207 /* This may fail, but that's fine, we will keep the null OID. */
208 read_ref(ref, &rec->before);
210 return rec;
213 static int git_sequencer_config(const char *k, const char *v, void *cb)
215 struct replay_opts *opts = cb;
216 int status;
218 if (!strcmp(k, "commit.cleanup")) {
219 const char *s;
221 status = git_config_string(&s, k, v);
222 if (status)
223 return status;
225 if (!strcmp(s, "verbatim")) {
226 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
227 opts->explicit_cleanup = 1;
228 } else if (!strcmp(s, "whitespace")) {
229 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
230 opts->explicit_cleanup = 1;
231 } else if (!strcmp(s, "strip")) {
232 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
233 opts->explicit_cleanup = 1;
234 } else if (!strcmp(s, "scissors")) {
235 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
236 opts->explicit_cleanup = 1;
237 } else {
238 warning(_("invalid commit message cleanup mode '%s'"),
242 free((char *)s);
243 return status;
246 if (!strcmp(k, "commit.gpgsign")) {
247 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
248 return 0;
251 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
252 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
253 if (ret == 0) {
255 * pull.twohead is allowed to be multi-valued; we only
256 * care about the first value.
258 char *tmp = strchr(opts->default_strategy, ' ');
259 if (tmp)
260 *tmp = '\0';
262 return ret;
265 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
266 opts->commit_use_reference = git_config_bool(k, v);
268 return git_diff_basic_config(k, v, NULL);
271 void sequencer_init_config(struct replay_opts *opts)
273 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
274 git_config(git_sequencer_config, opts);
277 static inline int is_rebase_i(const struct replay_opts *opts)
279 return opts->action == REPLAY_INTERACTIVE_REBASE;
282 static const char *get_dir(const struct replay_opts *opts)
284 if (is_rebase_i(opts))
285 return rebase_path();
286 return git_path_seq_dir();
289 static const char *get_todo_path(const struct replay_opts *opts)
291 if (is_rebase_i(opts))
292 return rebase_path_todo();
293 return git_path_todo_file();
297 * Returns 0 for non-conforming footer
298 * Returns 1 for conforming footer
299 * Returns 2 when sob exists within conforming footer
300 * Returns 3 when sob exists within conforming footer as last entry
302 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
303 size_t ignore_footer)
305 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
306 struct trailer_info info;
307 size_t i;
308 int found_sob = 0, found_sob_last = 0;
309 char saved_char;
311 opts.no_divider = 1;
313 if (ignore_footer) {
314 saved_char = sb->buf[sb->len - ignore_footer];
315 sb->buf[sb->len - ignore_footer] = '\0';
318 trailer_info_get(&info, sb->buf, &opts);
320 if (ignore_footer)
321 sb->buf[sb->len - ignore_footer] = saved_char;
323 if (info.trailer_start == info.trailer_end)
324 return 0;
326 for (i = 0; i < info.trailer_nr; i++)
327 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
328 found_sob = 1;
329 if (i == info.trailer_nr - 1)
330 found_sob_last = 1;
333 trailer_info_release(&info);
335 if (found_sob_last)
336 return 3;
337 if (found_sob)
338 return 2;
339 return 1;
342 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
344 static struct strbuf buf = STRBUF_INIT;
346 strbuf_reset(&buf);
347 if (opts->gpg_sign)
348 sq_quotef(&buf, "-S%s", opts->gpg_sign);
349 return buf.buf;
352 void replay_opts_release(struct replay_opts *opts)
354 free(opts->gpg_sign);
355 free(opts->reflog_action);
356 free(opts->default_strategy);
357 free(opts->strategy);
358 for (size_t i = 0; i < opts->xopts_nr; i++)
359 free(opts->xopts[i]);
360 free(opts->xopts);
361 strbuf_release(&opts->current_fixups);
362 if (opts->revs)
363 release_revisions(opts->revs);
364 free(opts->revs);
367 int sequencer_remove_state(struct replay_opts *opts)
369 struct strbuf buf = STRBUF_INIT;
370 int ret = 0;
372 if (is_rebase_i(opts) &&
373 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
374 char *p = buf.buf;
375 while (*p) {
376 char *eol = strchr(p, '\n');
377 if (eol)
378 *eol = '\0';
379 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
380 warning(_("could not delete '%s'"), p);
381 ret = -1;
383 if (!eol)
384 break;
385 p = eol + 1;
389 strbuf_reset(&buf);
390 strbuf_addstr(&buf, get_dir(opts));
391 if (remove_dir_recursively(&buf, 0))
392 ret = error(_("could not remove '%s'"), buf.buf);
393 strbuf_release(&buf);
395 return ret;
398 static const char *action_name(const struct replay_opts *opts)
400 switch (opts->action) {
401 case REPLAY_REVERT:
402 return N_("revert");
403 case REPLAY_PICK:
404 return N_("cherry-pick");
405 case REPLAY_INTERACTIVE_REBASE:
406 return N_("rebase");
408 die(_("unknown action: %d"), opts->action);
411 struct commit_message {
412 char *parent_label;
413 char *label;
414 char *subject;
415 const char *message;
418 static const char *short_commit_name(struct commit *commit)
420 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
423 static int get_message(struct commit *commit, struct commit_message *out)
425 const char *abbrev, *subject;
426 int subject_len;
428 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
429 abbrev = short_commit_name(commit);
431 subject_len = find_commit_subject(out->message, &subject);
433 out->subject = xmemdupz(subject, subject_len);
434 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
435 out->parent_label = xstrfmt("parent of %s", out->label);
437 return 0;
440 static void free_message(struct commit *commit, struct commit_message *msg)
442 free(msg->parent_label);
443 free(msg->label);
444 free(msg->subject);
445 unuse_commit_buffer(commit, msg->message);
448 static void print_advice(struct repository *r, int show_hint,
449 struct replay_opts *opts)
451 char *msg = getenv("GIT_CHERRY_PICK_HELP");
453 if (msg) {
454 advise("%s\n", msg);
456 * A conflict has occurred but the porcelain
457 * (typically rebase --interactive) wants to take care
458 * of the commit itself so remove CHERRY_PICK_HEAD
460 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
461 NULL, 0);
462 return;
465 if (show_hint) {
466 if (opts->no_commit)
467 advise(_("after resolving the conflicts, mark the corrected paths\n"
468 "with 'git add <paths>' or 'git rm <paths>'"));
469 else if (opts->action == REPLAY_PICK)
470 advise(_("After resolving the conflicts, mark them with\n"
471 "\"git add/rm <pathspec>\", then run\n"
472 "\"git cherry-pick --continue\".\n"
473 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
474 "To abort and get back to the state before \"git cherry-pick\",\n"
475 "run \"git cherry-pick --abort\"."));
476 else if (opts->action == REPLAY_REVERT)
477 advise(_("After resolving the conflicts, mark them with\n"
478 "\"git add/rm <pathspec>\", then run\n"
479 "\"git revert --continue\".\n"
480 "You can instead skip this commit with \"git revert --skip\".\n"
481 "To abort and get back to the state before \"git revert\",\n"
482 "run \"git revert --abort\"."));
483 else
484 BUG("unexpected pick action in print_advice()");
488 static int write_message(const void *buf, size_t len, const char *filename,
489 int append_eol)
491 struct lock_file msg_file = LOCK_INIT;
493 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
494 if (msg_fd < 0)
495 return error_errno(_("could not lock '%s'"), filename);
496 if (write_in_full(msg_fd, buf, len) < 0) {
497 error_errno(_("could not write to '%s'"), filename);
498 rollback_lock_file(&msg_file);
499 return -1;
501 if (append_eol && write(msg_fd, "\n", 1) < 0) {
502 error_errno(_("could not write eol to '%s'"), filename);
503 rollback_lock_file(&msg_file);
504 return -1;
506 if (commit_lock_file(&msg_file) < 0)
507 return error(_("failed to finalize '%s'"), filename);
509 return 0;
512 int read_oneliner(struct strbuf *buf,
513 const char *path, unsigned flags)
515 int orig_len = buf->len;
517 if (strbuf_read_file(buf, path, 0) < 0) {
518 if ((flags & READ_ONELINER_WARN_MISSING) ||
519 (errno != ENOENT && errno != ENOTDIR))
520 warning_errno(_("could not read '%s'"), path);
521 return 0;
524 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
525 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
526 --buf->len;
527 buf->buf[buf->len] = '\0';
530 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
531 return 0;
533 return 1;
536 static struct tree *empty_tree(struct repository *r)
538 return lookup_tree(r, the_hash_algo->empty_tree);
541 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
543 if (repo_read_index_unmerged(repo))
544 return error_resolve_conflict(action_name(opts));
546 error(_("your local changes would be overwritten by %s."),
547 _(action_name(opts)));
549 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
550 advise(_("commit your changes or stash them to proceed."));
551 return -1;
554 static void update_abort_safety_file(void)
556 struct object_id head;
558 /* Do nothing on a single-pick */
559 if (!file_exists(git_path_seq_dir()))
560 return;
562 if (!get_oid("HEAD", &head))
563 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
564 else
565 write_file(git_path_abort_safety_file(), "%s", "");
568 static int fast_forward_to(struct repository *r,
569 const struct object_id *to,
570 const struct object_id *from,
571 int unborn,
572 struct replay_opts *opts)
574 struct ref_transaction *transaction;
575 struct strbuf sb = STRBUF_INIT;
576 struct strbuf err = STRBUF_INIT;
578 repo_read_index(r);
579 if (checkout_fast_forward(r, from, to, 1))
580 return -1; /* the callee should have complained already */
582 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
584 transaction = ref_transaction_begin(&err);
585 if (!transaction ||
586 ref_transaction_update(transaction, "HEAD",
587 to, unborn && !is_rebase_i(opts) ?
588 null_oid() : from,
589 0, sb.buf, &err) ||
590 ref_transaction_commit(transaction, &err)) {
591 ref_transaction_free(transaction);
592 error("%s", err.buf);
593 strbuf_release(&sb);
594 strbuf_release(&err);
595 return -1;
598 strbuf_release(&sb);
599 strbuf_release(&err);
600 ref_transaction_free(transaction);
601 update_abort_safety_file();
602 return 0;
605 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
606 int use_editor)
608 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
609 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
610 COMMIT_MSG_CLEANUP_SPACE;
611 else if (!strcmp(cleanup_arg, "verbatim"))
612 return COMMIT_MSG_CLEANUP_NONE;
613 else if (!strcmp(cleanup_arg, "whitespace"))
614 return COMMIT_MSG_CLEANUP_SPACE;
615 else if (!strcmp(cleanup_arg, "strip"))
616 return COMMIT_MSG_CLEANUP_ALL;
617 else if (!strcmp(cleanup_arg, "scissors"))
618 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
619 COMMIT_MSG_CLEANUP_SPACE;
620 else
621 die(_("Invalid cleanup mode %s"), cleanup_arg);
625 * NB using int rather than enum cleanup_mode to stop clang's
626 * -Wtautological-constant-out-of-range-compare complaining that the comparison
627 * is always true.
629 static const char *describe_cleanup_mode(int cleanup_mode)
631 static const char *modes[] = { "whitespace",
632 "verbatim",
633 "scissors",
634 "strip" };
636 if (cleanup_mode < ARRAY_SIZE(modes))
637 return modes[cleanup_mode];
639 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
642 void append_conflicts_hint(struct index_state *istate,
643 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
645 int i;
647 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
648 strbuf_addch(msgbuf, '\n');
649 wt_status_append_cut_line(msgbuf);
650 strbuf_addch(msgbuf, comment_line_char);
653 strbuf_addch(msgbuf, '\n');
654 strbuf_commented_addf(msgbuf, "Conflicts:\n");
655 for (i = 0; i < istate->cache_nr;) {
656 const struct cache_entry *ce = istate->cache[i++];
657 if (ce_stage(ce)) {
658 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
659 while (i < istate->cache_nr &&
660 !strcmp(ce->name, istate->cache[i]->name))
661 i++;
666 static int do_recursive_merge(struct repository *r,
667 struct commit *base, struct commit *next,
668 const char *base_label, const char *next_label,
669 struct object_id *head, struct strbuf *msgbuf,
670 struct replay_opts *opts)
672 struct merge_options o;
673 struct merge_result result;
674 struct tree *next_tree, *base_tree, *head_tree;
675 int clean, show_output;
676 int i;
677 struct lock_file index_lock = LOCK_INIT;
679 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
680 return -1;
682 repo_read_index(r);
684 init_merge_options(&o, r);
685 o.ancestor = base ? base_label : "(empty tree)";
686 o.branch1 = "HEAD";
687 o.branch2 = next ? next_label : "(empty tree)";
688 if (is_rebase_i(opts))
689 o.buffer_output = 2;
690 o.show_rename_progress = 1;
692 head_tree = parse_tree_indirect(head);
693 next_tree = next ? get_commit_tree(next) : empty_tree(r);
694 base_tree = base ? get_commit_tree(base) : empty_tree(r);
696 for (i = 0; i < opts->xopts_nr; i++)
697 parse_merge_opt(&o, opts->xopts[i]);
699 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
700 memset(&result, 0, sizeof(result));
701 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
702 &result);
703 show_output = !is_rebase_i(opts) || !result.clean;
705 * TODO: merge_switch_to_result will update index/working tree;
706 * we only really want to do that if !result.clean || this is
707 * the final patch to be picked. But determining this is the
708 * final patch would take some work, and "head_tree" would need
709 * to be replace with the tree the index matched before we
710 * started doing any picks.
712 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
713 clean = result.clean;
714 } else {
715 ensure_full_index(r->index);
716 clean = merge_trees(&o, head_tree, next_tree, base_tree);
717 if (is_rebase_i(opts) && clean <= 0)
718 fputs(o.obuf.buf, stdout);
719 strbuf_release(&o.obuf);
721 if (clean < 0) {
722 rollback_lock_file(&index_lock);
723 return clean;
726 if (write_locked_index(r->index, &index_lock,
727 COMMIT_LOCK | SKIP_IF_UNCHANGED))
729 * TRANSLATORS: %s will be "revert", "cherry-pick" or
730 * "rebase".
732 return error(_("%s: Unable to write new index file"),
733 _(action_name(opts)));
735 if (!clean)
736 append_conflicts_hint(r->index, msgbuf,
737 opts->default_msg_cleanup);
739 return !clean;
742 static struct object_id *get_cache_tree_oid(struct index_state *istate)
744 if (!cache_tree_fully_valid(istate->cache_tree))
745 if (cache_tree_update(istate, 0)) {
746 error(_("unable to update cache tree"));
747 return NULL;
750 return &istate->cache_tree->oid;
753 static int is_index_unchanged(struct repository *r)
755 struct object_id head_oid, *cache_tree_oid;
756 struct commit *head_commit;
757 struct index_state *istate = r->index;
759 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
760 return error(_("could not resolve HEAD commit"));
762 head_commit = lookup_commit(r, &head_oid);
765 * If head_commit is NULL, check_commit, called from
766 * lookup_commit, would have indicated that head_commit is not
767 * a commit object already. parse_commit() will return failure
768 * without further complaints in such a case. Otherwise, if
769 * the commit is invalid, parse_commit() will complain. So
770 * there is nothing for us to say here. Just return failure.
772 if (parse_commit(head_commit))
773 return -1;
775 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
776 return -1;
778 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
781 static int write_author_script(const char *message)
783 struct strbuf buf = STRBUF_INIT;
784 const char *eol;
785 int res;
787 for (;;)
788 if (!*message || starts_with(message, "\n")) {
789 missing_author:
790 /* Missing 'author' line? */
791 unlink(rebase_path_author_script());
792 return 0;
793 } else if (skip_prefix(message, "author ", &message))
794 break;
795 else if ((eol = strchr(message, '\n')))
796 message = eol + 1;
797 else
798 goto missing_author;
800 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
801 while (*message && *message != '\n' && *message != '\r')
802 if (skip_prefix(message, " <", &message))
803 break;
804 else if (*message != '\'')
805 strbuf_addch(&buf, *(message++));
806 else
807 strbuf_addf(&buf, "'\\%c'", *(message++));
808 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
809 while (*message && *message != '\n' && *message != '\r')
810 if (skip_prefix(message, "> ", &message))
811 break;
812 else if (*message != '\'')
813 strbuf_addch(&buf, *(message++));
814 else
815 strbuf_addf(&buf, "'\\%c'", *(message++));
816 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
817 while (*message && *message != '\n' && *message != '\r')
818 if (*message != '\'')
819 strbuf_addch(&buf, *(message++));
820 else
821 strbuf_addf(&buf, "'\\%c'", *(message++));
822 strbuf_addch(&buf, '\'');
823 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
824 strbuf_release(&buf);
825 return res;
829 * Take a series of KEY='VALUE' lines where VALUE part is
830 * sq-quoted, and append <KEY, VALUE> at the end of the string list
832 static int parse_key_value_squoted(char *buf, struct string_list *list)
834 while (*buf) {
835 struct string_list_item *item;
836 char *np;
837 char *cp = strchr(buf, '=');
838 if (!cp) {
839 np = strchrnul(buf, '\n');
840 return error(_("no key present in '%.*s'"),
841 (int) (np - buf), buf);
843 np = strchrnul(cp, '\n');
844 *cp++ = '\0';
845 item = string_list_append(list, buf);
847 buf = np + (*np == '\n');
848 *np = '\0';
849 cp = sq_dequote(cp);
850 if (!cp)
851 return error(_("unable to dequote value of '%s'"),
852 item->string);
853 item->util = xstrdup(cp);
855 return 0;
859 * Reads and parses the state directory's "author-script" file, and sets name,
860 * email and date accordingly.
861 * Returns 0 on success, -1 if the file could not be parsed.
863 * The author script is of the format:
865 * GIT_AUTHOR_NAME='$author_name'
866 * GIT_AUTHOR_EMAIL='$author_email'
867 * GIT_AUTHOR_DATE='$author_date'
869 * where $author_name, $author_email and $author_date are quoted. We are strict
870 * with our parsing, as the file was meant to be eval'd in the now-removed
871 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
872 * from what this function expects, it is better to bail out than to do
873 * something that the user does not expect.
875 int read_author_script(const char *path, char **name, char **email, char **date,
876 int allow_missing)
878 struct strbuf buf = STRBUF_INIT;
879 struct string_list kv = STRING_LIST_INIT_DUP;
880 int retval = -1; /* assume failure */
881 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
883 if (strbuf_read_file(&buf, path, 256) <= 0) {
884 strbuf_release(&buf);
885 if (errno == ENOENT && allow_missing)
886 return 0;
887 else
888 return error_errno(_("could not open '%s' for reading"),
889 path);
892 if (parse_key_value_squoted(buf.buf, &kv))
893 goto finish;
895 for (i = 0; i < kv.nr; i++) {
896 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
897 if (name_i != -2)
898 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
899 else
900 name_i = i;
901 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
902 if (email_i != -2)
903 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
904 else
905 email_i = i;
906 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
907 if (date_i != -2)
908 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
909 else
910 date_i = i;
911 } else {
912 err = error(_("unknown variable '%s'"),
913 kv.items[i].string);
916 if (name_i == -2)
917 error(_("missing 'GIT_AUTHOR_NAME'"));
918 if (email_i == -2)
919 error(_("missing 'GIT_AUTHOR_EMAIL'"));
920 if (date_i == -2)
921 error(_("missing 'GIT_AUTHOR_DATE'"));
922 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
923 goto finish;
924 *name = kv.items[name_i].util;
925 *email = kv.items[email_i].util;
926 *date = kv.items[date_i].util;
927 retval = 0;
928 finish:
929 string_list_clear(&kv, !!retval);
930 strbuf_release(&buf);
931 return retval;
935 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
936 * file with shell quoting into struct strvec. Returns -1 on
937 * error, 0 otherwise.
939 static int read_env_script(struct strvec *env)
941 char *name, *email, *date;
943 if (read_author_script(rebase_path_author_script(),
944 &name, &email, &date, 0))
945 return -1;
947 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
948 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
949 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
950 free(name);
951 free(email);
952 free(date);
954 return 0;
957 static char *get_author(const char *message)
959 size_t len;
960 const char *a;
962 a = find_commit_header(message, "author", &len);
963 if (a)
964 return xmemdupz(a, len);
966 return NULL;
969 static const char *author_date_from_env(const struct strvec *env)
971 int i;
972 const char *date;
974 for (i = 0; i < env->nr; i++)
975 if (skip_prefix(env->v[i],
976 "GIT_AUTHOR_DATE=", &date))
977 return date;
979 * If GIT_AUTHOR_DATE is missing we should have already errored out when
980 * reading the script
982 BUG("GIT_AUTHOR_DATE missing from author script");
985 static const char staged_changes_advice[] =
986 N_("you have staged changes in your working tree\n"
987 "If these changes are meant to be squashed into the previous commit, run:\n"
988 "\n"
989 " git commit --amend %s\n"
990 "\n"
991 "If they are meant to go into a new commit, run:\n"
992 "\n"
993 " git commit %s\n"
994 "\n"
995 "In both cases, once you're done, continue with:\n"
996 "\n"
997 " git rebase --continue\n");
999 #define ALLOW_EMPTY (1<<0)
1000 #define EDIT_MSG (1<<1)
1001 #define AMEND_MSG (1<<2)
1002 #define CLEANUP_MSG (1<<3)
1003 #define VERIFY_MSG (1<<4)
1004 #define CREATE_ROOT_COMMIT (1<<5)
1005 #define VERBATIM_MSG (1<<6)
1007 static int run_command_silent_on_success(struct child_process *cmd)
1009 struct strbuf buf = STRBUF_INIT;
1010 int rc;
1012 cmd->stdout_to_stderr = 1;
1013 rc = pipe_command(cmd,
1014 NULL, 0,
1015 NULL, 0,
1016 &buf, 0);
1018 if (rc)
1019 fputs(buf.buf, stderr);
1020 strbuf_release(&buf);
1021 return rc;
1025 * If we are cherry-pick, and if the merge did not result in
1026 * hand-editing, we will hit this commit and inherit the original
1027 * author date and name.
1029 * If we are revert, or if our cherry-pick results in a hand merge,
1030 * we had better say that the current user is responsible for that.
1032 * An exception is when run_git_commit() is called during an
1033 * interactive rebase: in that case, we will want to retain the
1034 * author metadata.
1036 static int run_git_commit(const char *defmsg,
1037 struct replay_opts *opts,
1038 unsigned int flags)
1040 struct child_process cmd = CHILD_PROCESS_INIT;
1042 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1043 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1045 cmd.git_cmd = 1;
1047 if (is_rebase_i(opts) &&
1048 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1049 !(!defmsg && (flags & AMEND_MSG))) &&
1050 read_env_script(&cmd.env)) {
1051 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1053 return error(_(staged_changes_advice),
1054 gpg_opt, gpg_opt);
1057 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1059 if (opts->committer_date_is_author_date)
1060 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1061 opts->ignore_date ?
1062 "" :
1063 author_date_from_env(&cmd.env));
1064 if (opts->ignore_date)
1065 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1067 strvec_push(&cmd.args, "commit");
1069 if (!(flags & VERIFY_MSG))
1070 strvec_push(&cmd.args, "-n");
1071 if ((flags & AMEND_MSG))
1072 strvec_push(&cmd.args, "--amend");
1073 if (opts->gpg_sign)
1074 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1075 else
1076 strvec_push(&cmd.args, "--no-gpg-sign");
1077 if (defmsg)
1078 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1079 else if (!(flags & EDIT_MSG))
1080 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1081 if ((flags & CLEANUP_MSG))
1082 strvec_push(&cmd.args, "--cleanup=strip");
1083 if ((flags & VERBATIM_MSG))
1084 strvec_push(&cmd.args, "--cleanup=verbatim");
1085 if ((flags & EDIT_MSG))
1086 strvec_push(&cmd.args, "-e");
1087 else if (!(flags & CLEANUP_MSG) &&
1088 !opts->signoff && !opts->record_origin &&
1089 !opts->explicit_cleanup)
1090 strvec_push(&cmd.args, "--cleanup=verbatim");
1092 if ((flags & ALLOW_EMPTY))
1093 strvec_push(&cmd.args, "--allow-empty");
1095 if (!(flags & EDIT_MSG))
1096 strvec_push(&cmd.args, "--allow-empty-message");
1098 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1099 return run_command_silent_on_success(&cmd);
1100 else
1101 return run_command(&cmd);
1104 static int rest_is_empty(const struct strbuf *sb, int start)
1106 int i, eol;
1107 const char *nl;
1109 /* Check if the rest is just whitespace and Signed-off-by's. */
1110 for (i = start; i < sb->len; i++) {
1111 nl = memchr(sb->buf + i, '\n', sb->len - i);
1112 if (nl)
1113 eol = nl - sb->buf;
1114 else
1115 eol = sb->len;
1117 if (strlen(sign_off_header) <= eol - i &&
1118 starts_with(sb->buf + i, sign_off_header)) {
1119 i = eol;
1120 continue;
1122 while (i < eol)
1123 if (!isspace(sb->buf[i++]))
1124 return 0;
1127 return 1;
1130 void cleanup_message(struct strbuf *msgbuf,
1131 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1133 if (verbose || /* Truncate the message just before the diff, if any. */
1134 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1135 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1136 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1137 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1141 * Find out if the message in the strbuf contains only whitespace and
1142 * Signed-off-by lines.
1144 int message_is_empty(const struct strbuf *sb,
1145 enum commit_msg_cleanup_mode cleanup_mode)
1147 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1148 return 0;
1149 return rest_is_empty(sb, 0);
1153 * See if the user edited the message in the editor or left what
1154 * was in the template intact
1156 int template_untouched(const struct strbuf *sb, const char *template_file,
1157 enum commit_msg_cleanup_mode cleanup_mode)
1159 struct strbuf tmpl = STRBUF_INIT;
1160 const char *start;
1162 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1163 return 0;
1165 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1166 return 0;
1168 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1169 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1170 start = sb->buf;
1171 strbuf_release(&tmpl);
1172 return rest_is_empty(sb, start - sb->buf);
1175 int update_head_with_reflog(const struct commit *old_head,
1176 const struct object_id *new_head,
1177 const char *action, const struct strbuf *msg,
1178 struct strbuf *err)
1180 struct ref_transaction *transaction;
1181 struct strbuf sb = STRBUF_INIT;
1182 const char *nl;
1183 int ret = 0;
1185 if (action) {
1186 strbuf_addstr(&sb, action);
1187 strbuf_addstr(&sb, ": ");
1190 nl = strchr(msg->buf, '\n');
1191 if (nl) {
1192 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1193 } else {
1194 strbuf_addbuf(&sb, msg);
1195 strbuf_addch(&sb, '\n');
1198 transaction = ref_transaction_begin(err);
1199 if (!transaction ||
1200 ref_transaction_update(transaction, "HEAD", new_head,
1201 old_head ? &old_head->object.oid : null_oid(),
1202 0, sb.buf, err) ||
1203 ref_transaction_commit(transaction, err)) {
1204 ret = -1;
1206 ref_transaction_free(transaction);
1207 strbuf_release(&sb);
1209 return ret;
1212 static int run_rewrite_hook(const struct object_id *oldoid,
1213 const struct object_id *newoid)
1215 struct child_process proc = CHILD_PROCESS_INIT;
1216 int code;
1217 struct strbuf sb = STRBUF_INIT;
1218 const char *hook_path = find_hook("post-rewrite");
1220 if (!hook_path)
1221 return 0;
1223 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1224 proc.in = -1;
1225 proc.stdout_to_stderr = 1;
1226 proc.trace2_hook_name = "post-rewrite";
1228 code = start_command(&proc);
1229 if (code)
1230 return code;
1231 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1232 sigchain_push(SIGPIPE, SIG_IGN);
1233 write_in_full(proc.in, sb.buf, sb.len);
1234 close(proc.in);
1235 strbuf_release(&sb);
1236 sigchain_pop(SIGPIPE);
1237 return finish_command(&proc);
1240 void commit_post_rewrite(struct repository *r,
1241 const struct commit *old_head,
1242 const struct object_id *new_head)
1244 struct notes_rewrite_cfg *cfg;
1246 cfg = init_copy_notes_for_rewrite("amend");
1247 if (cfg) {
1248 /* we are amending, so old_head is not NULL */
1249 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1250 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1252 run_rewrite_hook(&old_head->object.oid, new_head);
1255 static int run_prepare_commit_msg_hook(struct repository *r,
1256 struct strbuf *msg,
1257 const char *commit)
1259 int ret = 0;
1260 const char *name, *arg1 = NULL, *arg2 = NULL;
1262 name = git_path_commit_editmsg();
1263 if (write_message(msg->buf, msg->len, name, 0))
1264 return -1;
1266 if (commit) {
1267 arg1 = "commit";
1268 arg2 = commit;
1269 } else {
1270 arg1 = "message";
1272 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1273 arg1, arg2, NULL))
1274 ret = error(_("'prepare-commit-msg' hook failed"));
1276 return ret;
1279 static const char implicit_ident_advice_noconfig[] =
1280 N_("Your name and email address were configured automatically based\n"
1281 "on your username and hostname. Please check that they are accurate.\n"
1282 "You can suppress this message by setting them explicitly. Run the\n"
1283 "following command and follow the instructions in your editor to edit\n"
1284 "your configuration file:\n"
1285 "\n"
1286 " git config --global --edit\n"
1287 "\n"
1288 "After doing this, you may fix the identity used for this commit with:\n"
1289 "\n"
1290 " git commit --amend --reset-author\n");
1292 static const char implicit_ident_advice_config[] =
1293 N_("Your name and email address were configured automatically based\n"
1294 "on your username and hostname. Please check that they are accurate.\n"
1295 "You can suppress this message by setting them explicitly:\n"
1296 "\n"
1297 " git config --global user.name \"Your Name\"\n"
1298 " git config --global user.email you@example.com\n"
1299 "\n"
1300 "After doing this, you may fix the identity used for this commit with:\n"
1301 "\n"
1302 " git commit --amend --reset-author\n");
1304 static const char *implicit_ident_advice(void)
1306 char *user_config = interpolate_path("~/.gitconfig", 0);
1307 char *xdg_config = xdg_config_home("config");
1308 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1310 free(user_config);
1311 free(xdg_config);
1313 if (config_exists)
1314 return _(implicit_ident_advice_config);
1315 else
1316 return _(implicit_ident_advice_noconfig);
1320 void print_commit_summary(struct repository *r,
1321 const char *prefix,
1322 const struct object_id *oid,
1323 unsigned int flags)
1325 struct rev_info rev;
1326 struct commit *commit;
1327 struct strbuf format = STRBUF_INIT;
1328 const char *head;
1329 struct pretty_print_context pctx = {0};
1330 struct strbuf author_ident = STRBUF_INIT;
1331 struct strbuf committer_ident = STRBUF_INIT;
1332 struct ref_store *refs;
1334 commit = lookup_commit(r, oid);
1335 if (!commit)
1336 die(_("couldn't look up newly created commit"));
1337 if (parse_commit(commit))
1338 die(_("could not parse newly created commit"));
1340 strbuf_addstr(&format, "format:%h] %s");
1342 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1343 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1344 if (strbuf_cmp(&author_ident, &committer_ident)) {
1345 strbuf_addstr(&format, "\n Author: ");
1346 strbuf_addbuf_percentquote(&format, &author_ident);
1348 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1349 struct strbuf date = STRBUF_INIT;
1351 format_commit_message(commit, "%ad", &date, &pctx);
1352 strbuf_addstr(&format, "\n Date: ");
1353 strbuf_addbuf_percentquote(&format, &date);
1354 strbuf_release(&date);
1356 if (!committer_ident_sufficiently_given()) {
1357 strbuf_addstr(&format, "\n Committer: ");
1358 strbuf_addbuf_percentquote(&format, &committer_ident);
1359 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1360 strbuf_addch(&format, '\n');
1361 strbuf_addstr(&format, implicit_ident_advice());
1364 strbuf_release(&author_ident);
1365 strbuf_release(&committer_ident);
1367 repo_init_revisions(r, &rev, prefix);
1368 setup_revisions(0, NULL, &rev, NULL);
1370 rev.diff = 1;
1371 rev.diffopt.output_format =
1372 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1374 rev.verbose_header = 1;
1375 rev.show_root_diff = 1;
1376 get_commit_format(format.buf, &rev);
1377 rev.always_show_header = 0;
1378 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1379 diff_setup_done(&rev.diffopt);
1381 refs = get_main_ref_store(the_repository);
1382 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1383 if (!head)
1384 die(_("unable to resolve HEAD after creating commit"));
1385 if (!strcmp(head, "HEAD"))
1386 head = _("detached HEAD");
1387 else
1388 skip_prefix(head, "refs/heads/", &head);
1389 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1390 _(" (root-commit)") : "");
1392 if (!log_tree_commit(&rev, commit)) {
1393 rev.always_show_header = 1;
1394 rev.use_terminator = 1;
1395 log_tree_commit(&rev, commit);
1398 release_revisions(&rev);
1399 strbuf_release(&format);
1402 static int parse_head(struct repository *r, struct commit **head)
1404 struct commit *current_head;
1405 struct object_id oid;
1407 if (get_oid("HEAD", &oid)) {
1408 current_head = NULL;
1409 } else {
1410 current_head = lookup_commit_reference(r, &oid);
1411 if (!current_head)
1412 return error(_("could not parse HEAD"));
1413 if (!oideq(&oid, &current_head->object.oid)) {
1414 warning(_("HEAD %s is not a commit!"),
1415 oid_to_hex(&oid));
1417 if (parse_commit(current_head))
1418 return error(_("could not parse HEAD commit"));
1420 *head = current_head;
1422 return 0;
1426 * Try to commit without forking 'git commit'. In some cases we need
1427 * to run 'git commit' to display an error message
1429 * Returns:
1430 * -1 - error unable to commit
1431 * 0 - success
1432 * 1 - run 'git commit'
1434 static int try_to_commit(struct repository *r,
1435 struct strbuf *msg, const char *author,
1436 struct replay_opts *opts, unsigned int flags,
1437 struct object_id *oid)
1439 struct object_id tree;
1440 struct commit *current_head = NULL;
1441 struct commit_list *parents = NULL;
1442 struct commit_extra_header *extra = NULL;
1443 struct strbuf err = STRBUF_INIT;
1444 struct strbuf commit_msg = STRBUF_INIT;
1445 char *amend_author = NULL;
1446 const char *committer = NULL;
1447 const char *hook_commit = NULL;
1448 enum commit_msg_cleanup_mode cleanup;
1449 int res = 0;
1451 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1452 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1454 if (parse_head(r, &current_head))
1455 return -1;
1457 if (flags & AMEND_MSG) {
1458 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1459 const char *out_enc = get_commit_output_encoding();
1460 const char *message = logmsg_reencode(current_head, NULL,
1461 out_enc);
1463 if (!msg) {
1464 const char *orig_message = NULL;
1466 find_commit_subject(message, &orig_message);
1467 msg = &commit_msg;
1468 strbuf_addstr(msg, orig_message);
1469 hook_commit = "HEAD";
1471 author = amend_author = get_author(message);
1472 unuse_commit_buffer(current_head, message);
1473 if (!author) {
1474 res = error(_("unable to parse commit author"));
1475 goto out;
1477 parents = copy_commit_list(current_head->parents);
1478 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1479 } else if (current_head &&
1480 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1481 commit_list_insert(current_head, &parents);
1484 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1485 res = error(_("git write-tree failed to write a tree"));
1486 goto out;
1489 if (!(flags & ALLOW_EMPTY)) {
1490 struct commit *first_parent = current_head;
1492 if (flags & AMEND_MSG) {
1493 if (current_head->parents) {
1494 first_parent = current_head->parents->item;
1495 if (repo_parse_commit(r, first_parent)) {
1496 res = error(_("could not parse HEAD commit"));
1497 goto out;
1499 } else {
1500 first_parent = NULL;
1503 if (oideq(first_parent
1504 ? get_commit_tree_oid(first_parent)
1505 : the_hash_algo->empty_tree,
1506 &tree)) {
1507 res = 1; /* run 'git commit' to display error message */
1508 goto out;
1512 if (hook_exists("prepare-commit-msg")) {
1513 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1514 if (res)
1515 goto out;
1516 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1517 2048) < 0) {
1518 res = error_errno(_("unable to read commit message "
1519 "from '%s'"),
1520 git_path_commit_editmsg());
1521 goto out;
1523 msg = &commit_msg;
1526 if (flags & CLEANUP_MSG)
1527 cleanup = COMMIT_MSG_CLEANUP_ALL;
1528 else if (flags & VERBATIM_MSG)
1529 cleanup = COMMIT_MSG_CLEANUP_NONE;
1530 else if ((opts->signoff || opts->record_origin) &&
1531 !opts->explicit_cleanup)
1532 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1533 else
1534 cleanup = opts->default_msg_cleanup;
1536 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1537 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1538 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1539 res = 1; /* run 'git commit' to display error message */
1540 goto out;
1543 if (opts->committer_date_is_author_date) {
1544 struct ident_split id;
1545 struct strbuf date = STRBUF_INIT;
1547 if (!opts->ignore_date) {
1548 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1549 res = error(_("invalid author identity '%s'"),
1550 author);
1551 goto out;
1553 if (!id.date_begin) {
1554 res = error(_(
1555 "corrupt author: missing date information"));
1556 goto out;
1558 strbuf_addf(&date, "@%.*s %.*s",
1559 (int)(id.date_end - id.date_begin),
1560 id.date_begin,
1561 (int)(id.tz_end - id.tz_begin),
1562 id.tz_begin);
1563 } else {
1564 reset_ident_date();
1566 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1567 getenv("GIT_COMMITTER_EMAIL"),
1568 WANT_COMMITTER_IDENT,
1569 opts->ignore_date ? NULL : date.buf,
1570 IDENT_STRICT);
1571 strbuf_release(&date);
1572 } else {
1573 reset_ident_date();
1576 if (opts->ignore_date) {
1577 struct ident_split id;
1578 char *name, *email;
1580 if (split_ident_line(&id, author, strlen(author)) < 0) {
1581 error(_("invalid author identity '%s'"), author);
1582 goto out;
1584 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1585 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1586 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1587 IDENT_STRICT);
1588 free(name);
1589 free(email);
1592 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1593 author, committer, opts->gpg_sign, extra)) {
1594 res = error(_("failed to write commit object"));
1595 goto out;
1598 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1599 msg, &err)) {
1600 res = error("%s", err.buf);
1601 goto out;
1604 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1605 if (flags & AMEND_MSG)
1606 commit_post_rewrite(r, current_head, oid);
1608 out:
1609 free_commit_extra_headers(extra);
1610 strbuf_release(&err);
1611 strbuf_release(&commit_msg);
1612 free(amend_author);
1614 return res;
1617 static int write_rebase_head(struct object_id *oid)
1619 if (update_ref("rebase", "REBASE_HEAD", oid,
1620 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1621 return error(_("could not update %s"), "REBASE_HEAD");
1623 return 0;
1626 static int do_commit(struct repository *r,
1627 const char *msg_file, const char *author,
1628 struct replay_opts *opts, unsigned int flags,
1629 struct object_id *oid)
1631 int res = 1;
1633 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1634 struct object_id oid;
1635 struct strbuf sb = STRBUF_INIT;
1637 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1638 return error_errno(_("unable to read commit message "
1639 "from '%s'"),
1640 msg_file);
1642 res = try_to_commit(r, msg_file ? &sb : NULL,
1643 author, opts, flags, &oid);
1644 strbuf_release(&sb);
1645 if (!res) {
1646 refs_delete_ref(get_main_ref_store(r), "",
1647 "CHERRY_PICK_HEAD", NULL, 0);
1648 unlink(git_path_merge_msg(r));
1649 if (!is_rebase_i(opts))
1650 print_commit_summary(r, NULL, &oid,
1651 SUMMARY_SHOW_AUTHOR_DATE);
1652 return res;
1655 if (res == 1) {
1656 if (is_rebase_i(opts) && oid)
1657 if (write_rebase_head(oid))
1658 return -1;
1659 return run_git_commit(msg_file, opts, flags);
1662 return res;
1665 static int is_original_commit_empty(struct commit *commit)
1667 const struct object_id *ptree_oid;
1669 if (parse_commit(commit))
1670 return error(_("could not parse commit %s"),
1671 oid_to_hex(&commit->object.oid));
1672 if (commit->parents) {
1673 struct commit *parent = commit->parents->item;
1674 if (parse_commit(parent))
1675 return error(_("could not parse parent commit %s"),
1676 oid_to_hex(&parent->object.oid));
1677 ptree_oid = get_commit_tree_oid(parent);
1678 } else {
1679 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1682 return oideq(ptree_oid, get_commit_tree_oid(commit));
1686 * Should empty commits be allowed? Return status:
1687 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1688 * 0: Halt on empty commit
1689 * 1: Allow empty commit
1690 * 2: Drop empty commit
1692 static int allow_empty(struct repository *r,
1693 struct replay_opts *opts,
1694 struct commit *commit)
1696 int index_unchanged, originally_empty;
1699 * Four cases:
1701 * (1) we do not allow empty at all and error out.
1703 * (2) we allow ones that were initially empty, and
1704 * just drop the ones that become empty
1706 * (3) we allow ones that were initially empty, but
1707 * halt for the ones that become empty;
1709 * (4) we allow both.
1711 if (!opts->allow_empty)
1712 return 0; /* let "git commit" barf as necessary */
1714 index_unchanged = is_index_unchanged(r);
1715 if (index_unchanged < 0)
1716 return index_unchanged;
1717 if (!index_unchanged)
1718 return 0; /* we do not have to say --allow-empty */
1720 if (opts->keep_redundant_commits)
1721 return 1;
1723 originally_empty = is_original_commit_empty(commit);
1724 if (originally_empty < 0)
1725 return originally_empty;
1726 if (originally_empty)
1727 return 1;
1728 else if (opts->drop_redundant_commits)
1729 return 2;
1730 else
1731 return 0;
1734 static struct {
1735 char c;
1736 const char *str;
1737 } todo_command_info[] = {
1738 [TODO_PICK] = { 'p', "pick" },
1739 [TODO_REVERT] = { 0, "revert" },
1740 [TODO_EDIT] = { 'e', "edit" },
1741 [TODO_REWORD] = { 'r', "reword" },
1742 [TODO_FIXUP] = { 'f', "fixup" },
1743 [TODO_SQUASH] = { 's', "squash" },
1744 [TODO_EXEC] = { 'x', "exec" },
1745 [TODO_BREAK] = { 'b', "break" },
1746 [TODO_LABEL] = { 'l', "label" },
1747 [TODO_RESET] = { 't', "reset" },
1748 [TODO_MERGE] = { 'm', "merge" },
1749 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1750 [TODO_NOOP] = { 0, "noop" },
1751 [TODO_DROP] = { 'd', "drop" },
1752 [TODO_COMMENT] = { 0, NULL },
1755 static const char *command_to_string(const enum todo_command command)
1757 if (command < TODO_COMMENT)
1758 return todo_command_info[command].str;
1759 die(_("unknown command: %d"), command);
1762 static char command_to_char(const enum todo_command command)
1764 if (command < TODO_COMMENT)
1765 return todo_command_info[command].c;
1766 return comment_line_char;
1769 static int is_noop(const enum todo_command command)
1771 return TODO_NOOP <= command;
1774 static int is_fixup(enum todo_command command)
1776 return command == TODO_FIXUP || command == TODO_SQUASH;
1779 /* Does this command create a (non-merge) commit? */
1780 static int is_pick_or_similar(enum todo_command command)
1782 switch (command) {
1783 case TODO_PICK:
1784 case TODO_REVERT:
1785 case TODO_EDIT:
1786 case TODO_REWORD:
1787 case TODO_FIXUP:
1788 case TODO_SQUASH:
1789 return 1;
1790 default:
1791 return 0;
1795 enum todo_item_flags {
1796 TODO_EDIT_MERGE_MSG = (1 << 0),
1797 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1798 TODO_EDIT_FIXUP_MSG = (1 << 2),
1801 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1802 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1803 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1804 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1805 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1807 static int is_fixup_flag(enum todo_command command, unsigned flag)
1809 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1810 (flag & TODO_EDIT_FIXUP_MSG));
1814 * Wrapper around strbuf_add_commented_lines() which avoids double
1815 * commenting commit subjects.
1817 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1819 const char *s = str;
1820 while (len > 0 && s[0] == comment_line_char) {
1821 size_t count;
1822 const char *n = memchr(s, '\n', len);
1823 if (!n)
1824 count = len;
1825 else
1826 count = n - s + 1;
1827 strbuf_add(buf, s, count);
1828 s += count;
1829 len -= count;
1831 strbuf_add_commented_lines(buf, s, len);
1834 /* Does the current fixup chain contain a squash command? */
1835 static int seen_squash(struct replay_opts *opts)
1837 return starts_with(opts->current_fixups.buf, "squash") ||
1838 strstr(opts->current_fixups.buf, "\nsquash");
1841 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1843 strbuf_setlen(buf1, 2);
1844 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1845 strbuf_addch(buf1, '\n');
1846 strbuf_setlen(buf2, 2);
1847 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1848 strbuf_addch(buf2, '\n');
1852 * Comment out any un-commented commit messages, updating the message comments
1853 * to say they will be skipped but do not comment out the empty lines that
1854 * surround commit messages and their comments.
1856 static void update_squash_message_for_fixup(struct strbuf *msg)
1858 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1859 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1860 const char *s, *start;
1861 char *orig_msg;
1862 size_t orig_msg_len;
1863 int i = 1;
1865 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1866 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1867 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1868 while (s) {
1869 const char *next;
1870 size_t off;
1871 if (skip_prefix(s, buf1.buf, &next)) {
1873 * Copy the last message, preserving the blank line
1874 * preceding the current line
1876 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1877 copy_lines(msg, start, s - start - off);
1878 if (off)
1879 strbuf_addch(msg, '\n');
1881 * The next message needs to be commented out but the
1882 * message header is already commented out so just copy
1883 * it and the blank line that follows it.
1885 strbuf_addbuf(msg, &buf2);
1886 if (*next == '\n')
1887 strbuf_addch(msg, *next++);
1888 start = s = next;
1889 copy_lines = add_commented_lines;
1890 update_comment_bufs(&buf1, &buf2, ++i);
1891 } else if (skip_prefix(s, buf2.buf, &next)) {
1892 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1893 copy_lines(msg, start, s - start - off);
1894 start = s - off;
1895 s = next;
1896 copy_lines = strbuf_add;
1897 update_comment_bufs(&buf1, &buf2, ++i);
1898 } else {
1899 s = strchr(s, '\n');
1900 if (s)
1901 s++;
1904 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1905 free(orig_msg);
1906 strbuf_release(&buf1);
1907 strbuf_release(&buf2);
1910 static int append_squash_message(struct strbuf *buf, const char *body,
1911 enum todo_command command, struct replay_opts *opts,
1912 unsigned flag)
1914 const char *fixup_msg;
1915 size_t commented_len = 0, fixup_off;
1917 * amend is non-interactive and not normally used with fixup!
1918 * or squash! commits, so only comment out those subjects when
1919 * squashing commit messages.
1921 if (starts_with(body, "amend!") ||
1922 ((command == TODO_SQUASH || seen_squash(opts)) &&
1923 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1924 commented_len = commit_subject_length(body);
1926 strbuf_addf(buf, "\n%c ", comment_line_char);
1927 strbuf_addf(buf, _(nth_commit_msg_fmt),
1928 ++opts->current_fixup_count + 1);
1929 strbuf_addstr(buf, "\n\n");
1930 strbuf_add_commented_lines(buf, body, commented_len);
1931 /* buf->buf may be reallocated so store an offset into the buffer */
1932 fixup_off = buf->len;
1933 strbuf_addstr(buf, body + commented_len);
1935 /* fixup -C after squash behaves like squash */
1936 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1938 * We're replacing the commit message so we need to
1939 * append the Signed-off-by: trailer if the user
1940 * requested '--signoff'.
1942 if (opts->signoff)
1943 append_signoff(buf, 0, 0);
1945 if ((command == TODO_FIXUP) &&
1946 (flag & TODO_REPLACE_FIXUP_MSG) &&
1947 (file_exists(rebase_path_fixup_msg()) ||
1948 !file_exists(rebase_path_squash_msg()))) {
1949 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1950 if (write_message(fixup_msg, strlen(fixup_msg),
1951 rebase_path_fixup_msg(), 0) < 0)
1952 return error(_("cannot write '%s'"),
1953 rebase_path_fixup_msg());
1954 } else {
1955 unlink(rebase_path_fixup_msg());
1957 } else {
1958 unlink(rebase_path_fixup_msg());
1961 return 0;
1964 static int update_squash_messages(struct repository *r,
1965 enum todo_command command,
1966 struct commit *commit,
1967 struct replay_opts *opts,
1968 unsigned flag)
1970 struct strbuf buf = STRBUF_INIT;
1971 int res = 0;
1972 const char *message, *body;
1973 const char *encoding = get_commit_output_encoding();
1975 if (opts->current_fixup_count > 0) {
1976 struct strbuf header = STRBUF_INIT;
1977 char *eol;
1979 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1980 return error(_("could not read '%s'"),
1981 rebase_path_squash_msg());
1983 eol = buf.buf[0] != comment_line_char ?
1984 buf.buf : strchrnul(buf.buf, '\n');
1986 strbuf_addf(&header, "%c ", comment_line_char);
1987 strbuf_addf(&header, _(combined_commit_msg_fmt),
1988 opts->current_fixup_count + 2);
1989 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1990 strbuf_release(&header);
1991 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1992 update_squash_message_for_fixup(&buf);
1993 } else {
1994 struct object_id head;
1995 struct commit *head_commit;
1996 const char *head_message, *body;
1998 if (get_oid("HEAD", &head))
1999 return error(_("need a HEAD to fixup"));
2000 if (!(head_commit = lookup_commit_reference(r, &head)))
2001 return error(_("could not read HEAD"));
2002 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
2003 return error(_("could not read HEAD's commit message"));
2005 find_commit_subject(head_message, &body);
2006 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2007 rebase_path_fixup_msg(), 0) < 0) {
2008 unuse_commit_buffer(head_commit, head_message);
2009 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2011 strbuf_addf(&buf, "%c ", comment_line_char);
2012 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2013 strbuf_addf(&buf, "\n%c ", comment_line_char);
2014 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2015 _(skip_first_commit_msg_str) :
2016 _(first_commit_msg_str));
2017 strbuf_addstr(&buf, "\n\n");
2018 if (is_fixup_flag(command, flag))
2019 strbuf_add_commented_lines(&buf, body, strlen(body));
2020 else
2021 strbuf_addstr(&buf, body);
2023 unuse_commit_buffer(head_commit, head_message);
2026 if (!(message = logmsg_reencode(commit, NULL, encoding)))
2027 return error(_("could not read commit message of %s"),
2028 oid_to_hex(&commit->object.oid));
2029 find_commit_subject(message, &body);
2031 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2032 res = append_squash_message(&buf, body, command, opts, flag);
2033 } else if (command == TODO_FIXUP) {
2034 strbuf_addf(&buf, "\n%c ", comment_line_char);
2035 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2036 ++opts->current_fixup_count + 1);
2037 strbuf_addstr(&buf, "\n\n");
2038 strbuf_add_commented_lines(&buf, body, strlen(body));
2039 } else
2040 return error(_("unknown command: %d"), command);
2041 unuse_commit_buffer(commit, message);
2043 if (!res)
2044 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2046 strbuf_release(&buf);
2048 if (!res) {
2049 strbuf_addf(&opts->current_fixups, "%s%s %s",
2050 opts->current_fixups.len ? "\n" : "",
2051 command_to_string(command),
2052 oid_to_hex(&commit->object.oid));
2053 res = write_message(opts->current_fixups.buf,
2054 opts->current_fixups.len,
2055 rebase_path_current_fixups(), 0);
2058 return res;
2061 static void flush_rewritten_pending(void)
2063 struct strbuf buf = STRBUF_INIT;
2064 struct object_id newoid;
2065 FILE *out;
2067 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2068 !get_oid("HEAD", &newoid) &&
2069 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2070 char *bol = buf.buf, *eol;
2072 while (*bol) {
2073 eol = strchrnul(bol, '\n');
2074 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2075 bol, oid_to_hex(&newoid));
2076 if (!*eol)
2077 break;
2078 bol = eol + 1;
2080 fclose(out);
2081 unlink(rebase_path_rewritten_pending());
2083 strbuf_release(&buf);
2086 static void record_in_rewritten(struct object_id *oid,
2087 enum todo_command next_command)
2089 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2091 if (!out)
2092 return;
2094 fprintf(out, "%s\n", oid_to_hex(oid));
2095 fclose(out);
2097 if (!is_fixup(next_command))
2098 flush_rewritten_pending();
2101 static int should_edit(struct replay_opts *opts) {
2102 if (opts->edit < 0)
2104 * Note that we only handle the case of non-conflicted
2105 * commits; continue_single_pick() handles the conflicted
2106 * commits itself instead of calling this function.
2108 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2109 return opts->edit;
2112 static void refer_to_commit(struct replay_opts *opts,
2113 struct strbuf *msgbuf, struct commit *commit)
2115 if (opts->commit_use_reference) {
2116 struct pretty_print_context ctx = {
2117 .abbrev = DEFAULT_ABBREV,
2118 .date_mode.type = DATE_SHORT,
2120 format_commit_message(commit, "%h (%s, %ad)", msgbuf, &ctx);
2121 } else {
2122 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2126 static int do_pick_commit(struct repository *r,
2127 struct todo_item *item,
2128 struct replay_opts *opts,
2129 int final_fixup, int *check_todo)
2131 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2132 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2133 struct object_id head;
2134 struct commit *base, *next, *parent;
2135 const char *base_label, *next_label;
2136 char *author = NULL;
2137 struct commit_message msg = { NULL, NULL, NULL, NULL };
2138 struct strbuf msgbuf = STRBUF_INIT;
2139 int res, unborn = 0, reword = 0, allow, drop_commit;
2140 enum todo_command command = item->command;
2141 struct commit *commit = item->commit;
2143 if (opts->no_commit) {
2145 * We do not intend to commit immediately. We just want to
2146 * merge the differences in, so let's compute the tree
2147 * that represents the "current" state for the merge machinery
2148 * to work on.
2150 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2151 return error(_("your index file is unmerged."));
2152 } else {
2153 unborn = get_oid("HEAD", &head);
2154 /* Do we want to generate a root commit? */
2155 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2156 oideq(&head, &opts->squash_onto)) {
2157 if (is_fixup(command))
2158 return error(_("cannot fixup root commit"));
2159 flags |= CREATE_ROOT_COMMIT;
2160 unborn = 1;
2161 } else if (unborn)
2162 oidcpy(&head, the_hash_algo->empty_tree);
2163 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2164 NULL, 0))
2165 return error_dirty_index(r, opts);
2167 discard_index(r->index);
2169 if (!commit->parents)
2170 parent = NULL;
2171 else if (commit->parents->next) {
2172 /* Reverting or cherry-picking a merge commit */
2173 int cnt;
2174 struct commit_list *p;
2176 if (!opts->mainline)
2177 return error(_("commit %s is a merge but no -m option was given."),
2178 oid_to_hex(&commit->object.oid));
2180 for (cnt = 1, p = commit->parents;
2181 cnt != opts->mainline && p;
2182 cnt++)
2183 p = p->next;
2184 if (cnt != opts->mainline || !p)
2185 return error(_("commit %s does not have parent %d"),
2186 oid_to_hex(&commit->object.oid), opts->mainline);
2187 parent = p->item;
2188 } else if (1 < opts->mainline)
2190 * Non-first parent explicitly specified as mainline for
2191 * non-merge commit
2193 return error(_("commit %s does not have parent %d"),
2194 oid_to_hex(&commit->object.oid), opts->mainline);
2195 else
2196 parent = commit->parents->item;
2198 if (get_message(commit, &msg) != 0)
2199 return error(_("cannot get commit message for %s"),
2200 oid_to_hex(&commit->object.oid));
2202 if (opts->allow_ff && !is_fixup(command) &&
2203 ((parent && oideq(&parent->object.oid, &head)) ||
2204 (!parent && unborn))) {
2205 if (is_rebase_i(opts))
2206 write_author_script(msg.message);
2207 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2208 opts);
2209 if (res || command != TODO_REWORD)
2210 goto leave;
2211 reword = 1;
2212 msg_file = NULL;
2213 goto fast_forward_edit;
2215 if (parent && parse_commit(parent) < 0)
2216 /* TRANSLATORS: The first %s will be a "todo" command like
2217 "revert" or "pick", the second %s a SHA1. */
2218 return error(_("%s: cannot parse parent commit %s"),
2219 command_to_string(command),
2220 oid_to_hex(&parent->object.oid));
2223 * "commit" is an existing commit. We would want to apply
2224 * the difference it introduces since its first parent "prev"
2225 * on top of the current HEAD if we are cherry-pick. Or the
2226 * reverse of it if we are revert.
2229 if (command == TODO_REVERT) {
2230 base = commit;
2231 base_label = msg.label;
2232 next = parent;
2233 next_label = msg.parent_label;
2234 if (opts->commit_use_reference) {
2235 strbuf_addstr(&msgbuf,
2236 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2237 } else {
2238 strbuf_addstr(&msgbuf, "Revert \"");
2239 strbuf_addstr(&msgbuf, msg.subject);
2240 strbuf_addstr(&msgbuf, "\"");
2242 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2243 refer_to_commit(opts, &msgbuf, commit);
2245 if (commit->parents && commit->parents->next) {
2246 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2247 refer_to_commit(opts, &msgbuf, parent);
2249 strbuf_addstr(&msgbuf, ".\n");
2250 } else {
2251 const char *p;
2253 base = parent;
2254 base_label = msg.parent_label;
2255 next = commit;
2256 next_label = msg.label;
2258 /* Append the commit log message to msgbuf. */
2259 if (find_commit_subject(msg.message, &p))
2260 strbuf_addstr(&msgbuf, p);
2262 if (opts->record_origin) {
2263 strbuf_complete_line(&msgbuf);
2264 if (!has_conforming_footer(&msgbuf, NULL, 0))
2265 strbuf_addch(&msgbuf, '\n');
2266 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2267 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2268 strbuf_addstr(&msgbuf, ")\n");
2270 if (!is_fixup(command))
2271 author = get_author(msg.message);
2274 if (command == TODO_REWORD)
2275 reword = 1;
2276 else if (is_fixup(command)) {
2277 if (update_squash_messages(r, command, commit,
2278 opts, item->flags)) {
2279 res = -1;
2280 goto leave;
2282 flags |= AMEND_MSG;
2283 if (!final_fixup)
2284 msg_file = rebase_path_squash_msg();
2285 else if (file_exists(rebase_path_fixup_msg())) {
2286 flags |= VERBATIM_MSG;
2287 msg_file = rebase_path_fixup_msg();
2288 } else {
2289 const char *dest = git_path_squash_msg(r);
2290 unlink(dest);
2291 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2292 res = error(_("could not rename '%s' to '%s'"),
2293 rebase_path_squash_msg(), dest);
2294 goto leave;
2296 unlink(git_path_merge_msg(r));
2297 msg_file = dest;
2298 flags |= EDIT_MSG;
2302 if (opts->signoff && !is_fixup(command))
2303 append_signoff(&msgbuf, 0, 0);
2305 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2306 res = -1;
2307 else if (!opts->strategy ||
2308 !strcmp(opts->strategy, "recursive") ||
2309 !strcmp(opts->strategy, "ort") ||
2310 command == TODO_REVERT) {
2311 res = do_recursive_merge(r, base, next, base_label, next_label,
2312 &head, &msgbuf, opts);
2313 if (res < 0)
2314 goto leave;
2316 res |= write_message(msgbuf.buf, msgbuf.len,
2317 git_path_merge_msg(r), 0);
2318 } else {
2319 struct commit_list *common = NULL;
2320 struct commit_list *remotes = NULL;
2322 res = write_message(msgbuf.buf, msgbuf.len,
2323 git_path_merge_msg(r), 0);
2325 commit_list_insert(base, &common);
2326 commit_list_insert(next, &remotes);
2327 res |= try_merge_command(r, opts->strategy,
2328 opts->xopts_nr, (const char **)opts->xopts,
2329 common, oid_to_hex(&head), remotes);
2330 free_commit_list(common);
2331 free_commit_list(remotes);
2335 * If the merge was clean or if it failed due to conflict, we write
2336 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2337 * However, if the merge did not even start, then we don't want to
2338 * write it at all.
2340 if ((command == TODO_PICK || command == TODO_REWORD ||
2341 command == TODO_EDIT) && !opts->no_commit &&
2342 (res == 0 || res == 1) &&
2343 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2344 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2345 res = -1;
2346 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2347 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2348 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2349 res = -1;
2351 if (res) {
2352 error(command == TODO_REVERT
2353 ? _("could not revert %s... %s")
2354 : _("could not apply %s... %s"),
2355 short_commit_name(commit), msg.subject);
2356 print_advice(r, res == 1, opts);
2357 repo_rerere(r, opts->allow_rerere_auto);
2358 goto leave;
2361 drop_commit = 0;
2362 allow = allow_empty(r, opts, commit);
2363 if (allow < 0) {
2364 res = allow;
2365 goto leave;
2366 } else if (allow == 1) {
2367 flags |= ALLOW_EMPTY;
2368 } else if (allow == 2) {
2369 drop_commit = 1;
2370 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2371 NULL, 0);
2372 unlink(git_path_merge_msg(r));
2373 unlink(git_path_auto_merge(r));
2374 fprintf(stderr,
2375 _("dropping %s %s -- patch contents already upstream\n"),
2376 oid_to_hex(&commit->object.oid), msg.subject);
2377 } /* else allow == 0 and there's nothing special to do */
2378 if (!opts->no_commit && !drop_commit) {
2379 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2380 res = do_commit(r, msg_file, author, opts, flags,
2381 commit? &commit->object.oid : NULL);
2382 else
2383 res = error(_("unable to parse commit author"));
2384 *check_todo = !!(flags & EDIT_MSG);
2385 if (!res && reword) {
2386 fast_forward_edit:
2387 res = run_git_commit(NULL, opts, EDIT_MSG |
2388 VERIFY_MSG | AMEND_MSG |
2389 (flags & ALLOW_EMPTY));
2390 *check_todo = 1;
2395 if (!res && final_fixup) {
2396 unlink(rebase_path_fixup_msg());
2397 unlink(rebase_path_squash_msg());
2398 unlink(rebase_path_current_fixups());
2399 strbuf_reset(&opts->current_fixups);
2400 opts->current_fixup_count = 0;
2403 leave:
2404 free_message(commit, &msg);
2405 free(author);
2406 strbuf_release(&msgbuf);
2407 update_abort_safety_file();
2409 return res;
2412 static int prepare_revs(struct replay_opts *opts)
2415 * picking (but not reverting) ranges (but not individual revisions)
2416 * should be done in reverse
2418 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2419 opts->revs->reverse ^= 1;
2421 if (prepare_revision_walk(opts->revs))
2422 return error(_("revision walk setup failed"));
2424 return 0;
2427 static int read_and_refresh_cache(struct repository *r,
2428 struct replay_opts *opts)
2430 struct lock_file index_lock = LOCK_INIT;
2431 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2432 if (repo_read_index(r) < 0) {
2433 rollback_lock_file(&index_lock);
2434 return error(_("git %s: failed to read the index"),
2435 action_name(opts));
2437 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2439 if (index_fd >= 0) {
2440 if (write_locked_index(r->index, &index_lock,
2441 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2442 return error(_("git %s: failed to refresh the index"),
2443 action_name(opts));
2448 * If we are resolving merges in any way other than "ort", then
2449 * expand the sparse index.
2451 if (opts->strategy && strcmp(opts->strategy, "ort"))
2452 ensure_full_index(r->index);
2453 return 0;
2456 void todo_list_release(struct todo_list *todo_list)
2458 strbuf_release(&todo_list->buf);
2459 FREE_AND_NULL(todo_list->items);
2460 todo_list->nr = todo_list->alloc = 0;
2463 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2465 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2466 todo_list->total_nr++;
2467 return todo_list->items + todo_list->nr++;
2470 const char *todo_item_get_arg(struct todo_list *todo_list,
2471 struct todo_item *item)
2473 return todo_list->buf.buf + item->arg_offset;
2476 static int is_command(enum todo_command command, const char **bol)
2478 const char *str = todo_command_info[command].str;
2479 const char nick = todo_command_info[command].c;
2480 const char *p = *bol;
2482 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2483 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2484 (*bol = p);
2487 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2489 switch (command) {
2490 case TODO_LABEL:
2492 * '#' is not a valid label as the merge command uses it to
2493 * separate merge parents from the commit subject.
2495 if (!strcmp(arg, "#") ||
2496 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2497 return error(_("'%s' is not a valid label"), arg);
2498 break;
2500 case TODO_UPDATE_REF:
2501 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2502 return error(_("'%s' is not a valid refname"), arg);
2503 if (check_refname_format(arg, 0))
2504 return error(_("update-ref requires a fully qualified "
2505 "refname e.g. refs/heads/%s"), arg);
2506 break;
2508 default:
2509 BUG("unexpected todo_command");
2512 return 0;
2515 static int parse_insn_line(struct repository *r, struct todo_item *item,
2516 const char *buf, const char *bol, char *eol)
2518 struct object_id commit_oid;
2519 char *end_of_object_name;
2520 int i, saved, status, padding;
2522 item->flags = 0;
2524 /* left-trim */
2525 bol += strspn(bol, " \t");
2527 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2528 item->command = TODO_COMMENT;
2529 item->commit = NULL;
2530 item->arg_offset = bol - buf;
2531 item->arg_len = eol - bol;
2532 return 0;
2535 for (i = 0; i < TODO_COMMENT; i++)
2536 if (is_command(i, &bol)) {
2537 item->command = i;
2538 break;
2540 if (i >= TODO_COMMENT)
2541 return error(_("invalid command '%.*s'"),
2542 (int)strcspn(bol, " \t\r\n"), bol);
2544 /* Eat up extra spaces/ tabs before object name */
2545 padding = strspn(bol, " \t");
2546 bol += padding;
2548 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2549 if (bol != eol)
2550 return error(_("%s does not accept arguments: '%s'"),
2551 command_to_string(item->command), bol);
2552 item->commit = NULL;
2553 item->arg_offset = bol - buf;
2554 item->arg_len = eol - bol;
2555 return 0;
2558 if (!padding)
2559 return error(_("missing arguments for %s"),
2560 command_to_string(item->command));
2562 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2563 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2564 int ret = 0;
2566 item->commit = NULL;
2567 item->arg_offset = bol - buf;
2568 item->arg_len = (int)(eol - bol);
2569 if (item->command == TODO_LABEL ||
2570 item->command == TODO_UPDATE_REF) {
2571 saved = *eol;
2572 *eol = '\0';
2573 ret = check_label_or_ref_arg(item->command, bol);
2574 *eol = saved;
2576 return ret;
2579 if (item->command == TODO_FIXUP) {
2580 if (skip_prefix(bol, "-C", &bol)) {
2581 bol += strspn(bol, " \t");
2582 item->flags |= TODO_REPLACE_FIXUP_MSG;
2583 } else if (skip_prefix(bol, "-c", &bol)) {
2584 bol += strspn(bol, " \t");
2585 item->flags |= TODO_EDIT_FIXUP_MSG;
2589 if (item->command == TODO_MERGE) {
2590 if (skip_prefix(bol, "-C", &bol))
2591 bol += strspn(bol, " \t");
2592 else if (skip_prefix(bol, "-c", &bol)) {
2593 bol += strspn(bol, " \t");
2594 item->flags |= TODO_EDIT_MERGE_MSG;
2595 } else {
2596 item->flags |= TODO_EDIT_MERGE_MSG;
2597 item->commit = NULL;
2598 item->arg_offset = bol - buf;
2599 item->arg_len = (int)(eol - bol);
2600 return 0;
2604 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2605 saved = *end_of_object_name;
2606 *end_of_object_name = '\0';
2607 status = get_oid(bol, &commit_oid);
2608 if (status < 0)
2609 error(_("could not parse '%s'"), bol); /* return later */
2610 *end_of_object_name = saved;
2612 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2613 item->arg_offset = bol - buf;
2614 item->arg_len = (int)(eol - bol);
2616 if (status < 0)
2617 return status;
2619 item->commit = lookup_commit_reference(r, &commit_oid);
2620 return item->commit ? 0 : -1;
2623 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2625 const char *todo_file, *bol;
2626 struct strbuf buf = STRBUF_INIT;
2627 int ret = 0;
2629 todo_file = git_path_todo_file();
2630 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2631 if (errno == ENOENT || errno == ENOTDIR)
2632 return -1;
2633 else
2634 return error_errno("unable to open '%s'", todo_file);
2636 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2637 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2638 *action = REPLAY_PICK;
2639 else if (is_command(TODO_REVERT, &bol) &&
2640 (*bol == ' ' || *bol == '\t'))
2641 *action = REPLAY_REVERT;
2642 else
2643 ret = -1;
2645 strbuf_release(&buf);
2647 return ret;
2650 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2651 struct todo_list *todo_list)
2653 struct todo_item *item;
2654 char *p = buf, *next_p;
2655 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2657 todo_list->current = todo_list->nr = 0;
2659 for (i = 1; *p; i++, p = next_p) {
2660 char *eol = strchrnul(p, '\n');
2662 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2664 if (p != eol && eol[-1] == '\r')
2665 eol--; /* strip Carriage Return */
2667 item = append_new_todo(todo_list);
2668 item->offset_in_buf = p - todo_list->buf.buf;
2669 if (parse_insn_line(r, item, buf, p, eol)) {
2670 res = error(_("invalid line %d: %.*s"),
2671 i, (int)(eol - p), p);
2672 item->command = TODO_COMMENT + 1;
2673 item->arg_offset = p - buf;
2674 item->arg_len = (int)(eol - p);
2675 item->commit = NULL;
2678 if (fixup_okay)
2679 ; /* do nothing */
2680 else if (is_fixup(item->command))
2681 return error(_("cannot '%s' without a previous commit"),
2682 command_to_string(item->command));
2683 else if (!is_noop(item->command))
2684 fixup_okay = 1;
2687 return res;
2690 static int count_commands(struct todo_list *todo_list)
2692 int count = 0, i;
2694 for (i = 0; i < todo_list->nr; i++)
2695 if (todo_list->items[i].command != TODO_COMMENT)
2696 count++;
2698 return count;
2701 static int get_item_line_offset(struct todo_list *todo_list, int index)
2703 return index < todo_list->nr ?
2704 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2707 static const char *get_item_line(struct todo_list *todo_list, int index)
2709 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2712 static int get_item_line_length(struct todo_list *todo_list, int index)
2714 return get_item_line_offset(todo_list, index + 1)
2715 - get_item_line_offset(todo_list, index);
2718 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2720 int fd;
2721 ssize_t len;
2723 fd = open(path, O_RDONLY);
2724 if (fd < 0)
2725 return error_errno(_("could not open '%s'"), path);
2726 len = strbuf_read(sb, fd, 0);
2727 close(fd);
2728 if (len < 0)
2729 return error(_("could not read '%s'."), path);
2730 return len;
2733 static int have_finished_the_last_pick(void)
2735 struct strbuf buf = STRBUF_INIT;
2736 const char *eol;
2737 const char *todo_path = git_path_todo_file();
2738 int ret = 0;
2740 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2741 if (errno == ENOENT) {
2742 return 0;
2743 } else {
2744 error_errno("unable to open '%s'", todo_path);
2745 return 0;
2748 /* If there is only one line then we are done */
2749 eol = strchr(buf.buf, '\n');
2750 if (!eol || !eol[1])
2751 ret = 1;
2753 strbuf_release(&buf);
2755 return ret;
2758 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2760 struct replay_opts opts = REPLAY_OPTS_INIT;
2761 int need_cleanup = 0;
2763 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2764 if (!refs_delete_ref(get_main_ref_store(r), "",
2765 "CHERRY_PICK_HEAD", NULL, 0) &&
2766 verbose)
2767 warning(_("cancelling a cherry picking in progress"));
2768 opts.action = REPLAY_PICK;
2769 need_cleanup = 1;
2772 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2773 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2774 NULL, 0) &&
2775 verbose)
2776 warning(_("cancelling a revert in progress"));
2777 opts.action = REPLAY_REVERT;
2778 need_cleanup = 1;
2781 unlink(git_path_auto_merge(r));
2783 if (!need_cleanup)
2784 return;
2786 if (!have_finished_the_last_pick())
2787 return;
2789 sequencer_remove_state(&opts);
2792 static void todo_list_write_total_nr(struct todo_list *todo_list)
2794 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2796 if (f) {
2797 fprintf(f, "%d\n", todo_list->total_nr);
2798 fclose(f);
2802 static int read_populate_todo(struct repository *r,
2803 struct todo_list *todo_list,
2804 struct replay_opts *opts)
2806 const char *todo_file = get_todo_path(opts);
2807 int res;
2809 strbuf_reset(&todo_list->buf);
2810 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2811 return -1;
2813 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2814 if (res) {
2815 if (is_rebase_i(opts))
2816 return error(_("please fix this using "
2817 "'git rebase --edit-todo'."));
2818 return error(_("unusable instruction sheet: '%s'"), todo_file);
2821 if (!todo_list->nr &&
2822 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2823 return error(_("no commits parsed."));
2825 if (!is_rebase_i(opts)) {
2826 enum todo_command valid =
2827 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2828 int i;
2830 for (i = 0; i < todo_list->nr; i++)
2831 if (valid == todo_list->items[i].command)
2832 continue;
2833 else if (valid == TODO_PICK)
2834 return error(_("cannot cherry-pick during a revert."));
2835 else
2836 return error(_("cannot revert during a cherry-pick."));
2839 if (is_rebase_i(opts)) {
2840 struct todo_list done = TODO_LIST_INIT;
2842 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2843 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2844 todo_list->done_nr = count_commands(&done);
2845 else
2846 todo_list->done_nr = 0;
2848 todo_list->total_nr = todo_list->done_nr
2849 + count_commands(todo_list);
2850 todo_list_release(&done);
2852 todo_list_write_total_nr(todo_list);
2855 return 0;
2858 static int git_config_string_dup(char **dest,
2859 const char *var, const char *value)
2861 if (!value)
2862 return config_error_nonbool(var);
2863 free(*dest);
2864 *dest = xstrdup(value);
2865 return 0;
2868 static int populate_opts_cb(const char *key, const char *value, void *data)
2870 struct replay_opts *opts = data;
2871 int error_flag = 1;
2873 if (!value)
2874 error_flag = 0;
2875 else if (!strcmp(key, "options.no-commit"))
2876 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2877 else if (!strcmp(key, "options.edit"))
2878 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2879 else if (!strcmp(key, "options.allow-empty"))
2880 opts->allow_empty =
2881 git_config_bool_or_int(key, value, &error_flag);
2882 else if (!strcmp(key, "options.allow-empty-message"))
2883 opts->allow_empty_message =
2884 git_config_bool_or_int(key, value, &error_flag);
2885 else if (!strcmp(key, "options.keep-redundant-commits"))
2886 opts->keep_redundant_commits =
2887 git_config_bool_or_int(key, value, &error_flag);
2888 else if (!strcmp(key, "options.signoff"))
2889 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2890 else if (!strcmp(key, "options.record-origin"))
2891 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2892 else if (!strcmp(key, "options.allow-ff"))
2893 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2894 else if (!strcmp(key, "options.mainline"))
2895 opts->mainline = git_config_int(key, value);
2896 else if (!strcmp(key, "options.strategy"))
2897 git_config_string_dup(&opts->strategy, key, value);
2898 else if (!strcmp(key, "options.gpg-sign"))
2899 git_config_string_dup(&opts->gpg_sign, key, value);
2900 else if (!strcmp(key, "options.strategy-option")) {
2901 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2902 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2903 } else if (!strcmp(key, "options.allow-rerere-auto"))
2904 opts->allow_rerere_auto =
2905 git_config_bool_or_int(key, value, &error_flag) ?
2906 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2907 else if (!strcmp(key, "options.default-msg-cleanup")) {
2908 opts->explicit_cleanup = 1;
2909 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2910 } else
2911 return error(_("invalid key: %s"), key);
2913 if (!error_flag)
2914 return error(_("invalid value for '%s': '%s'"), key, value);
2916 return 0;
2919 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2921 int i;
2922 int count;
2923 char *strategy_opts_string = raw_opts;
2925 if (*strategy_opts_string == ' ')
2926 strategy_opts_string++;
2928 count = split_cmdline(strategy_opts_string,
2929 (const char ***)&opts->xopts);
2930 if (count < 0)
2931 die(_("could not split '%s': %s"), strategy_opts_string,
2932 split_cmdline_strerror(count));
2933 opts->xopts_nr = count;
2934 for (i = 0; i < opts->xopts_nr; i++) {
2935 const char *arg = opts->xopts[i];
2937 skip_prefix(arg, "--", &arg);
2938 opts->xopts[i] = xstrdup(arg);
2942 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2944 strbuf_reset(buf);
2945 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2946 return;
2947 free(opts->strategy);
2948 opts->strategy = strbuf_detach(buf, NULL);
2949 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2950 return;
2952 parse_strategy_opts(opts, buf->buf);
2955 static int read_populate_opts(struct replay_opts *opts)
2957 if (is_rebase_i(opts)) {
2958 struct strbuf buf = STRBUF_INIT;
2959 int ret = 0;
2961 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2962 READ_ONELINER_SKIP_IF_EMPTY)) {
2963 if (!starts_with(buf.buf, "-S"))
2964 strbuf_reset(&buf);
2965 else {
2966 free(opts->gpg_sign);
2967 opts->gpg_sign = xstrdup(buf.buf + 2);
2969 strbuf_reset(&buf);
2972 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2973 READ_ONELINER_SKIP_IF_EMPTY)) {
2974 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2975 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2976 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2977 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2978 strbuf_reset(&buf);
2981 if (file_exists(rebase_path_verbose()))
2982 opts->verbose = 1;
2984 if (file_exists(rebase_path_quiet()))
2985 opts->quiet = 1;
2987 if (file_exists(rebase_path_signoff())) {
2988 opts->allow_ff = 0;
2989 opts->signoff = 1;
2992 if (file_exists(rebase_path_cdate_is_adate())) {
2993 opts->allow_ff = 0;
2994 opts->committer_date_is_author_date = 1;
2997 if (file_exists(rebase_path_ignore_date())) {
2998 opts->allow_ff = 0;
2999 opts->ignore_date = 1;
3002 if (file_exists(rebase_path_reschedule_failed_exec()))
3003 opts->reschedule_failed_exec = 1;
3004 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3005 opts->reschedule_failed_exec = 0;
3007 if (file_exists(rebase_path_drop_redundant_commits()))
3008 opts->drop_redundant_commits = 1;
3010 if (file_exists(rebase_path_keep_redundant_commits()))
3011 opts->keep_redundant_commits = 1;
3013 read_strategy_opts(opts, &buf);
3014 strbuf_reset(&buf);
3016 if (read_oneliner(&opts->current_fixups,
3017 rebase_path_current_fixups(),
3018 READ_ONELINER_SKIP_IF_EMPTY)) {
3019 const char *p = opts->current_fixups.buf;
3020 opts->current_fixup_count = 1;
3021 while ((p = strchr(p, '\n'))) {
3022 opts->current_fixup_count++;
3023 p++;
3027 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3028 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
3029 ret = error(_("unusable squash-onto"));
3030 goto done_rebase_i;
3032 opts->have_squash_onto = 1;
3035 done_rebase_i:
3036 strbuf_release(&buf);
3037 return ret;
3040 if (!file_exists(git_path_opts_file()))
3041 return 0;
3043 * The function git_parse_source(), called from git_config_from_file(),
3044 * may die() in case of a syntactically incorrect file. We do not care
3045 * about this case, though, because we wrote that file ourselves, so we
3046 * are pretty certain that it is syntactically correct.
3048 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3049 return error(_("malformed options sheet: '%s'"),
3050 git_path_opts_file());
3051 return 0;
3054 static void write_strategy_opts(struct replay_opts *opts)
3056 int i;
3057 struct strbuf buf = STRBUF_INIT;
3059 for (i = 0; i < opts->xopts_nr; ++i)
3060 strbuf_addf(&buf, " --%s", opts->xopts[i]);
3062 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3063 strbuf_release(&buf);
3066 int write_basic_state(struct replay_opts *opts, const char *head_name,
3067 struct commit *onto, const struct object_id *orig_head)
3069 if (head_name)
3070 write_file(rebase_path_head_name(), "%s\n", head_name);
3071 if (onto)
3072 write_file(rebase_path_onto(), "%s\n",
3073 oid_to_hex(&onto->object.oid));
3074 if (orig_head)
3075 write_file(rebase_path_orig_head(), "%s\n",
3076 oid_to_hex(orig_head));
3078 if (opts->quiet)
3079 write_file(rebase_path_quiet(), "%s", "");
3080 if (opts->verbose)
3081 write_file(rebase_path_verbose(), "%s", "");
3082 if (opts->strategy)
3083 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3084 if (opts->xopts_nr > 0)
3085 write_strategy_opts(opts);
3087 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3088 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3089 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3090 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3092 if (opts->gpg_sign)
3093 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3094 if (opts->signoff)
3095 write_file(rebase_path_signoff(), "--signoff\n");
3096 if (opts->drop_redundant_commits)
3097 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3098 if (opts->keep_redundant_commits)
3099 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3100 if (opts->committer_date_is_author_date)
3101 write_file(rebase_path_cdate_is_adate(), "%s", "");
3102 if (opts->ignore_date)
3103 write_file(rebase_path_ignore_date(), "%s", "");
3104 if (opts->reschedule_failed_exec)
3105 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3106 else
3107 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3109 return 0;
3112 static int walk_revs_populate_todo(struct todo_list *todo_list,
3113 struct replay_opts *opts)
3115 enum todo_command command = opts->action == REPLAY_PICK ?
3116 TODO_PICK : TODO_REVERT;
3117 const char *command_string = todo_command_info[command].str;
3118 const char *encoding;
3119 struct commit *commit;
3121 if (prepare_revs(opts))
3122 return -1;
3124 encoding = get_log_output_encoding();
3126 while ((commit = get_revision(opts->revs))) {
3127 struct todo_item *item = append_new_todo(todo_list);
3128 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3129 const char *subject;
3130 int subject_len;
3132 item->command = command;
3133 item->commit = commit;
3134 item->arg_offset = 0;
3135 item->arg_len = 0;
3136 item->offset_in_buf = todo_list->buf.len;
3137 subject_len = find_commit_subject(commit_buffer, &subject);
3138 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3139 short_commit_name(commit), subject_len, subject);
3140 unuse_commit_buffer(commit, commit_buffer);
3143 if (!todo_list->nr)
3144 return error(_("empty commit set passed"));
3146 return 0;
3149 static int create_seq_dir(struct repository *r)
3151 enum replay_action action;
3152 const char *in_progress_error = NULL;
3153 const char *in_progress_advice = NULL;
3154 unsigned int advise_skip =
3155 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3156 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3158 if (!sequencer_get_last_command(r, &action)) {
3159 switch (action) {
3160 case REPLAY_REVERT:
3161 in_progress_error = _("revert is already in progress");
3162 in_progress_advice =
3163 _("try \"git revert (--continue | %s--abort | --quit)\"");
3164 break;
3165 case REPLAY_PICK:
3166 in_progress_error = _("cherry-pick is already in progress");
3167 in_progress_advice =
3168 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3169 break;
3170 default:
3171 BUG("unexpected action in create_seq_dir");
3174 if (in_progress_error) {
3175 error("%s", in_progress_error);
3176 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3177 advise(in_progress_advice,
3178 advise_skip ? "--skip | " : "");
3179 return -1;
3181 if (mkdir(git_path_seq_dir(), 0777) < 0)
3182 return error_errno(_("could not create sequencer directory '%s'"),
3183 git_path_seq_dir());
3185 return 0;
3188 static int save_head(const char *head)
3190 struct lock_file head_lock = LOCK_INIT;
3191 struct strbuf buf = STRBUF_INIT;
3192 int fd;
3193 ssize_t written;
3195 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3196 if (fd < 0)
3197 return error_errno(_("could not lock HEAD"));
3198 strbuf_addf(&buf, "%s\n", head);
3199 written = write_in_full(fd, buf.buf, buf.len);
3200 strbuf_release(&buf);
3201 if (written < 0) {
3202 error_errno(_("could not write to '%s'"), git_path_head_file());
3203 rollback_lock_file(&head_lock);
3204 return -1;
3206 if (commit_lock_file(&head_lock) < 0)
3207 return error(_("failed to finalize '%s'"), git_path_head_file());
3208 return 0;
3211 static int rollback_is_safe(void)
3213 struct strbuf sb = STRBUF_INIT;
3214 struct object_id expected_head, actual_head;
3216 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3217 strbuf_trim(&sb);
3218 if (get_oid_hex(sb.buf, &expected_head)) {
3219 strbuf_release(&sb);
3220 die(_("could not parse %s"), git_path_abort_safety_file());
3222 strbuf_release(&sb);
3224 else if (errno == ENOENT)
3225 oidclr(&expected_head);
3226 else
3227 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3229 if (get_oid("HEAD", &actual_head))
3230 oidclr(&actual_head);
3232 return oideq(&actual_head, &expected_head);
3235 static int reset_merge(const struct object_id *oid)
3237 struct child_process cmd = CHILD_PROCESS_INIT;
3239 cmd.git_cmd = 1;
3240 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3242 if (!is_null_oid(oid))
3243 strvec_push(&cmd.args, oid_to_hex(oid));
3245 return run_command(&cmd);
3248 static int rollback_single_pick(struct repository *r)
3250 struct object_id head_oid;
3252 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3253 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3254 return error(_("no cherry-pick or revert in progress"));
3255 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3256 return error(_("cannot resolve HEAD"));
3257 if (is_null_oid(&head_oid))
3258 return error(_("cannot abort from a branch yet to be born"));
3259 return reset_merge(&head_oid);
3262 static int skip_single_pick(void)
3264 struct object_id head;
3266 if (read_ref_full("HEAD", 0, &head, NULL))
3267 return error(_("cannot resolve HEAD"));
3268 return reset_merge(&head);
3271 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3273 FILE *f;
3274 struct object_id oid;
3275 struct strbuf buf = STRBUF_INIT;
3276 const char *p;
3278 f = fopen(git_path_head_file(), "r");
3279 if (!f && errno == ENOENT) {
3281 * There is no multiple-cherry-pick in progress.
3282 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3283 * a single-cherry-pick in progress, abort that.
3285 return rollback_single_pick(r);
3287 if (!f)
3288 return error_errno(_("cannot open '%s'"), git_path_head_file());
3289 if (strbuf_getline_lf(&buf, f)) {
3290 error(_("cannot read '%s': %s"), git_path_head_file(),
3291 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3292 fclose(f);
3293 goto fail;
3295 fclose(f);
3296 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3297 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3298 git_path_head_file());
3299 goto fail;
3301 if (is_null_oid(&oid)) {
3302 error(_("cannot abort from a branch yet to be born"));
3303 goto fail;
3306 if (!rollback_is_safe()) {
3307 /* Do not error, just do not rollback */
3308 warning(_("You seem to have moved HEAD. "
3309 "Not rewinding, check your HEAD!"));
3310 } else
3311 if (reset_merge(&oid))
3312 goto fail;
3313 strbuf_release(&buf);
3314 return sequencer_remove_state(opts);
3315 fail:
3316 strbuf_release(&buf);
3317 return -1;
3320 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3322 enum replay_action action = -1;
3323 sequencer_get_last_command(r, &action);
3326 * Check whether the subcommand requested to skip the commit is actually
3327 * in progress and that it's safe to skip the commit.
3329 * opts->action tells us which subcommand requested to skip the commit.
3330 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3331 * action is in progress and we can skip the commit.
3333 * Otherwise we check that the last instruction was related to the
3334 * particular subcommand we're trying to execute and barf if that's not
3335 * the case.
3337 * Finally we check that the rollback is "safe", i.e., has the HEAD
3338 * moved? In this case, it doesn't make sense to "reset the merge" and
3339 * "skip the commit" as the user already handled this by committing. But
3340 * we'd not want to barf here, instead give advice on how to proceed. We
3341 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3342 * it gets removed when the user commits, so if it still exists we're
3343 * sure the user can't have committed before.
3345 switch (opts->action) {
3346 case REPLAY_REVERT:
3347 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3348 if (action != REPLAY_REVERT)
3349 return error(_("no revert in progress"));
3350 if (!rollback_is_safe())
3351 goto give_advice;
3353 break;
3354 case REPLAY_PICK:
3355 if (!refs_ref_exists(get_main_ref_store(r),
3356 "CHERRY_PICK_HEAD")) {
3357 if (action != REPLAY_PICK)
3358 return error(_("no cherry-pick in progress"));
3359 if (!rollback_is_safe())
3360 goto give_advice;
3362 break;
3363 default:
3364 BUG("unexpected action in sequencer_skip");
3367 if (skip_single_pick())
3368 return error(_("failed to skip the commit"));
3369 if (!is_directory(git_path_seq_dir()))
3370 return 0;
3372 return sequencer_continue(r, opts);
3374 give_advice:
3375 error(_("there is nothing to skip"));
3377 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3378 advise(_("have you committed already?\n"
3379 "try \"git %s --continue\""),
3380 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3382 return -1;
3385 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3387 struct lock_file todo_lock = LOCK_INIT;
3388 const char *todo_path = get_todo_path(opts);
3389 int next = todo_list->current, offset, fd;
3392 * rebase -i writes "git-rebase-todo" without the currently executing
3393 * command, appending it to "done" instead.
3395 if (is_rebase_i(opts))
3396 next++;
3398 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3399 if (fd < 0)
3400 return error_errno(_("could not lock '%s'"), todo_path);
3401 offset = get_item_line_offset(todo_list, next);
3402 if (write_in_full(fd, todo_list->buf.buf + offset,
3403 todo_list->buf.len - offset) < 0)
3404 return error_errno(_("could not write to '%s'"), todo_path);
3405 if (commit_lock_file(&todo_lock) < 0)
3406 return error(_("failed to finalize '%s'"), todo_path);
3408 if (is_rebase_i(opts) && next > 0) {
3409 const char *done = rebase_path_done();
3410 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3411 int ret = 0;
3413 if (fd < 0)
3414 return 0;
3415 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3416 get_item_line_length(todo_list, next - 1))
3417 < 0)
3418 ret = error_errno(_("could not write to '%s'"), done);
3419 if (close(fd) < 0)
3420 ret = error_errno(_("failed to finalize '%s'"), done);
3421 return ret;
3423 return 0;
3426 static int save_opts(struct replay_opts *opts)
3428 const char *opts_file = git_path_opts_file();
3429 int res = 0;
3431 if (opts->no_commit)
3432 res |= git_config_set_in_file_gently(opts_file,
3433 "options.no-commit", "true");
3434 if (opts->edit >= 0)
3435 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3436 opts->edit ? "true" : "false");
3437 if (opts->allow_empty)
3438 res |= git_config_set_in_file_gently(opts_file,
3439 "options.allow-empty", "true");
3440 if (opts->allow_empty_message)
3441 res |= git_config_set_in_file_gently(opts_file,
3442 "options.allow-empty-message", "true");
3443 if (opts->keep_redundant_commits)
3444 res |= git_config_set_in_file_gently(opts_file,
3445 "options.keep-redundant-commits", "true");
3446 if (opts->signoff)
3447 res |= git_config_set_in_file_gently(opts_file,
3448 "options.signoff", "true");
3449 if (opts->record_origin)
3450 res |= git_config_set_in_file_gently(opts_file,
3451 "options.record-origin", "true");
3452 if (opts->allow_ff)
3453 res |= git_config_set_in_file_gently(opts_file,
3454 "options.allow-ff", "true");
3455 if (opts->mainline) {
3456 struct strbuf buf = STRBUF_INIT;
3457 strbuf_addf(&buf, "%d", opts->mainline);
3458 res |= git_config_set_in_file_gently(opts_file,
3459 "options.mainline", buf.buf);
3460 strbuf_release(&buf);
3462 if (opts->strategy)
3463 res |= git_config_set_in_file_gently(opts_file,
3464 "options.strategy", opts->strategy);
3465 if (opts->gpg_sign)
3466 res |= git_config_set_in_file_gently(opts_file,
3467 "options.gpg-sign", opts->gpg_sign);
3468 if (opts->xopts) {
3469 int i;
3470 for (i = 0; i < opts->xopts_nr; i++)
3471 res |= git_config_set_multivar_in_file_gently(opts_file,
3472 "options.strategy-option",
3473 opts->xopts[i], "^$", 0);
3475 if (opts->allow_rerere_auto)
3476 res |= git_config_set_in_file_gently(opts_file,
3477 "options.allow-rerere-auto",
3478 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3479 "true" : "false");
3481 if (opts->explicit_cleanup)
3482 res |= git_config_set_in_file_gently(opts_file,
3483 "options.default-msg-cleanup",
3484 describe_cleanup_mode(opts->default_msg_cleanup));
3485 return res;
3488 static int make_patch(struct repository *r,
3489 struct commit *commit,
3490 struct replay_opts *opts)
3492 struct strbuf buf = STRBUF_INIT;
3493 struct rev_info log_tree_opt;
3494 const char *subject;
3495 char hex[GIT_MAX_HEXSZ + 1];
3496 int res = 0;
3498 oid_to_hex_r(hex, &commit->object.oid);
3499 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3500 return -1;
3501 res |= write_rebase_head(&commit->object.oid);
3503 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3504 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3505 repo_init_revisions(r, &log_tree_opt, NULL);
3506 log_tree_opt.abbrev = 0;
3507 log_tree_opt.diff = 1;
3508 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3509 log_tree_opt.disable_stdin = 1;
3510 log_tree_opt.no_commit_id = 1;
3511 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3512 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3513 if (!log_tree_opt.diffopt.file)
3514 res |= error_errno(_("could not open '%s'"), buf.buf);
3515 else {
3516 res |= log_tree_commit(&log_tree_opt, commit);
3517 fclose(log_tree_opt.diffopt.file);
3519 strbuf_reset(&buf);
3521 strbuf_addf(&buf, "%s/message", get_dir(opts));
3522 if (!file_exists(buf.buf)) {
3523 const char *encoding = get_commit_output_encoding();
3524 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3525 find_commit_subject(commit_buffer, &subject);
3526 res |= write_message(subject, strlen(subject), buf.buf, 1);
3527 unuse_commit_buffer(commit, commit_buffer);
3529 strbuf_release(&buf);
3530 release_revisions(&log_tree_opt);
3532 return res;
3535 static int intend_to_amend(void)
3537 struct object_id head;
3538 char *p;
3540 if (get_oid("HEAD", &head))
3541 return error(_("cannot read HEAD"));
3543 p = oid_to_hex(&head);
3544 return write_message(p, strlen(p), rebase_path_amend(), 1);
3547 static int error_with_patch(struct repository *r,
3548 struct commit *commit,
3549 const char *subject, int subject_len,
3550 struct replay_opts *opts,
3551 int exit_code, int to_amend)
3553 if (commit) {
3554 if (make_patch(r, commit, opts))
3555 return -1;
3556 } else if (copy_file(rebase_path_message(),
3557 git_path_merge_msg(r), 0666))
3558 return error(_("unable to copy '%s' to '%s'"),
3559 git_path_merge_msg(r), rebase_path_message());
3561 if (to_amend) {
3562 if (intend_to_amend())
3563 return -1;
3565 fprintf(stderr,
3566 _("You can amend the commit now, with\n"
3567 "\n"
3568 " git commit --amend %s\n"
3569 "\n"
3570 "Once you are satisfied with your changes, run\n"
3571 "\n"
3572 " git rebase --continue\n"),
3573 gpg_sign_opt_quoted(opts));
3574 } else if (exit_code) {
3575 if (commit)
3576 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3577 short_commit_name(commit), subject_len, subject);
3578 else
3580 * We don't have the hash of the parent so
3581 * just print the line from the todo file.
3583 fprintf_ln(stderr, _("Could not merge %.*s"),
3584 subject_len, subject);
3587 return exit_code;
3590 static int error_failed_squash(struct repository *r,
3591 struct commit *commit,
3592 struct replay_opts *opts,
3593 int subject_len,
3594 const char *subject)
3596 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3597 return error(_("could not copy '%s' to '%s'"),
3598 rebase_path_squash_msg(), rebase_path_message());
3599 unlink(git_path_merge_msg(r));
3600 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3601 return error(_("could not copy '%s' to '%s'"),
3602 rebase_path_message(),
3603 git_path_merge_msg(r));
3604 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3607 static int do_exec(struct repository *r, const char *command_line)
3609 struct child_process cmd = CHILD_PROCESS_INIT;
3610 int dirty, status;
3612 fprintf(stderr, _("Executing: %s\n"), command_line);
3613 cmd.use_shell = 1;
3614 strvec_push(&cmd.args, command_line);
3615 status = run_command(&cmd);
3617 /* force re-reading of the cache */
3618 discard_index(r->index);
3619 if (repo_read_index(r) < 0)
3620 return error(_("could not read index"));
3622 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3624 if (status) {
3625 warning(_("execution failed: %s\n%s"
3626 "You can fix the problem, and then run\n"
3627 "\n"
3628 " git rebase --continue\n"
3629 "\n"),
3630 command_line,
3631 dirty ? N_("and made changes to the index and/or the "
3632 "working tree\n") : "");
3633 if (status == 127)
3634 /* command not found */
3635 status = 1;
3636 } else if (dirty) {
3637 warning(_("execution succeeded: %s\nbut "
3638 "left changes to the index and/or the working tree\n"
3639 "Commit or stash your changes, and then run\n"
3640 "\n"
3641 " git rebase --continue\n"
3642 "\n"), command_line);
3643 status = 1;
3646 return status;
3649 __attribute__((format (printf, 2, 3)))
3650 static int safe_append(const char *filename, const char *fmt, ...)
3652 va_list ap;
3653 struct lock_file lock = LOCK_INIT;
3654 int fd = hold_lock_file_for_update(&lock, filename,
3655 LOCK_REPORT_ON_ERROR);
3656 struct strbuf buf = STRBUF_INIT;
3658 if (fd < 0)
3659 return -1;
3661 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3662 error_errno(_("could not read '%s'"), filename);
3663 rollback_lock_file(&lock);
3664 return -1;
3666 strbuf_complete(&buf, '\n');
3667 va_start(ap, fmt);
3668 strbuf_vaddf(&buf, fmt, ap);
3669 va_end(ap);
3671 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3672 error_errno(_("could not write to '%s'"), filename);
3673 strbuf_release(&buf);
3674 rollback_lock_file(&lock);
3675 return -1;
3677 if (commit_lock_file(&lock) < 0) {
3678 strbuf_release(&buf);
3679 rollback_lock_file(&lock);
3680 return error(_("failed to finalize '%s'"), filename);
3683 strbuf_release(&buf);
3684 return 0;
3687 static int do_label(struct repository *r, const char *name, int len)
3689 struct ref_store *refs = get_main_ref_store(r);
3690 struct ref_transaction *transaction;
3691 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3692 struct strbuf msg = STRBUF_INIT;
3693 int ret = 0;
3694 struct object_id head_oid;
3696 if (len == 1 && *name == '#')
3697 return error(_("illegal label name: '%.*s'"), len, name);
3699 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3700 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3702 transaction = ref_store_transaction_begin(refs, &err);
3703 if (!transaction) {
3704 error("%s", err.buf);
3705 ret = -1;
3706 } else if (get_oid("HEAD", &head_oid)) {
3707 error(_("could not read HEAD"));
3708 ret = -1;
3709 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3710 NULL, 0, msg.buf, &err) < 0 ||
3711 ref_transaction_commit(transaction, &err)) {
3712 error("%s", err.buf);
3713 ret = -1;
3715 ref_transaction_free(transaction);
3716 strbuf_release(&err);
3717 strbuf_release(&msg);
3719 if (!ret)
3720 ret = safe_append(rebase_path_refs_to_delete(),
3721 "%s\n", ref_name.buf);
3722 strbuf_release(&ref_name);
3724 return ret;
3727 static const char *sequencer_reflog_action(struct replay_opts *opts)
3729 if (!opts->reflog_action) {
3730 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3731 opts->reflog_action =
3732 xstrdup(opts->reflog_action ? opts->reflog_action
3733 : action_name(opts));
3736 return opts->reflog_action;
3739 __attribute__((format (printf, 3, 4)))
3740 static const char *reflog_message(struct replay_opts *opts,
3741 const char *sub_action, const char *fmt, ...)
3743 va_list ap;
3744 static struct strbuf buf = STRBUF_INIT;
3746 va_start(ap, fmt);
3747 strbuf_reset(&buf);
3748 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3749 if (sub_action)
3750 strbuf_addf(&buf, " (%s)", sub_action);
3751 if (fmt) {
3752 strbuf_addstr(&buf, ": ");
3753 strbuf_vaddf(&buf, fmt, ap);
3755 va_end(ap);
3757 return buf.buf;
3760 static struct commit *lookup_label(struct repository *r, const char *label,
3761 int len, struct strbuf *buf)
3763 struct commit *commit;
3764 struct object_id oid;
3766 strbuf_reset(buf);
3767 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3768 if (!read_ref(buf->buf, &oid)) {
3769 commit = lookup_commit_object(r, &oid);
3770 } else {
3771 /* fall back to non-rewritten ref or commit */
3772 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3773 commit = lookup_commit_reference_by_name(buf->buf);
3776 if (!commit)
3777 error(_("could not resolve '%s'"), buf->buf);
3779 return commit;
3782 static int do_reset(struct repository *r,
3783 const char *name, int len,
3784 struct replay_opts *opts)
3786 struct strbuf ref_name = STRBUF_INIT;
3787 struct object_id oid;
3788 struct lock_file lock = LOCK_INIT;
3789 struct tree_desc desc = { 0 };
3790 struct tree *tree;
3791 struct unpack_trees_options unpack_tree_opts = { 0 };
3792 int ret = 0;
3794 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3795 return -1;
3797 if (len == 10 && !strncmp("[new root]", name, len)) {
3798 if (!opts->have_squash_onto) {
3799 const char *hex;
3800 if (commit_tree("", 0, the_hash_algo->empty_tree,
3801 NULL, &opts->squash_onto,
3802 NULL, NULL))
3803 return error(_("writing fake root commit"));
3804 opts->have_squash_onto = 1;
3805 hex = oid_to_hex(&opts->squash_onto);
3806 if (write_message(hex, strlen(hex),
3807 rebase_path_squash_onto(), 0))
3808 return error(_("writing squash-onto"));
3810 oidcpy(&oid, &opts->squash_onto);
3811 } else {
3812 int i;
3813 struct commit *commit;
3815 /* Determine the length of the label */
3816 for (i = 0; i < len; i++)
3817 if (isspace(name[i]))
3818 break;
3819 len = i;
3821 commit = lookup_label(r, name, len, &ref_name);
3822 if (!commit) {
3823 ret = -1;
3824 goto cleanup;
3826 oid = commit->object.oid;
3829 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3830 unpack_tree_opts.head_idx = 1;
3831 unpack_tree_opts.src_index = r->index;
3832 unpack_tree_opts.dst_index = r->index;
3833 unpack_tree_opts.fn = oneway_merge;
3834 unpack_tree_opts.merge = 1;
3835 unpack_tree_opts.update = 1;
3836 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3837 unpack_tree_opts.skip_cache_tree_update = 1;
3838 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3840 if (repo_read_index_unmerged(r)) {
3841 ret = error_resolve_conflict(action_name(opts));
3842 goto cleanup;
3845 if (!fill_tree_descriptor(r, &desc, &oid)) {
3846 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3847 goto cleanup;
3850 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3851 ret = -1;
3852 goto cleanup;
3855 tree = parse_tree_indirect(&oid);
3856 prime_cache_tree(r, r->index, tree);
3858 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3859 ret = error(_("could not write index"));
3861 if (!ret)
3862 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3863 len, name), "HEAD", &oid,
3864 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3865 cleanup:
3866 free((void *)desc.buffer);
3867 if (ret < 0)
3868 rollback_lock_file(&lock);
3869 strbuf_release(&ref_name);
3870 clear_unpack_trees_porcelain(&unpack_tree_opts);
3871 return ret;
3874 static int do_merge(struct repository *r,
3875 struct commit *commit,
3876 const char *arg, int arg_len,
3877 int flags, int *check_todo, struct replay_opts *opts)
3879 int run_commit_flags = 0;
3880 struct strbuf ref_name = STRBUF_INIT;
3881 struct commit *head_commit, *merge_commit, *i;
3882 struct commit_list *bases, *j;
3883 struct commit_list *to_merge = NULL, **tail = &to_merge;
3884 const char *strategy = !opts->xopts_nr &&
3885 (!opts->strategy ||
3886 !strcmp(opts->strategy, "recursive") ||
3887 !strcmp(opts->strategy, "ort")) ?
3888 NULL : opts->strategy;
3889 struct merge_options o;
3890 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3891 static struct lock_file lock;
3892 const char *p;
3894 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3895 ret = -1;
3896 goto leave_merge;
3899 head_commit = lookup_commit_reference_by_name("HEAD");
3900 if (!head_commit) {
3901 ret = error(_("cannot merge without a current revision"));
3902 goto leave_merge;
3906 * For octopus merges, the arg starts with the list of revisions to be
3907 * merged. The list is optionally followed by '#' and the oneline.
3909 merge_arg_len = oneline_offset = arg_len;
3910 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3911 if (!*p)
3912 break;
3913 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3914 p += 1 + strspn(p + 1, " \t\n");
3915 oneline_offset = p - arg;
3916 break;
3918 k = strcspn(p, " \t\n");
3919 if (!k)
3920 continue;
3921 merge_commit = lookup_label(r, p, k, &ref_name);
3922 if (!merge_commit) {
3923 ret = error(_("unable to parse '%.*s'"), k, p);
3924 goto leave_merge;
3926 tail = &commit_list_insert(merge_commit, tail)->next;
3927 p += k;
3928 merge_arg_len = p - arg;
3931 if (!to_merge) {
3932 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3933 goto leave_merge;
3936 if (opts->have_squash_onto &&
3937 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3939 * When the user tells us to "merge" something into a
3940 * "[new root]", let's simply fast-forward to the merge head.
3942 rollback_lock_file(&lock);
3943 if (to_merge->next)
3944 ret = error(_("octopus merge cannot be executed on "
3945 "top of a [new root]"));
3946 else
3947 ret = fast_forward_to(r, &to_merge->item->object.oid,
3948 &head_commit->object.oid, 0,
3949 opts);
3950 goto leave_merge;
3954 * If HEAD is not identical to the first parent of the original merge
3955 * commit, we cannot fast-forward.
3957 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3958 oideq(&commit->parents->item->object.oid,
3959 &head_commit->object.oid);
3962 * If any merge head is different from the original one, we cannot
3963 * fast-forward.
3965 if (can_fast_forward) {
3966 struct commit_list *p = commit->parents->next;
3968 for (j = to_merge; j && p; j = j->next, p = p->next)
3969 if (!oideq(&j->item->object.oid,
3970 &p->item->object.oid)) {
3971 can_fast_forward = 0;
3972 break;
3975 * If the number of merge heads differs from the original merge
3976 * commit, we cannot fast-forward.
3978 if (j || p)
3979 can_fast_forward = 0;
3982 if (can_fast_forward) {
3983 rollback_lock_file(&lock);
3984 ret = fast_forward_to(r, &commit->object.oid,
3985 &head_commit->object.oid, 0, opts);
3986 if (flags & TODO_EDIT_MERGE_MSG)
3987 goto fast_forward_edit;
3989 goto leave_merge;
3992 if (commit) {
3993 const char *encoding = get_commit_output_encoding();
3994 const char *message = logmsg_reencode(commit, NULL, encoding);
3995 const char *body;
3996 int len;
3998 if (!message) {
3999 ret = error(_("could not get commit message of '%s'"),
4000 oid_to_hex(&commit->object.oid));
4001 goto leave_merge;
4003 write_author_script(message);
4004 find_commit_subject(message, &body);
4005 len = strlen(body);
4006 ret = write_message(body, len, git_path_merge_msg(r), 0);
4007 unuse_commit_buffer(commit, message);
4008 if (ret) {
4009 error_errno(_("could not write '%s'"),
4010 git_path_merge_msg(r));
4011 goto leave_merge;
4013 } else {
4014 struct strbuf buf = STRBUF_INIT;
4015 int len;
4017 strbuf_addf(&buf, "author %s", git_author_info(0));
4018 write_author_script(buf.buf);
4019 strbuf_reset(&buf);
4021 if (oneline_offset < arg_len) {
4022 p = arg + oneline_offset;
4023 len = arg_len - oneline_offset;
4024 } else {
4025 strbuf_addf(&buf, "Merge %s '%.*s'",
4026 to_merge->next ? "branches" : "branch",
4027 merge_arg_len, arg);
4028 p = buf.buf;
4029 len = buf.len;
4032 ret = write_message(p, len, git_path_merge_msg(r), 0);
4033 strbuf_release(&buf);
4034 if (ret) {
4035 error_errno(_("could not write '%s'"),
4036 git_path_merge_msg(r));
4037 goto leave_merge;
4041 if (strategy || to_merge->next) {
4042 /* Octopus merge */
4043 struct child_process cmd = CHILD_PROCESS_INIT;
4045 if (read_env_script(&cmd.env)) {
4046 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4048 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4049 goto leave_merge;
4052 if (opts->committer_date_is_author_date)
4053 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4054 opts->ignore_date ?
4055 "" :
4056 author_date_from_env(&cmd.env));
4057 if (opts->ignore_date)
4058 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4060 cmd.git_cmd = 1;
4061 strvec_push(&cmd.args, "merge");
4062 strvec_push(&cmd.args, "-s");
4063 if (!strategy)
4064 strvec_push(&cmd.args, "octopus");
4065 else {
4066 strvec_push(&cmd.args, strategy);
4067 for (k = 0; k < opts->xopts_nr; k++)
4068 strvec_pushf(&cmd.args,
4069 "-X%s", opts->xopts[k]);
4071 if (!(flags & TODO_EDIT_MERGE_MSG))
4072 strvec_push(&cmd.args, "--no-edit");
4073 else
4074 strvec_push(&cmd.args, "--edit");
4075 strvec_push(&cmd.args, "--no-ff");
4076 strvec_push(&cmd.args, "--no-log");
4077 strvec_push(&cmd.args, "--no-stat");
4078 strvec_push(&cmd.args, "-F");
4079 strvec_push(&cmd.args, git_path_merge_msg(r));
4080 if (opts->gpg_sign)
4081 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4082 else
4083 strvec_push(&cmd.args, "--no-gpg-sign");
4085 /* Add the tips to be merged */
4086 for (j = to_merge; j; j = j->next)
4087 strvec_push(&cmd.args,
4088 oid_to_hex(&j->item->object.oid));
4090 strbuf_release(&ref_name);
4091 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4092 NULL, 0);
4093 rollback_lock_file(&lock);
4095 ret = run_command(&cmd);
4097 /* force re-reading of the cache */
4098 if (!ret) {
4099 discard_index(r->index);
4100 if (repo_read_index(r) < 0)
4101 ret = error(_("could not read index"));
4103 goto leave_merge;
4106 merge_commit = to_merge->item;
4107 bases = get_merge_bases(head_commit, merge_commit);
4108 if (bases && oideq(&merge_commit->object.oid,
4109 &bases->item->object.oid)) {
4110 ret = 0;
4111 /* skip merging an ancestor of HEAD */
4112 goto leave_merge;
4115 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4116 git_path_merge_head(r), 0);
4117 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4119 bases = reverse_commit_list(bases);
4121 repo_read_index(r);
4122 init_merge_options(&o, r);
4123 o.branch1 = "HEAD";
4124 o.branch2 = ref_name.buf;
4125 o.buffer_output = 2;
4127 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4129 * TODO: Should use merge_incore_recursive() and
4130 * merge_switch_to_result(), skipping the call to
4131 * merge_switch_to_result() when we don't actually need to
4132 * update the index and working copy immediately.
4134 ret = merge_ort_recursive(&o,
4135 head_commit, merge_commit, bases,
4136 &i);
4137 } else {
4138 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4139 &i);
4141 if (ret <= 0)
4142 fputs(o.obuf.buf, stdout);
4143 strbuf_release(&o.obuf);
4144 if (ret < 0) {
4145 error(_("could not even attempt to merge '%.*s'"),
4146 merge_arg_len, arg);
4147 goto leave_merge;
4150 * The return value of merge_recursive() is 1 on clean, and 0 on
4151 * unclean merge.
4153 * Let's reverse that, so that do_merge() returns 0 upon success and
4154 * 1 upon failed merge (keeping the return value -1 for the cases where
4155 * we will want to reschedule the `merge` command).
4157 ret = !ret;
4159 if (r->index->cache_changed &&
4160 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4161 ret = error(_("merge: Unable to write new index file"));
4162 goto leave_merge;
4165 rollback_lock_file(&lock);
4166 if (ret)
4167 repo_rerere(r, opts->allow_rerere_auto);
4168 else
4170 * In case of problems, we now want to return a positive
4171 * value (a negative one would indicate that the `merge`
4172 * command needs to be rescheduled).
4174 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4175 run_commit_flags);
4177 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4178 fast_forward_edit:
4179 *check_todo = 1;
4180 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4181 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4185 leave_merge:
4186 strbuf_release(&ref_name);
4187 rollback_lock_file(&lock);
4188 free_commit_list(to_merge);
4189 return ret;
4192 static int write_update_refs_state(struct string_list *refs_to_oids)
4194 int result = 0;
4195 struct lock_file lock = LOCK_INIT;
4196 FILE *fp = NULL;
4197 struct string_list_item *item;
4198 char *path;
4200 path = rebase_path_update_refs(the_repository->gitdir);
4202 if (!refs_to_oids->nr) {
4203 if (unlink(path) && errno != ENOENT)
4204 result = error_errno(_("could not unlink: %s"), path);
4205 goto cleanup;
4208 if (safe_create_leading_directories(path)) {
4209 result = error(_("unable to create leading directories of %s"),
4210 path);
4211 goto cleanup;
4214 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4215 result = error(_("another 'rebase' process appears to be running; "
4216 "'%s.lock' already exists"),
4217 path);
4218 goto cleanup;
4221 fp = fdopen_lock_file(&lock, "w");
4222 if (!fp) {
4223 result = error_errno(_("could not open '%s' for writing"), path);
4224 rollback_lock_file(&lock);
4225 goto cleanup;
4228 for_each_string_list_item(item, refs_to_oids) {
4229 struct update_ref_record *rec = item->util;
4230 fprintf(fp, "%s\n%s\n%s\n", item->string,
4231 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4234 result = commit_lock_file(&lock);
4236 cleanup:
4237 free(path);
4238 return result;
4242 * Parse the update-refs file for the current rebase, then remove the
4243 * refs that do not appear in the todo_list (and have not had updated
4244 * values stored) and add refs that are in the todo_list but not
4245 * represented in the update-refs file.
4247 * If there are changes to the update-refs list, then write the new state
4248 * to disk.
4250 void todo_list_filter_update_refs(struct repository *r,
4251 struct todo_list *todo_list)
4253 int i;
4254 int updated = 0;
4255 struct string_list update_refs = STRING_LIST_INIT_DUP;
4257 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4260 * For each item in the update_refs list, if it has no updated
4261 * value and does not appear in the todo_list, then remove it
4262 * from the update_refs list.
4264 for (i = 0; i < update_refs.nr; i++) {
4265 int j;
4266 int found = 0;
4267 const char *ref = update_refs.items[i].string;
4268 size_t reflen = strlen(ref);
4269 struct update_ref_record *rec = update_refs.items[i].util;
4271 /* OID already stored as updated. */
4272 if (!is_null_oid(&rec->after))
4273 continue;
4275 for (j = 0; !found && j < todo_list->total_nr; j++) {
4276 struct todo_item *item = &todo_list->items[j];
4277 const char *arg = todo_list->buf.buf + item->arg_offset;
4279 if (item->command != TODO_UPDATE_REF)
4280 continue;
4282 if (item->arg_len != reflen ||
4283 strncmp(arg, ref, reflen))
4284 continue;
4286 found = 1;
4289 if (!found) {
4290 free(update_refs.items[i].string);
4291 free(update_refs.items[i].util);
4293 update_refs.nr--;
4294 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4296 updated = 1;
4297 i--;
4302 * For each todo_item, check if its ref is in the update_refs list.
4303 * If not, then add it as an un-updated ref.
4305 for (i = 0; i < todo_list->total_nr; i++) {
4306 struct todo_item *item = &todo_list->items[i];
4307 const char *arg = todo_list->buf.buf + item->arg_offset;
4308 int j, found = 0;
4310 if (item->command != TODO_UPDATE_REF)
4311 continue;
4313 for (j = 0; !found && j < update_refs.nr; j++) {
4314 const char *ref = update_refs.items[j].string;
4316 found = strlen(ref) == item->arg_len &&
4317 !strncmp(ref, arg, item->arg_len);
4320 if (!found) {
4321 struct string_list_item *inserted;
4322 struct strbuf argref = STRBUF_INIT;
4324 strbuf_add(&argref, arg, item->arg_len);
4325 inserted = string_list_insert(&update_refs, argref.buf);
4326 inserted->util = init_update_ref_record(argref.buf);
4327 strbuf_release(&argref);
4328 updated = 1;
4332 if (updated)
4333 write_update_refs_state(&update_refs);
4334 string_list_clear(&update_refs, 1);
4337 static int do_update_ref(struct repository *r, const char *refname)
4339 struct string_list_item *item;
4340 struct string_list list = STRING_LIST_INIT_DUP;
4342 if (sequencer_get_update_refs_state(r->gitdir, &list))
4343 return -1;
4345 for_each_string_list_item(item, &list) {
4346 if (!strcmp(item->string, refname)) {
4347 struct update_ref_record *rec = item->util;
4348 if (read_ref("HEAD", &rec->after))
4349 return -1;
4350 break;
4354 write_update_refs_state(&list);
4355 string_list_clear(&list, 1);
4356 return 0;
4359 static int do_update_refs(struct repository *r, int quiet)
4361 int res = 0;
4362 struct string_list_item *item;
4363 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4364 struct ref_store *refs = get_main_ref_store(r);
4365 struct strbuf update_msg = STRBUF_INIT;
4366 struct strbuf error_msg = STRBUF_INIT;
4368 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4369 return res;
4371 for_each_string_list_item(item, &refs_to_oids) {
4372 struct update_ref_record *rec = item->util;
4373 int loop_res;
4375 loop_res = refs_update_ref(refs, "rewritten during rebase",
4376 item->string,
4377 &rec->after, &rec->before,
4378 0, UPDATE_REFS_MSG_ON_ERR);
4379 res |= loop_res;
4381 if (quiet)
4382 continue;
4384 if (loop_res)
4385 strbuf_addf(&error_msg, "\t%s\n", item->string);
4386 else
4387 strbuf_addf(&update_msg, "\t%s\n", item->string);
4390 if (!quiet &&
4391 (update_msg.len || error_msg.len)) {
4392 fprintf(stderr,
4393 _("Updated the following refs with %s:\n%s"),
4394 "--update-refs",
4395 update_msg.buf);
4397 if (res)
4398 fprintf(stderr,
4399 _("Failed to update the following refs with %s:\n%s"),
4400 "--update-refs",
4401 error_msg.buf);
4404 string_list_clear(&refs_to_oids, 1);
4405 strbuf_release(&update_msg);
4406 strbuf_release(&error_msg);
4407 return res;
4410 static int is_final_fixup(struct todo_list *todo_list)
4412 int i = todo_list->current;
4414 if (!is_fixup(todo_list->items[i].command))
4415 return 0;
4417 while (++i < todo_list->nr)
4418 if (is_fixup(todo_list->items[i].command))
4419 return 0;
4420 else if (!is_noop(todo_list->items[i].command))
4421 break;
4422 return 1;
4425 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4427 int i;
4429 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4430 if (!is_noop(todo_list->items[i].command))
4431 return todo_list->items[i].command;
4433 return -1;
4436 void create_autostash(struct repository *r, const char *path)
4438 struct strbuf buf = STRBUF_INIT;
4439 struct lock_file lock_file = LOCK_INIT;
4440 int fd;
4442 fd = repo_hold_locked_index(r, &lock_file, 0);
4443 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4444 if (0 <= fd)
4445 repo_update_index_if_able(r, &lock_file);
4446 rollback_lock_file(&lock_file);
4448 if (has_unstaged_changes(r, 1) ||
4449 has_uncommitted_changes(r, 1)) {
4450 struct child_process stash = CHILD_PROCESS_INIT;
4451 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4452 struct object_id oid;
4454 strvec_pushl(&stash.args,
4455 "stash", "create", "autostash", NULL);
4456 stash.git_cmd = 1;
4457 stash.no_stdin = 1;
4458 strbuf_reset(&buf);
4459 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4460 die(_("Cannot autostash"));
4461 strbuf_trim_trailing_newline(&buf);
4462 if (get_oid(buf.buf, &oid))
4463 die(_("Unexpected stash response: '%s'"),
4464 buf.buf);
4465 strbuf_reset(&buf);
4466 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4468 if (safe_create_leading_directories_const(path))
4469 die(_("Could not create directory for '%s'"),
4470 path);
4471 write_file(path, "%s", oid_to_hex(&oid));
4472 printf(_("Created autostash: %s\n"), buf.buf);
4473 if (reset_head(r, &ropts) < 0)
4474 die(_("could not reset --hard"));
4475 discard_index(r->index);
4476 if (repo_read_index(r) < 0)
4477 die(_("could not read index"));
4479 strbuf_release(&buf);
4482 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4484 struct child_process child = CHILD_PROCESS_INIT;
4485 int ret = 0;
4487 if (attempt_apply) {
4488 child.git_cmd = 1;
4489 child.no_stdout = 1;
4490 child.no_stderr = 1;
4491 strvec_push(&child.args, "stash");
4492 strvec_push(&child.args, "apply");
4493 strvec_push(&child.args, stash_oid);
4494 ret = run_command(&child);
4497 if (attempt_apply && !ret)
4498 fprintf(stderr, _("Applied autostash.\n"));
4499 else {
4500 struct child_process store = CHILD_PROCESS_INIT;
4502 store.git_cmd = 1;
4503 strvec_push(&store.args, "stash");
4504 strvec_push(&store.args, "store");
4505 strvec_push(&store.args, "-m");
4506 strvec_push(&store.args, "autostash");
4507 strvec_push(&store.args, "-q");
4508 strvec_push(&store.args, stash_oid);
4509 if (run_command(&store))
4510 ret = error(_("cannot store %s"), stash_oid);
4511 else
4512 fprintf(stderr,
4513 _("%s\n"
4514 "Your changes are safe in the stash.\n"
4515 "You can run \"git stash pop\" or"
4516 " \"git stash drop\" at any time.\n"),
4517 attempt_apply ?
4518 _("Applying autostash resulted in conflicts.") :
4519 _("Autostash exists; creating a new stash entry."));
4522 return ret;
4525 static int apply_save_autostash(const char *path, int attempt_apply)
4527 struct strbuf stash_oid = STRBUF_INIT;
4528 int ret = 0;
4530 if (!read_oneliner(&stash_oid, path,
4531 READ_ONELINER_SKIP_IF_EMPTY)) {
4532 strbuf_release(&stash_oid);
4533 return 0;
4535 strbuf_trim(&stash_oid);
4537 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4539 unlink(path);
4540 strbuf_release(&stash_oid);
4541 return ret;
4544 int save_autostash(const char *path)
4546 return apply_save_autostash(path, 0);
4549 int apply_autostash(const char *path)
4551 return apply_save_autostash(path, 1);
4554 int apply_autostash_oid(const char *stash_oid)
4556 return apply_save_autostash_oid(stash_oid, 1);
4559 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4560 const char *onto_name, const struct object_id *onto,
4561 const struct object_id *orig_head)
4563 struct reset_head_opts ropts = {
4564 .oid = onto,
4565 .orig_head = orig_head,
4566 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4567 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4568 .head_msg = reflog_message(opts, "start", "checkout %s",
4569 onto_name),
4570 .default_reflog_action = sequencer_reflog_action(opts)
4572 if (reset_head(r, &ropts)) {
4573 apply_autostash(rebase_path_autostash());
4574 sequencer_remove_state(opts);
4575 return error(_("could not detach HEAD"));
4578 return 0;
4581 static int stopped_at_head(struct repository *r)
4583 struct object_id head;
4584 struct commit *commit;
4585 struct commit_message message;
4587 if (get_oid("HEAD", &head) ||
4588 !(commit = lookup_commit(r, &head)) ||
4589 parse_commit(commit) || get_message(commit, &message))
4590 fprintf(stderr, _("Stopped at HEAD\n"));
4591 else {
4592 fprintf(stderr, _("Stopped at %s\n"), message.label);
4593 free_message(commit, &message);
4595 return 0;
4599 static int reread_todo_if_changed(struct repository *r,
4600 struct todo_list *todo_list,
4601 struct replay_opts *opts)
4603 int offset;
4604 struct strbuf buf = STRBUF_INIT;
4606 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4607 return -1;
4608 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4609 if (buf.len != todo_list->buf.len - offset ||
4610 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4611 /* Reread the todo file if it has changed. */
4612 todo_list_release(todo_list);
4613 if (read_populate_todo(r, todo_list, opts))
4614 return -1; /* message was printed */
4615 /* `current` will be incremented on return */
4616 todo_list->current = -1;
4618 strbuf_release(&buf);
4620 return 0;
4623 static const char rescheduled_advice[] =
4624 N_("Could not execute the todo command\n"
4625 "\n"
4626 " %.*s"
4627 "\n"
4628 "It has been rescheduled; To edit the command before continuing, please\n"
4629 "edit the todo list first:\n"
4630 "\n"
4631 " git rebase --edit-todo\n"
4632 " git rebase --continue\n");
4634 static int pick_commits(struct repository *r,
4635 struct todo_list *todo_list,
4636 struct replay_opts *opts)
4638 int res = 0, reschedule = 0;
4640 opts->reflog_message = sequencer_reflog_action(opts);
4641 if (opts->allow_ff)
4642 assert(!(opts->signoff || opts->no_commit ||
4643 opts->record_origin || should_edit(opts) ||
4644 opts->committer_date_is_author_date ||
4645 opts->ignore_date));
4646 if (read_and_refresh_cache(r, opts))
4647 return -1;
4649 while (todo_list->current < todo_list->nr) {
4650 struct todo_item *item = todo_list->items + todo_list->current;
4651 const char *arg = todo_item_get_arg(todo_list, item);
4652 int check_todo = 0;
4654 if (save_todo(todo_list, opts))
4655 return -1;
4656 if (is_rebase_i(opts)) {
4657 if (item->command != TODO_COMMENT) {
4658 FILE *f = fopen(rebase_path_msgnum(), "w");
4660 todo_list->done_nr++;
4662 if (f) {
4663 fprintf(f, "%d\n", todo_list->done_nr);
4664 fclose(f);
4666 if (!opts->quiet)
4667 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4668 todo_list->done_nr,
4669 todo_list->total_nr,
4670 opts->verbose ? "\n" : "\r");
4672 unlink(rebase_path_message());
4673 unlink(rebase_path_author_script());
4674 unlink(rebase_path_stopped_sha());
4675 unlink(rebase_path_amend());
4676 unlink(git_path_merge_head(r));
4677 unlink(git_path_auto_merge(r));
4678 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4680 if (item->command == TODO_BREAK) {
4681 if (!opts->verbose)
4682 term_clear_line();
4683 return stopped_at_head(r);
4686 if (item->command <= TODO_SQUASH) {
4687 if (is_rebase_i(opts))
4688 opts->reflog_message = reflog_message(opts,
4689 command_to_string(item->command), NULL);
4691 res = do_pick_commit(r, item, opts,
4692 is_final_fixup(todo_list),
4693 &check_todo);
4694 if (is_rebase_i(opts) && res < 0) {
4695 /* Reschedule */
4696 advise(_(rescheduled_advice),
4697 get_item_line_length(todo_list,
4698 todo_list->current),
4699 get_item_line(todo_list,
4700 todo_list->current));
4701 todo_list->current--;
4702 if (save_todo(todo_list, opts))
4703 return -1;
4705 if (item->command == TODO_EDIT) {
4706 struct commit *commit = item->commit;
4707 if (!res) {
4708 if (!opts->verbose)
4709 term_clear_line();
4710 fprintf(stderr,
4711 _("Stopped at %s... %.*s\n"),
4712 short_commit_name(commit),
4713 item->arg_len, arg);
4715 return error_with_patch(r, commit,
4716 arg, item->arg_len, opts, res, !res);
4718 if (is_rebase_i(opts) && !res)
4719 record_in_rewritten(&item->commit->object.oid,
4720 peek_command(todo_list, 1));
4721 if (res && is_fixup(item->command)) {
4722 if (res == 1)
4723 intend_to_amend();
4724 return error_failed_squash(r, item->commit, opts,
4725 item->arg_len, arg);
4726 } else if (res && is_rebase_i(opts) && item->commit) {
4727 int to_amend = 0;
4728 struct object_id oid;
4731 * If we are rewording and have either
4732 * fast-forwarded already, or are about to
4733 * create a new root commit, we want to amend,
4734 * otherwise we do not.
4736 if (item->command == TODO_REWORD &&
4737 !get_oid("HEAD", &oid) &&
4738 (oideq(&item->commit->object.oid, &oid) ||
4739 (opts->have_squash_onto &&
4740 oideq(&opts->squash_onto, &oid))))
4741 to_amend = 1;
4743 return res | error_with_patch(r, item->commit,
4744 arg, item->arg_len, opts,
4745 res, to_amend);
4747 } else if (item->command == TODO_EXEC) {
4748 char *end_of_arg = (char *)(arg + item->arg_len);
4749 int saved = *end_of_arg;
4751 if (!opts->verbose)
4752 term_clear_line();
4753 *end_of_arg = '\0';
4754 res = do_exec(r, arg);
4755 *end_of_arg = saved;
4757 if (res) {
4758 if (opts->reschedule_failed_exec)
4759 reschedule = 1;
4761 check_todo = 1;
4762 } else if (item->command == TODO_LABEL) {
4763 if ((res = do_label(r, arg, item->arg_len)))
4764 reschedule = 1;
4765 } else if (item->command == TODO_RESET) {
4766 if ((res = do_reset(r, arg, item->arg_len, opts)))
4767 reschedule = 1;
4768 } else if (item->command == TODO_MERGE) {
4769 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4770 item->flags, &check_todo, opts)) < 0)
4771 reschedule = 1;
4772 else if (item->commit)
4773 record_in_rewritten(&item->commit->object.oid,
4774 peek_command(todo_list, 1));
4775 if (res > 0)
4776 /* failed with merge conflicts */
4777 return error_with_patch(r, item->commit,
4778 arg, item->arg_len,
4779 opts, res, 0);
4780 } else if (item->command == TODO_UPDATE_REF) {
4781 struct strbuf ref = STRBUF_INIT;
4782 strbuf_add(&ref, arg, item->arg_len);
4783 if ((res = do_update_ref(r, ref.buf)))
4784 reschedule = 1;
4785 strbuf_release(&ref);
4786 } else if (!is_noop(item->command))
4787 return error(_("unknown command %d"), item->command);
4789 if (reschedule) {
4790 advise(_(rescheduled_advice),
4791 get_item_line_length(todo_list,
4792 todo_list->current),
4793 get_item_line(todo_list, todo_list->current));
4794 todo_list->current--;
4795 if (save_todo(todo_list, opts))
4796 return -1;
4797 if (item->commit)
4798 return error_with_patch(r,
4799 item->commit,
4800 arg, item->arg_len,
4801 opts, res, 0);
4802 } else if (is_rebase_i(opts) && check_todo && !res &&
4803 reread_todo_if_changed(r, todo_list, opts)) {
4804 return -1;
4807 todo_list->current++;
4808 if (res)
4809 return res;
4812 if (is_rebase_i(opts)) {
4813 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4814 struct stat st;
4816 /* Stopped in the middle, as planned? */
4817 if (todo_list->current < todo_list->nr)
4818 return 0;
4820 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4821 starts_with(head_ref.buf, "refs/")) {
4822 const char *msg;
4823 struct object_id head, orig;
4824 int res;
4826 if (get_oid("HEAD", &head)) {
4827 res = error(_("cannot read HEAD"));
4828 cleanup_head_ref:
4829 strbuf_release(&head_ref);
4830 strbuf_release(&buf);
4831 return res;
4833 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4834 get_oid_hex(buf.buf, &orig)) {
4835 res = error(_("could not read orig-head"));
4836 goto cleanup_head_ref;
4838 strbuf_reset(&buf);
4839 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4840 res = error(_("could not read 'onto'"));
4841 goto cleanup_head_ref;
4843 msg = reflog_message(opts, "finish", "%s onto %s",
4844 head_ref.buf, buf.buf);
4845 if (update_ref(msg, head_ref.buf, &head, &orig,
4846 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4847 res = error(_("could not update %s"),
4848 head_ref.buf);
4849 goto cleanup_head_ref;
4851 msg = reflog_message(opts, "finish", "returning to %s",
4852 head_ref.buf);
4853 if (create_symref("HEAD", head_ref.buf, msg)) {
4854 res = error(_("could not update HEAD to %s"),
4855 head_ref.buf);
4856 goto cleanup_head_ref;
4858 strbuf_reset(&buf);
4861 if (opts->verbose) {
4862 struct rev_info log_tree_opt;
4863 struct object_id orig, head;
4865 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4866 repo_init_revisions(r, &log_tree_opt, NULL);
4867 log_tree_opt.diff = 1;
4868 log_tree_opt.diffopt.output_format =
4869 DIFF_FORMAT_DIFFSTAT;
4870 log_tree_opt.disable_stdin = 1;
4872 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4873 !get_oid(buf.buf, &orig) &&
4874 !get_oid("HEAD", &head)) {
4875 diff_tree_oid(&orig, &head, "",
4876 &log_tree_opt.diffopt);
4877 log_tree_diff_flush(&log_tree_opt);
4879 release_revisions(&log_tree_opt);
4881 flush_rewritten_pending();
4882 if (!stat(rebase_path_rewritten_list(), &st) &&
4883 st.st_size > 0) {
4884 struct child_process child = CHILD_PROCESS_INIT;
4885 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4887 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4888 child.git_cmd = 1;
4889 strvec_push(&child.args, "notes");
4890 strvec_push(&child.args, "copy");
4891 strvec_push(&child.args, "--for-rewrite=rebase");
4892 /* we don't care if this copying failed */
4893 run_command(&child);
4895 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4896 strvec_push(&hook_opt.args, "rebase");
4897 run_hooks_opt("post-rewrite", &hook_opt);
4899 apply_autostash(rebase_path_autostash());
4901 if (!opts->quiet) {
4902 if (!opts->verbose)
4903 term_clear_line();
4904 fprintf(stderr,
4905 _("Successfully rebased and updated %s.\n"),
4906 head_ref.buf);
4909 strbuf_release(&buf);
4910 strbuf_release(&head_ref);
4912 if (do_update_refs(r, opts->quiet))
4913 return -1;
4917 * Sequence of picks finished successfully; cleanup by
4918 * removing the .git/sequencer directory
4920 return sequencer_remove_state(opts);
4923 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4925 struct child_process cmd = CHILD_PROCESS_INIT;
4927 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4928 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4929 return error(_("no cherry-pick or revert in progress"));
4931 cmd.git_cmd = 1;
4932 strvec_push(&cmd.args, "commit");
4935 * continue_single_pick() handles the case of recovering from a
4936 * conflict. should_edit() doesn't handle that case; for a conflict,
4937 * we want to edit if the user asked for it, or if they didn't specify
4938 * and stdin is a tty.
4940 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4942 * Include --cleanup=strip as well because we don't want the
4943 * "# Conflicts:" messages.
4945 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4947 return run_command(&cmd);
4950 static int commit_staged_changes(struct repository *r,
4951 struct replay_opts *opts,
4952 struct todo_list *todo_list)
4954 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4955 unsigned int final_fixup = 0, is_clean;
4957 if (has_unstaged_changes(r, 1))
4958 return error(_("cannot rebase: You have unstaged changes."));
4960 is_clean = !has_uncommitted_changes(r, 0);
4962 if (file_exists(rebase_path_amend())) {
4963 struct strbuf rev = STRBUF_INIT;
4964 struct object_id head, to_amend;
4966 if (get_oid("HEAD", &head))
4967 return error(_("cannot amend non-existing commit"));
4968 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4969 return error(_("invalid file: '%s'"), rebase_path_amend());
4970 if (get_oid_hex(rev.buf, &to_amend))
4971 return error(_("invalid contents: '%s'"),
4972 rebase_path_amend());
4973 if (!is_clean && !oideq(&head, &to_amend))
4974 return error(_("\nYou have uncommitted changes in your "
4975 "working tree. Please, commit them\n"
4976 "first and then run 'git rebase "
4977 "--continue' again."));
4979 * When skipping a failed fixup/squash, we need to edit the
4980 * commit message, the current fixup list and count, and if it
4981 * was the last fixup/squash in the chain, we need to clean up
4982 * the commit message and if there was a squash, let the user
4983 * edit it.
4985 if (!is_clean || !opts->current_fixup_count)
4986 ; /* this is not the final fixup */
4987 else if (!oideq(&head, &to_amend) ||
4988 !file_exists(rebase_path_stopped_sha())) {
4989 /* was a final fixup or squash done manually? */
4990 if (!is_fixup(peek_command(todo_list, 0))) {
4991 unlink(rebase_path_fixup_msg());
4992 unlink(rebase_path_squash_msg());
4993 unlink(rebase_path_current_fixups());
4994 strbuf_reset(&opts->current_fixups);
4995 opts->current_fixup_count = 0;
4997 } else {
4998 /* we are in a fixup/squash chain */
4999 const char *p = opts->current_fixups.buf;
5000 int len = opts->current_fixups.len;
5002 opts->current_fixup_count--;
5003 if (!len)
5004 BUG("Incorrect current_fixups:\n%s", p);
5005 while (len && p[len - 1] != '\n')
5006 len--;
5007 strbuf_setlen(&opts->current_fixups, len);
5008 if (write_message(p, len, rebase_path_current_fixups(),
5009 0) < 0)
5010 return error(_("could not write file: '%s'"),
5011 rebase_path_current_fixups());
5014 * If a fixup/squash in a fixup/squash chain failed, the
5015 * commit message is already correct, no need to commit
5016 * it again.
5018 * Only if it is the final command in the fixup/squash
5019 * chain, and only if the chain is longer than a single
5020 * fixup/squash command (which was just skipped), do we
5021 * actually need to re-commit with a cleaned up commit
5022 * message.
5024 if (opts->current_fixup_count > 0 &&
5025 !is_fixup(peek_command(todo_list, 0))) {
5026 final_fixup = 1;
5028 * If there was not a single "squash" in the
5029 * chain, we only need to clean up the commit
5030 * message, no need to bother the user with
5031 * opening the commit message in the editor.
5033 if (!starts_with(p, "squash ") &&
5034 !strstr(p, "\nsquash "))
5035 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5036 } else if (is_fixup(peek_command(todo_list, 0))) {
5038 * We need to update the squash message to skip
5039 * the latest commit message.
5041 struct commit *commit;
5042 const char *path = rebase_path_squash_msg();
5043 const char *encoding = get_commit_output_encoding();
5045 if (parse_head(r, &commit) ||
5046 !(p = logmsg_reencode(commit, NULL, encoding)) ||
5047 write_message(p, strlen(p), path, 0)) {
5048 unuse_commit_buffer(commit, p);
5049 return error(_("could not write file: "
5050 "'%s'"), path);
5052 unuse_commit_buffer(commit, p);
5056 strbuf_release(&rev);
5057 flags |= AMEND_MSG;
5060 if (is_clean) {
5061 if (refs_ref_exists(get_main_ref_store(r),
5062 "CHERRY_PICK_HEAD") &&
5063 refs_delete_ref(get_main_ref_store(r), "",
5064 "CHERRY_PICK_HEAD", NULL, 0))
5065 return error(_("could not remove CHERRY_PICK_HEAD"));
5066 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5067 return error_errno(_("could not remove '%s'"),
5068 git_path_merge_msg(r));
5069 if (!final_fixup)
5070 return 0;
5073 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5074 opts, flags))
5075 return error(_("could not commit staged changes."));
5076 unlink(rebase_path_amend());
5077 unlink(git_path_merge_head(r));
5078 unlink(git_path_auto_merge(r));
5079 if (final_fixup) {
5080 unlink(rebase_path_fixup_msg());
5081 unlink(rebase_path_squash_msg());
5083 if (opts->current_fixup_count > 0) {
5085 * Whether final fixup or not, we just cleaned up the commit
5086 * message...
5088 unlink(rebase_path_current_fixups());
5089 strbuf_reset(&opts->current_fixups);
5090 opts->current_fixup_count = 0;
5092 return 0;
5095 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5097 struct todo_list todo_list = TODO_LIST_INIT;
5098 int res;
5100 if (read_and_refresh_cache(r, opts))
5101 return -1;
5103 if (read_populate_opts(opts))
5104 return -1;
5105 if (is_rebase_i(opts)) {
5106 if ((res = read_populate_todo(r, &todo_list, opts)))
5107 goto release_todo_list;
5109 if (file_exists(rebase_path_dropped())) {
5110 if ((res = todo_list_check_against_backup(r, &todo_list)))
5111 goto release_todo_list;
5113 unlink(rebase_path_dropped());
5116 opts->reflog_message = reflog_message(opts, "continue", NULL);
5117 if (commit_staged_changes(r, opts, &todo_list)) {
5118 res = -1;
5119 goto release_todo_list;
5121 } else if (!file_exists(get_todo_path(opts)))
5122 return continue_single_pick(r, opts);
5123 else if ((res = read_populate_todo(r, &todo_list, opts)))
5124 goto release_todo_list;
5126 if (!is_rebase_i(opts)) {
5127 /* Verify that the conflict has been resolved */
5128 if (refs_ref_exists(get_main_ref_store(r),
5129 "CHERRY_PICK_HEAD") ||
5130 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5131 res = continue_single_pick(r, opts);
5132 if (res)
5133 goto release_todo_list;
5135 if (index_differs_from(r, "HEAD", NULL, 0)) {
5136 res = error_dirty_index(r, opts);
5137 goto release_todo_list;
5139 todo_list.current++;
5140 } else if (file_exists(rebase_path_stopped_sha())) {
5141 struct strbuf buf = STRBUF_INIT;
5142 struct object_id oid;
5144 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5145 READ_ONELINER_SKIP_IF_EMPTY) &&
5146 !get_oid_hex(buf.buf, &oid))
5147 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5148 strbuf_release(&buf);
5151 res = pick_commits(r, &todo_list, opts);
5152 release_todo_list:
5153 todo_list_release(&todo_list);
5154 return res;
5157 static int single_pick(struct repository *r,
5158 struct commit *cmit,
5159 struct replay_opts *opts)
5161 int check_todo;
5162 struct todo_item item;
5164 item.command = opts->action == REPLAY_PICK ?
5165 TODO_PICK : TODO_REVERT;
5166 item.commit = cmit;
5168 opts->reflog_message = sequencer_reflog_action(opts);
5169 return do_pick_commit(r, &item, opts, 0, &check_todo);
5172 int sequencer_pick_revisions(struct repository *r,
5173 struct replay_opts *opts)
5175 struct todo_list todo_list = TODO_LIST_INIT;
5176 struct object_id oid;
5177 int i, res;
5179 assert(opts->revs);
5180 if (read_and_refresh_cache(r, opts))
5181 return -1;
5183 for (i = 0; i < opts->revs->pending.nr; i++) {
5184 struct object_id oid;
5185 const char *name = opts->revs->pending.objects[i].name;
5187 /* This happens when using --stdin. */
5188 if (!strlen(name))
5189 continue;
5191 if (!get_oid(name, &oid)) {
5192 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5193 enum object_type type = oid_object_info(r,
5194 &oid,
5195 NULL);
5196 return error(_("%s: can't cherry-pick a %s"),
5197 name, type_name(type));
5199 } else
5200 return error(_("%s: bad revision"), name);
5204 * If we were called as "git cherry-pick <commit>", just
5205 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5206 * REVERT_HEAD, and don't touch the sequencer state.
5207 * This means it is possible to cherry-pick in the middle
5208 * of a cherry-pick sequence.
5210 if (opts->revs->cmdline.nr == 1 &&
5211 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5212 opts->revs->no_walk &&
5213 !opts->revs->cmdline.rev->flags) {
5214 struct commit *cmit;
5215 if (prepare_revision_walk(opts->revs))
5216 return error(_("revision walk setup failed"));
5217 cmit = get_revision(opts->revs);
5218 if (!cmit)
5219 return error(_("empty commit set passed"));
5220 if (get_revision(opts->revs))
5221 BUG("unexpected extra commit from walk");
5222 return single_pick(r, cmit, opts);
5226 * Start a new cherry-pick/ revert sequence; but
5227 * first, make sure that an existing one isn't in
5228 * progress
5231 if (walk_revs_populate_todo(&todo_list, opts) ||
5232 create_seq_dir(r) < 0)
5233 return -1;
5234 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
5235 return error(_("can't revert as initial commit"));
5236 if (save_head(oid_to_hex(&oid)))
5237 return -1;
5238 if (save_opts(opts))
5239 return -1;
5240 update_abort_safety_file();
5241 res = pick_commits(r, &todo_list, opts);
5242 todo_list_release(&todo_list);
5243 return res;
5246 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5248 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5249 struct strbuf sob = STRBUF_INIT;
5250 int has_footer;
5252 strbuf_addstr(&sob, sign_off_header);
5253 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5254 strbuf_addch(&sob, '\n');
5256 if (!ignore_footer)
5257 strbuf_complete_line(msgbuf);
5260 * If the whole message buffer is equal to the sob, pretend that we
5261 * found a conforming footer with a matching sob
5263 if (msgbuf->len - ignore_footer == sob.len &&
5264 !strncmp(msgbuf->buf, sob.buf, sob.len))
5265 has_footer = 3;
5266 else
5267 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5269 if (!has_footer) {
5270 const char *append_newlines = NULL;
5271 size_t len = msgbuf->len - ignore_footer;
5273 if (!len) {
5275 * The buffer is completely empty. Leave foom for
5276 * the title and body to be filled in by the user.
5278 append_newlines = "\n\n";
5279 } else if (len == 1) {
5281 * Buffer contains a single newline. Add another
5282 * so that we leave room for the title and body.
5284 append_newlines = "\n";
5285 } else if (msgbuf->buf[len - 2] != '\n') {
5287 * Buffer ends with a single newline. Add another
5288 * so that there is an empty line between the message
5289 * body and the sob.
5291 append_newlines = "\n";
5292 } /* else, the buffer already ends with two newlines. */
5294 if (append_newlines)
5295 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5296 append_newlines, strlen(append_newlines));
5299 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5300 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5301 sob.buf, sob.len);
5303 strbuf_release(&sob);
5306 struct labels_entry {
5307 struct hashmap_entry entry;
5308 char label[FLEX_ARRAY];
5311 static int labels_cmp(const void *fndata UNUSED,
5312 const struct hashmap_entry *eptr,
5313 const struct hashmap_entry *entry_or_key, const void *key)
5315 const struct labels_entry *a, *b;
5317 a = container_of(eptr, const struct labels_entry, entry);
5318 b = container_of(entry_or_key, const struct labels_entry, entry);
5320 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5323 struct string_entry {
5324 struct oidmap_entry entry;
5325 char string[FLEX_ARRAY];
5328 struct label_state {
5329 struct oidmap commit2label;
5330 struct hashmap labels;
5331 struct strbuf buf;
5334 static const char *label_oid(struct object_id *oid, const char *label,
5335 struct label_state *state)
5337 struct labels_entry *labels_entry;
5338 struct string_entry *string_entry;
5339 struct object_id dummy;
5340 int i;
5342 string_entry = oidmap_get(&state->commit2label, oid);
5343 if (string_entry)
5344 return string_entry->string;
5347 * For "uninteresting" commits, i.e. commits that are not to be
5348 * rebased, and which can therefore not be labeled, we use a unique
5349 * abbreviation of the commit name. This is slightly more complicated
5350 * than calling find_unique_abbrev() because we also need to make
5351 * sure that the abbreviation does not conflict with any other
5352 * label.
5354 * We disallow "interesting" commits to be labeled by a string that
5355 * is a valid full-length hash, to ensure that we always can find an
5356 * abbreviation for any uninteresting commit's names that does not
5357 * clash with any other label.
5359 strbuf_reset(&state->buf);
5360 if (!label) {
5361 char *p;
5363 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5364 label = p = state->buf.buf;
5366 find_unique_abbrev_r(p, oid, default_abbrev);
5369 * We may need to extend the abbreviated hash so that there is
5370 * no conflicting label.
5372 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5373 size_t i = strlen(p) + 1;
5375 oid_to_hex_r(p, oid);
5376 for (; i < the_hash_algo->hexsz; i++) {
5377 char save = p[i];
5378 p[i] = '\0';
5379 if (!hashmap_get_from_hash(&state->labels,
5380 strihash(p), p))
5381 break;
5382 p[i] = save;
5385 } else {
5386 struct strbuf *buf = &state->buf;
5389 * Sanitize labels by replacing non-alpha-numeric characters
5390 * (including white-space ones) by dashes, as they might be
5391 * illegal in file names (and hence in ref names).
5393 * Note that we retain non-ASCII UTF-8 characters (identified
5394 * via the most significant bit). They should be all acceptable
5395 * in file names. We do not validate the UTF-8 here, that's not
5396 * the job of this function.
5398 for (; *label; label++)
5399 if ((*label & 0x80) || isalnum(*label))
5400 strbuf_addch(buf, *label);
5401 /* avoid leading dash and double-dashes */
5402 else if (buf->len && buf->buf[buf->len - 1] != '-')
5403 strbuf_addch(buf, '-');
5404 if (!buf->len) {
5405 strbuf_addstr(buf, "rev-");
5406 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5408 label = buf->buf;
5410 if ((buf->len == the_hash_algo->hexsz &&
5411 !get_oid_hex(label, &dummy)) ||
5412 (buf->len == 1 && *label == '#') ||
5413 hashmap_get_from_hash(&state->labels,
5414 strihash(label), label)) {
5416 * If the label already exists, or if the label is a
5417 * valid full OID, or the label is a '#' (which we use
5418 * as a separator between merge heads and oneline), we
5419 * append a dash and a number to make it unique.
5421 size_t len = buf->len;
5423 for (i = 2; ; i++) {
5424 strbuf_setlen(buf, len);
5425 strbuf_addf(buf, "-%d", i);
5426 if (!hashmap_get_from_hash(&state->labels,
5427 strihash(buf->buf),
5428 buf->buf))
5429 break;
5432 label = buf->buf;
5436 FLEX_ALLOC_STR(labels_entry, label, label);
5437 hashmap_entry_init(&labels_entry->entry, strihash(label));
5438 hashmap_add(&state->labels, &labels_entry->entry);
5440 FLEX_ALLOC_STR(string_entry, string, label);
5441 oidcpy(&string_entry->entry.oid, oid);
5442 oidmap_put(&state->commit2label, string_entry);
5444 return string_entry->string;
5447 static int make_script_with_merges(struct pretty_print_context *pp,
5448 struct rev_info *revs, struct strbuf *out,
5449 unsigned flags)
5451 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5452 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5453 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5454 int skipped_commit = 0;
5455 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5456 struct strbuf label = STRBUF_INIT;
5457 struct commit_list *commits = NULL, **tail = &commits, *iter;
5458 struct commit_list *tips = NULL, **tips_tail = &tips;
5459 struct commit *commit;
5460 struct oidmap commit2todo = OIDMAP_INIT;
5461 struct string_entry *entry;
5462 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5463 shown = OIDSET_INIT;
5464 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5466 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5467 const char *cmd_pick = abbr ? "p" : "pick",
5468 *cmd_label = abbr ? "l" : "label",
5469 *cmd_reset = abbr ? "t" : "reset",
5470 *cmd_merge = abbr ? "m" : "merge";
5472 oidmap_init(&commit2todo, 0);
5473 oidmap_init(&state.commit2label, 0);
5474 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5475 strbuf_init(&state.buf, 32);
5477 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5478 struct labels_entry *onto_label_entry;
5479 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5480 FLEX_ALLOC_STR(entry, string, "onto");
5481 oidcpy(&entry->entry.oid, oid);
5482 oidmap_put(&state.commit2label, entry);
5484 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5485 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5486 hashmap_add(&state.labels, &onto_label_entry->entry);
5490 * First phase:
5491 * - get onelines for all commits
5492 * - gather all branch tips (i.e. 2nd or later parents of merges)
5493 * - label all branch tips
5495 while ((commit = get_revision(revs))) {
5496 struct commit_list *to_merge;
5497 const char *p1, *p2;
5498 struct object_id *oid;
5499 int is_empty;
5501 tail = &commit_list_insert(commit, tail)->next;
5502 oidset_insert(&interesting, &commit->object.oid);
5504 is_empty = is_original_commit_empty(commit);
5505 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5506 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5507 warning(_("skipped previously applied commit %s"),
5508 short_commit_name(commit));
5509 skipped_commit = 1;
5510 continue;
5512 if (is_empty && !keep_empty)
5513 continue;
5515 strbuf_reset(&oneline);
5516 pretty_print_commit(pp, commit, &oneline);
5518 to_merge = commit->parents ? commit->parents->next : NULL;
5519 if (!to_merge) {
5520 /* non-merge commit: easy case */
5521 strbuf_reset(&buf);
5522 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5523 oid_to_hex(&commit->object.oid),
5524 oneline.buf);
5525 if (is_empty)
5526 strbuf_addf(&buf, " %c empty",
5527 comment_line_char);
5529 FLEX_ALLOC_STR(entry, string, buf.buf);
5530 oidcpy(&entry->entry.oid, &commit->object.oid);
5531 oidmap_put(&commit2todo, entry);
5533 continue;
5536 /* Create a label */
5537 strbuf_reset(&label);
5538 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5539 (p1 = strchr(p1, '\'')) &&
5540 (p2 = strchr(++p1, '\'')))
5541 strbuf_add(&label, p1, p2 - p1);
5542 else if (skip_prefix(oneline.buf, "Merge pull request ",
5543 &p1) &&
5544 (p1 = strstr(p1, " from ")))
5545 strbuf_addstr(&label, p1 + strlen(" from "));
5546 else
5547 strbuf_addbuf(&label, &oneline);
5549 strbuf_reset(&buf);
5550 strbuf_addf(&buf, "%s -C %s",
5551 cmd_merge, oid_to_hex(&commit->object.oid));
5553 /* label the tips of merged branches */
5554 for (; to_merge; to_merge = to_merge->next) {
5555 oid = &to_merge->item->object.oid;
5556 strbuf_addch(&buf, ' ');
5558 if (!oidset_contains(&interesting, oid)) {
5559 strbuf_addstr(&buf, label_oid(oid, NULL,
5560 &state));
5561 continue;
5564 tips_tail = &commit_list_insert(to_merge->item,
5565 tips_tail)->next;
5567 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5569 strbuf_addf(&buf, " # %s", oneline.buf);
5571 FLEX_ALLOC_STR(entry, string, buf.buf);
5572 oidcpy(&entry->entry.oid, &commit->object.oid);
5573 oidmap_put(&commit2todo, entry);
5575 if (skipped_commit)
5576 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5577 _("use --reapply-cherry-picks to include skipped commits"));
5580 * Second phase:
5581 * - label branch points
5582 * - add HEAD to the branch tips
5584 for (iter = commits; iter; iter = iter->next) {
5585 struct commit_list *parent = iter->item->parents;
5586 for (; parent; parent = parent->next) {
5587 struct object_id *oid = &parent->item->object.oid;
5588 if (!oidset_contains(&interesting, oid))
5589 continue;
5590 if (oidset_insert(&child_seen, oid))
5591 label_oid(oid, "branch-point", &state);
5594 /* Add HEAD as implicit "tip of branch" */
5595 if (!iter->next)
5596 tips_tail = &commit_list_insert(iter->item,
5597 tips_tail)->next;
5601 * Third phase: output the todo list. This is a bit tricky, as we
5602 * want to avoid jumping back and forth between revisions. To
5603 * accomplish that goal, we walk backwards from the branch tips,
5604 * gathering commits not yet shown, reversing the list on the fly,
5605 * then outputting that list (labeling revisions as needed).
5607 strbuf_addf(out, "%s onto\n", cmd_label);
5608 for (iter = tips; iter; iter = iter->next) {
5609 struct commit_list *list = NULL, *iter2;
5611 commit = iter->item;
5612 if (oidset_contains(&shown, &commit->object.oid))
5613 continue;
5614 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5616 if (entry)
5617 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5618 else
5619 strbuf_addch(out, '\n');
5621 while (oidset_contains(&interesting, &commit->object.oid) &&
5622 !oidset_contains(&shown, &commit->object.oid)) {
5623 commit_list_insert(commit, &list);
5624 if (!commit->parents) {
5625 commit = NULL;
5626 break;
5628 commit = commit->parents->item;
5631 if (!commit)
5632 strbuf_addf(out, "%s %s\n", cmd_reset,
5633 rebase_cousins || root_with_onto ?
5634 "onto" : "[new root]");
5635 else {
5636 const char *to = NULL;
5638 entry = oidmap_get(&state.commit2label,
5639 &commit->object.oid);
5640 if (entry)
5641 to = entry->string;
5642 else if (!rebase_cousins)
5643 to = label_oid(&commit->object.oid, NULL,
5644 &state);
5646 if (!to || !strcmp(to, "onto"))
5647 strbuf_addf(out, "%s onto\n", cmd_reset);
5648 else {
5649 strbuf_reset(&oneline);
5650 pretty_print_commit(pp, commit, &oneline);
5651 strbuf_addf(out, "%s %s # %s\n",
5652 cmd_reset, to, oneline.buf);
5656 for (iter2 = list; iter2; iter2 = iter2->next) {
5657 struct object_id *oid = &iter2->item->object.oid;
5658 entry = oidmap_get(&commit2todo, oid);
5659 /* only show if not already upstream */
5660 if (entry)
5661 strbuf_addf(out, "%s\n", entry->string);
5662 entry = oidmap_get(&state.commit2label, oid);
5663 if (entry)
5664 strbuf_addf(out, "%s %s\n",
5665 cmd_label, entry->string);
5666 oidset_insert(&shown, oid);
5669 free_commit_list(list);
5672 free_commit_list(commits);
5673 free_commit_list(tips);
5675 strbuf_release(&label);
5676 strbuf_release(&oneline);
5677 strbuf_release(&buf);
5679 oidmap_free(&commit2todo, 1);
5680 oidmap_free(&state.commit2label, 1);
5681 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5682 strbuf_release(&state.buf);
5684 return 0;
5687 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5688 const char **argv, unsigned flags)
5690 char *format = NULL;
5691 struct pretty_print_context pp = {0};
5692 struct rev_info revs;
5693 struct commit *commit;
5694 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5695 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5696 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5697 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5698 int skipped_commit = 0;
5699 int ret = 0;
5701 repo_init_revisions(r, &revs, NULL);
5702 revs.verbose_header = 1;
5703 if (!rebase_merges)
5704 revs.max_parents = 1;
5705 revs.cherry_mark = !reapply_cherry_picks;
5706 revs.limited = 1;
5707 revs.reverse = 1;
5708 revs.right_only = 1;
5709 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5710 revs.topo_order = 1;
5712 revs.pretty_given = 1;
5713 git_config_get_string("rebase.instructionFormat", &format);
5714 if (!format || !*format) {
5715 free(format);
5716 format = xstrdup("%s");
5718 get_commit_format(format, &revs);
5719 free(format);
5720 pp.fmt = revs.commit_format;
5721 pp.output_encoding = get_log_output_encoding();
5723 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5724 ret = error(_("make_script: unhandled options"));
5725 goto cleanup;
5728 if (prepare_revision_walk(&revs) < 0) {
5729 ret = error(_("make_script: error preparing revisions"));
5730 goto cleanup;
5733 if (rebase_merges) {
5734 ret = make_script_with_merges(&pp, &revs, out, flags);
5735 goto cleanup;
5738 while ((commit = get_revision(&revs))) {
5739 int is_empty = is_original_commit_empty(commit);
5741 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5742 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5743 warning(_("skipped previously applied commit %s"),
5744 short_commit_name(commit));
5745 skipped_commit = 1;
5746 continue;
5748 if (is_empty && !keep_empty)
5749 continue;
5750 strbuf_addf(out, "%s %s ", insn,
5751 oid_to_hex(&commit->object.oid));
5752 pretty_print_commit(&pp, commit, out);
5753 if (is_empty)
5754 strbuf_addf(out, " %c empty", comment_line_char);
5755 strbuf_addch(out, '\n');
5757 if (skipped_commit)
5758 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5759 _("use --reapply-cherry-picks to include skipped commits"));
5760 cleanup:
5761 release_revisions(&revs);
5762 return ret;
5766 * Add commands after pick and (series of) squash/fixup commands
5767 * in the todo list.
5769 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5770 struct string_list *commands)
5772 struct strbuf *buf = &todo_list->buf;
5773 size_t base_offset = buf->len;
5774 int i, insert, nr = 0, alloc = 0;
5775 struct todo_item *items = NULL, *base_items = NULL;
5777 CALLOC_ARRAY(base_items, commands->nr);
5778 for (i = 0; i < commands->nr; i++) {
5779 size_t command_len = strlen(commands->items[i].string);
5781 strbuf_addstr(buf, commands->items[i].string);
5782 strbuf_addch(buf, '\n');
5784 base_items[i].command = TODO_EXEC;
5785 base_items[i].offset_in_buf = base_offset;
5786 base_items[i].arg_offset = base_offset;
5787 base_items[i].arg_len = command_len;
5789 base_offset += command_len + 1;
5793 * Insert <commands> after every pick. Here, fixup/squash chains
5794 * are considered part of the pick, so we insert the commands *after*
5795 * those chains if there are any.
5797 * As we insert the exec commands immediately after rearranging
5798 * any fixups and before the user edits the list, a fixup chain
5799 * can never contain comments (any comments are empty picks that
5800 * have been commented out because the user did not specify
5801 * --keep-empty). So, it is safe to insert an exec command
5802 * without looking at the command following a comment.
5804 insert = 0;
5805 for (i = 0; i < todo_list->nr; i++) {
5806 enum todo_command command = todo_list->items[i].command;
5807 if (insert && !is_fixup(command)) {
5808 ALLOC_GROW(items, nr + commands->nr, alloc);
5809 COPY_ARRAY(items + nr, base_items, commands->nr);
5810 nr += commands->nr;
5812 insert = 0;
5815 ALLOC_GROW(items, nr + 1, alloc);
5816 items[nr++] = todo_list->items[i];
5818 if (command == TODO_PICK || command == TODO_MERGE)
5819 insert = 1;
5822 /* insert or append final <commands> */
5823 if (insert) {
5824 ALLOC_GROW(items, nr + commands->nr, alloc);
5825 COPY_ARRAY(items + nr, base_items, commands->nr);
5826 nr += commands->nr;
5829 free(base_items);
5830 FREE_AND_NULL(todo_list->items);
5831 todo_list->items = items;
5832 todo_list->nr = nr;
5833 todo_list->alloc = alloc;
5836 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5837 struct strbuf *buf, int num, unsigned flags)
5839 struct todo_item *item;
5840 int i, max = todo_list->nr;
5842 if (num > 0 && num < max)
5843 max = num;
5845 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5846 char cmd;
5848 /* if the item is not a command write it and continue */
5849 if (item->command >= TODO_COMMENT) {
5850 strbuf_addf(buf, "%.*s\n", item->arg_len,
5851 todo_item_get_arg(todo_list, item));
5852 continue;
5855 /* add command to the buffer */
5856 cmd = command_to_char(item->command);
5857 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5858 strbuf_addch(buf, cmd);
5859 else
5860 strbuf_addstr(buf, command_to_string(item->command));
5862 /* add commit id */
5863 if (item->commit) {
5864 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5865 short_commit_name(item->commit) :
5866 oid_to_hex(&item->commit->object.oid);
5868 if (item->command == TODO_FIXUP) {
5869 if (item->flags & TODO_EDIT_FIXUP_MSG)
5870 strbuf_addstr(buf, " -c");
5871 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5872 strbuf_addstr(buf, " -C");
5876 if (item->command == TODO_MERGE) {
5877 if (item->flags & TODO_EDIT_MERGE_MSG)
5878 strbuf_addstr(buf, " -c");
5879 else
5880 strbuf_addstr(buf, " -C");
5883 strbuf_addf(buf, " %s", oid);
5886 /* add all the rest */
5887 if (!item->arg_len)
5888 strbuf_addch(buf, '\n');
5889 else
5890 strbuf_addf(buf, " %.*s\n", item->arg_len,
5891 todo_item_get_arg(todo_list, item));
5895 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5896 const char *file, const char *shortrevisions,
5897 const char *shortonto, int num, unsigned flags)
5899 int res;
5900 struct strbuf buf = STRBUF_INIT;
5902 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5903 if (flags & TODO_LIST_APPEND_TODO_HELP)
5904 append_todo_help(count_commands(todo_list),
5905 shortrevisions, shortonto, &buf);
5907 res = write_message(buf.buf, buf.len, file, 0);
5908 strbuf_release(&buf);
5910 return res;
5913 /* skip picking commits whose parents are unchanged */
5914 static int skip_unnecessary_picks(struct repository *r,
5915 struct todo_list *todo_list,
5916 struct object_id *base_oid)
5918 struct object_id *parent_oid;
5919 int i;
5921 for (i = 0; i < todo_list->nr; i++) {
5922 struct todo_item *item = todo_list->items + i;
5924 if (item->command >= TODO_NOOP)
5925 continue;
5926 if (item->command != TODO_PICK)
5927 break;
5928 if (parse_commit(item->commit)) {
5929 return error(_("could not parse commit '%s'"),
5930 oid_to_hex(&item->commit->object.oid));
5932 if (!item->commit->parents)
5933 break; /* root commit */
5934 if (item->commit->parents->next)
5935 break; /* merge commit */
5936 parent_oid = &item->commit->parents->item->object.oid;
5937 if (!oideq(parent_oid, base_oid))
5938 break;
5939 oidcpy(base_oid, &item->commit->object.oid);
5941 if (i > 0) {
5942 const char *done_path = rebase_path_done();
5944 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5945 error_errno(_("could not write to '%s'"), done_path);
5946 return -1;
5949 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5950 todo_list->nr -= i;
5951 todo_list->current = 0;
5952 todo_list->done_nr += i;
5954 if (is_fixup(peek_command(todo_list, 0)))
5955 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5958 return 0;
5961 struct todo_add_branch_context {
5962 struct todo_item *items;
5963 size_t items_nr;
5964 size_t items_alloc;
5965 struct strbuf *buf;
5966 struct commit *commit;
5967 struct string_list refs_to_oids;
5970 static int add_decorations_to_list(const struct commit *commit,
5971 struct todo_add_branch_context *ctx)
5973 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5974 const char *head_ref = resolve_ref_unsafe("HEAD",
5975 RESOLVE_REF_READING,
5976 NULL,
5977 NULL);
5979 while (decoration) {
5980 struct todo_item *item;
5981 const char *path;
5982 size_t base_offset = ctx->buf->len;
5985 * If the branch is the current HEAD, then it will be
5986 * updated by the default rebase behavior.
5988 if (head_ref && !strcmp(head_ref, decoration->name)) {
5989 decoration = decoration->next;
5990 continue;
5993 ALLOC_GROW(ctx->items,
5994 ctx->items_nr + 1,
5995 ctx->items_alloc);
5996 item = &ctx->items[ctx->items_nr];
5997 memset(item, 0, sizeof(*item));
5999 /* If the branch is checked out, then leave a comment instead. */
6000 if ((path = branch_checked_out(decoration->name))) {
6001 item->command = TODO_COMMENT;
6002 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6003 decoration->name, path);
6004 } else {
6005 struct string_list_item *sti;
6006 item->command = TODO_UPDATE_REF;
6007 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6009 sti = string_list_insert(&ctx->refs_to_oids,
6010 decoration->name);
6011 sti->util = init_update_ref_record(decoration->name);
6014 item->offset_in_buf = base_offset;
6015 item->arg_offset = base_offset;
6016 item->arg_len = ctx->buf->len - base_offset;
6017 ctx->items_nr++;
6019 decoration = decoration->next;
6022 return 0;
6026 * For each 'pick' command, find out if the commit has a decoration in
6027 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6029 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6031 int i, res;
6032 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6033 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6034 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6035 struct decoration_filter decoration_filter = {
6036 .include_ref_pattern = &decorate_refs_include,
6037 .exclude_ref_pattern = &decorate_refs_exclude,
6038 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6040 struct todo_add_branch_context ctx = {
6041 .buf = &todo_list->buf,
6042 .refs_to_oids = STRING_LIST_INIT_DUP,
6045 ctx.items_alloc = 2 * todo_list->nr + 1;
6046 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6048 string_list_append(&decorate_refs_include, "refs/heads/");
6049 load_ref_decorations(&decoration_filter, 0);
6051 for (i = 0; i < todo_list->nr; ) {
6052 struct todo_item *item = &todo_list->items[i];
6054 /* insert ith item into new list */
6055 ALLOC_GROW(ctx.items,
6056 ctx.items_nr + 1,
6057 ctx.items_alloc);
6059 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6061 if (item->commit) {
6062 ctx.commit = item->commit;
6063 add_decorations_to_list(item->commit, &ctx);
6067 res = write_update_refs_state(&ctx.refs_to_oids);
6069 string_list_clear(&ctx.refs_to_oids, 1);
6071 if (res) {
6072 /* we failed, so clean up the new list. */
6073 free(ctx.items);
6074 return res;
6077 free(todo_list->items);
6078 todo_list->items = ctx.items;
6079 todo_list->nr = ctx.items_nr;
6080 todo_list->alloc = ctx.items_alloc;
6082 return 0;
6085 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6086 const char *shortrevisions, const char *onto_name,
6087 struct commit *onto, const struct object_id *orig_head,
6088 struct string_list *commands, unsigned autosquash,
6089 unsigned update_refs,
6090 struct todo_list *todo_list)
6092 char shortonto[GIT_MAX_HEXSZ + 1];
6093 const char *todo_file = rebase_path_todo();
6094 struct todo_list new_todo = TODO_LIST_INIT;
6095 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6096 struct object_id oid = onto->object.oid;
6097 int res;
6099 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
6101 if (buf->len == 0) {
6102 struct todo_item *item = append_new_todo(todo_list);
6103 item->command = TODO_NOOP;
6104 item->commit = NULL;
6105 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6108 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6109 return -1;
6111 if (autosquash && todo_list_rearrange_squash(todo_list))
6112 return -1;
6114 if (commands->nr)
6115 todo_list_add_exec_commands(todo_list, commands);
6117 if (count_commands(todo_list) == 0) {
6118 apply_autostash(rebase_path_autostash());
6119 sequencer_remove_state(opts);
6121 return error(_("nothing to do"));
6124 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6125 shortonto, flags);
6126 if (res == -1)
6127 return -1;
6128 else if (res == -2) {
6129 apply_autostash(rebase_path_autostash());
6130 sequencer_remove_state(opts);
6132 return -1;
6133 } else if (res == -3) {
6134 apply_autostash(rebase_path_autostash());
6135 sequencer_remove_state(opts);
6136 todo_list_release(&new_todo);
6138 return error(_("nothing to do"));
6139 } else if (res == -4) {
6140 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6141 todo_list_release(&new_todo);
6143 return -1;
6146 /* Expand the commit IDs */
6147 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6148 strbuf_swap(&new_todo.buf, &buf2);
6149 strbuf_release(&buf2);
6150 new_todo.total_nr -= new_todo.nr;
6151 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6152 BUG("invalid todo list after expanding IDs:\n%s",
6153 new_todo.buf.buf);
6155 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6156 todo_list_release(&new_todo);
6157 return error(_("could not skip unnecessary pick commands"));
6160 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6161 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6162 todo_list_release(&new_todo);
6163 return error_errno(_("could not write '%s'"), todo_file);
6166 res = -1;
6168 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6169 goto cleanup;
6171 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6172 goto cleanup;
6174 todo_list_write_total_nr(&new_todo);
6175 res = pick_commits(r, &new_todo, opts);
6177 cleanup:
6178 todo_list_release(&new_todo);
6180 return res;
6183 struct subject2item_entry {
6184 struct hashmap_entry entry;
6185 int i;
6186 char subject[FLEX_ARRAY];
6189 static int subject2item_cmp(const void *fndata UNUSED,
6190 const struct hashmap_entry *eptr,
6191 const struct hashmap_entry *entry_or_key,
6192 const void *key)
6194 const struct subject2item_entry *a, *b;
6196 a = container_of(eptr, const struct subject2item_entry, entry);
6197 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6199 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6202 define_commit_slab(commit_todo_item, struct todo_item *);
6204 static int skip_fixupish(const char *subject, const char **p) {
6205 return skip_prefix(subject, "fixup! ", p) ||
6206 skip_prefix(subject, "amend! ", p) ||
6207 skip_prefix(subject, "squash! ", p);
6211 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6212 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6213 * after the former, and change "pick" to "fixup"/"squash".
6215 * Note that if the config has specified a custom instruction format, each log
6216 * message will have to be retrieved from the commit (as the oneline in the
6217 * script cannot be trusted) in order to normalize the autosquash arrangement.
6219 int todo_list_rearrange_squash(struct todo_list *todo_list)
6221 struct hashmap subject2item;
6222 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6223 char **subjects;
6224 struct commit_todo_item commit_todo;
6225 struct todo_item *items = NULL;
6227 init_commit_todo_item(&commit_todo);
6229 * The hashmap maps onelines to the respective todo list index.
6231 * If any items need to be rearranged, the next[i] value will indicate
6232 * which item was moved directly after the i'th.
6234 * In that case, last[i] will indicate the index of the latest item to
6235 * be moved to appear after the i'th.
6237 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6238 ALLOC_ARRAY(next, todo_list->nr);
6239 ALLOC_ARRAY(tail, todo_list->nr);
6240 ALLOC_ARRAY(subjects, todo_list->nr);
6241 for (i = 0; i < todo_list->nr; i++) {
6242 struct strbuf buf = STRBUF_INIT;
6243 struct todo_item *item = todo_list->items + i;
6244 const char *commit_buffer, *subject, *p;
6245 size_t subject_len;
6246 int i2 = -1;
6247 struct subject2item_entry *entry;
6249 next[i] = tail[i] = -1;
6250 if (!item->commit || item->command == TODO_DROP) {
6251 subjects[i] = NULL;
6252 continue;
6255 if (is_fixup(item->command)) {
6256 clear_commit_todo_item(&commit_todo);
6257 return error(_("the script was already rearranged."));
6260 parse_commit(item->commit);
6261 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
6262 find_commit_subject(commit_buffer, &subject);
6263 format_subject(&buf, subject, " ");
6264 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6265 unuse_commit_buffer(item->commit, commit_buffer);
6266 if (skip_fixupish(subject, &p)) {
6267 struct commit *commit2;
6269 for (;;) {
6270 while (isspace(*p))
6271 p++;
6272 if (!skip_fixupish(p, &p))
6273 break;
6276 entry = hashmap_get_entry_from_hash(&subject2item,
6277 strhash(p), p,
6278 struct subject2item_entry,
6279 entry);
6280 if (entry)
6281 /* found by title */
6282 i2 = entry->i;
6283 else if (!strchr(p, ' ') &&
6284 (commit2 =
6285 lookup_commit_reference_by_name(p)) &&
6286 *commit_todo_item_at(&commit_todo, commit2))
6287 /* found by commit name */
6288 i2 = *commit_todo_item_at(&commit_todo, commit2)
6289 - todo_list->items;
6290 else {
6291 /* copy can be a prefix of the commit subject */
6292 for (i2 = 0; i2 < i; i2++)
6293 if (subjects[i2] &&
6294 starts_with(subjects[i2], p))
6295 break;
6296 if (i2 == i)
6297 i2 = -1;
6300 if (i2 >= 0) {
6301 rearranged = 1;
6302 if (starts_with(subject, "fixup!")) {
6303 todo_list->items[i].command = TODO_FIXUP;
6304 } else if (starts_with(subject, "amend!")) {
6305 todo_list->items[i].command = TODO_FIXUP;
6306 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6307 } else {
6308 todo_list->items[i].command = TODO_SQUASH;
6310 if (tail[i2] < 0) {
6311 next[i] = next[i2];
6312 next[i2] = i;
6313 } else {
6314 next[i] = next[tail[i2]];
6315 next[tail[i2]] = i;
6317 tail[i2] = i;
6318 } else if (!hashmap_get_from_hash(&subject2item,
6319 strhash(subject), subject)) {
6320 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6321 entry->i = i;
6322 hashmap_entry_init(&entry->entry,
6323 strhash(entry->subject));
6324 hashmap_put(&subject2item, &entry->entry);
6327 *commit_todo_item_at(&commit_todo, item->commit) = item;
6330 if (rearranged) {
6331 for (i = 0; i < todo_list->nr; i++) {
6332 enum todo_command command = todo_list->items[i].command;
6333 int cur = i;
6336 * Initially, all commands are 'pick's. If it is a
6337 * fixup or a squash now, we have rearranged it.
6339 if (is_fixup(command))
6340 continue;
6342 while (cur >= 0) {
6343 ALLOC_GROW(items, nr + 1, alloc);
6344 items[nr++] = todo_list->items[cur];
6345 cur = next[cur];
6349 FREE_AND_NULL(todo_list->items);
6350 todo_list->items = items;
6351 todo_list->nr = nr;
6352 todo_list->alloc = alloc;
6355 free(next);
6356 free(tail);
6357 for (i = 0; i < todo_list->nr; i++)
6358 free(subjects[i]);
6359 free(subjects);
6360 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6362 clear_commit_todo_item(&commit_todo);
6364 return 0;
6367 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6369 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6370 struct object_id cherry_pick_head, rebase_head;
6372 if (file_exists(git_path_seq_dir()))
6373 *whence = FROM_CHERRY_PICK_MULTI;
6374 if (file_exists(rebase_path()) &&
6375 !get_oid("REBASE_HEAD", &rebase_head) &&
6376 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
6377 oideq(&rebase_head, &cherry_pick_head))
6378 *whence = FROM_REBASE_PICK;
6379 else
6380 *whence = FROM_CHERRY_PICK_SINGLE;
6382 return 1;
6385 return 0;
6388 int sequencer_get_update_refs_state(const char *wt_dir,
6389 struct string_list *refs)
6391 int result = 0;
6392 FILE *fp = NULL;
6393 struct strbuf ref = STRBUF_INIT;
6394 struct strbuf hash = STRBUF_INIT;
6395 struct update_ref_record *rec = NULL;
6397 char *path = rebase_path_update_refs(wt_dir);
6399 fp = fopen(path, "r");
6400 if (!fp)
6401 goto cleanup;
6403 while (strbuf_getline(&ref, fp) != EOF) {
6404 struct string_list_item *item;
6406 CALLOC_ARRAY(rec, 1);
6408 if (strbuf_getline(&hash, fp) == EOF ||
6409 get_oid_hex(hash.buf, &rec->before)) {
6410 warning(_("update-refs file at '%s' is invalid"),
6411 path);
6412 result = -1;
6413 goto cleanup;
6416 if (strbuf_getline(&hash, fp) == EOF ||
6417 get_oid_hex(hash.buf, &rec->after)) {
6418 warning(_("update-refs file at '%s' is invalid"),
6419 path);
6420 result = -1;
6421 goto cleanup;
6424 item = string_list_insert(refs, ref.buf);
6425 item->util = rec;
6426 rec = NULL;
6429 cleanup:
6430 if (fp)
6431 fclose(fp);
6432 free(path);
6433 free(rec);
6434 strbuf_release(&ref);
6435 strbuf_release(&hash);
6436 return result;