rebase -m: fix serialization of strategy options
[git/gitster.git] / sequencer.c
blobfc6ea75895fa85c6605c74157687c3ab697fce98
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 strvec_clear (&opts->xopts);
359 strbuf_release(&opts->current_fixups);
360 if (opts->revs)
361 release_revisions(opts->revs);
362 free(opts->revs);
365 int sequencer_remove_state(struct replay_opts *opts)
367 struct strbuf buf = STRBUF_INIT;
368 int ret = 0;
370 if (is_rebase_i(opts) &&
371 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
372 char *p = buf.buf;
373 while (*p) {
374 char *eol = strchr(p, '\n');
375 if (eol)
376 *eol = '\0';
377 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
378 warning(_("could not delete '%s'"), p);
379 ret = -1;
381 if (!eol)
382 break;
383 p = eol + 1;
387 strbuf_reset(&buf);
388 strbuf_addstr(&buf, get_dir(opts));
389 if (remove_dir_recursively(&buf, 0))
390 ret = error(_("could not remove '%s'"), buf.buf);
391 strbuf_release(&buf);
393 return ret;
396 static const char *action_name(const struct replay_opts *opts)
398 switch (opts->action) {
399 case REPLAY_REVERT:
400 return N_("revert");
401 case REPLAY_PICK:
402 return N_("cherry-pick");
403 case REPLAY_INTERACTIVE_REBASE:
404 return N_("rebase");
406 die(_("unknown action: %d"), opts->action);
409 struct commit_message {
410 char *parent_label;
411 char *label;
412 char *subject;
413 const char *message;
416 static const char *short_commit_name(struct commit *commit)
418 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
421 static int get_message(struct commit *commit, struct commit_message *out)
423 const char *abbrev, *subject;
424 int subject_len;
426 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
427 abbrev = short_commit_name(commit);
429 subject_len = find_commit_subject(out->message, &subject);
431 out->subject = xmemdupz(subject, subject_len);
432 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
433 out->parent_label = xstrfmt("parent of %s", out->label);
435 return 0;
438 static void free_message(struct commit *commit, struct commit_message *msg)
440 free(msg->parent_label);
441 free(msg->label);
442 free(msg->subject);
443 unuse_commit_buffer(commit, msg->message);
446 static void print_advice(struct repository *r, int show_hint,
447 struct replay_opts *opts)
449 char *msg = getenv("GIT_CHERRY_PICK_HELP");
451 if (msg) {
452 advise("%s\n", msg);
454 * A conflict has occurred but the porcelain
455 * (typically rebase --interactive) wants to take care
456 * of the commit itself so remove CHERRY_PICK_HEAD
458 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
459 NULL, 0);
460 return;
463 if (show_hint) {
464 if (opts->no_commit)
465 advise(_("after resolving the conflicts, mark the corrected paths\n"
466 "with 'git add <paths>' or 'git rm <paths>'"));
467 else if (opts->action == REPLAY_PICK)
468 advise(_("After resolving the conflicts, mark them with\n"
469 "\"git add/rm <pathspec>\", then run\n"
470 "\"git cherry-pick --continue\".\n"
471 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
472 "To abort and get back to the state before \"git cherry-pick\",\n"
473 "run \"git cherry-pick --abort\"."));
474 else if (opts->action == REPLAY_REVERT)
475 advise(_("After resolving the conflicts, mark them with\n"
476 "\"git add/rm <pathspec>\", then run\n"
477 "\"git revert --continue\".\n"
478 "You can instead skip this commit with \"git revert --skip\".\n"
479 "To abort and get back to the state before \"git revert\",\n"
480 "run \"git revert --abort\"."));
481 else
482 BUG("unexpected pick action in print_advice()");
486 static int write_message(const void *buf, size_t len, const char *filename,
487 int append_eol)
489 struct lock_file msg_file = LOCK_INIT;
491 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
492 if (msg_fd < 0)
493 return error_errno(_("could not lock '%s'"), filename);
494 if (write_in_full(msg_fd, buf, len) < 0) {
495 error_errno(_("could not write to '%s'"), filename);
496 rollback_lock_file(&msg_file);
497 return -1;
499 if (append_eol && write(msg_fd, "\n", 1) < 0) {
500 error_errno(_("could not write eol to '%s'"), filename);
501 rollback_lock_file(&msg_file);
502 return -1;
504 if (commit_lock_file(&msg_file) < 0)
505 return error(_("failed to finalize '%s'"), filename);
507 return 0;
510 int read_oneliner(struct strbuf *buf,
511 const char *path, unsigned flags)
513 int orig_len = buf->len;
515 if (strbuf_read_file(buf, path, 0) < 0) {
516 if ((flags & READ_ONELINER_WARN_MISSING) ||
517 (errno != ENOENT && errno != ENOTDIR))
518 warning_errno(_("could not read '%s'"), path);
519 return 0;
522 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
523 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
524 --buf->len;
525 buf->buf[buf->len] = '\0';
528 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
529 return 0;
531 return 1;
534 static struct tree *empty_tree(struct repository *r)
536 return lookup_tree(r, the_hash_algo->empty_tree);
539 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
541 if (repo_read_index_unmerged(repo))
542 return error_resolve_conflict(action_name(opts));
544 error(_("your local changes would be overwritten by %s."),
545 _(action_name(opts)));
547 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
548 advise(_("commit your changes or stash them to proceed."));
549 return -1;
552 static void update_abort_safety_file(void)
554 struct object_id head;
556 /* Do nothing on a single-pick */
557 if (!file_exists(git_path_seq_dir()))
558 return;
560 if (!get_oid("HEAD", &head))
561 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
562 else
563 write_file(git_path_abort_safety_file(), "%s", "");
566 static int fast_forward_to(struct repository *r,
567 const struct object_id *to,
568 const struct object_id *from,
569 int unborn,
570 struct replay_opts *opts)
572 struct ref_transaction *transaction;
573 struct strbuf sb = STRBUF_INIT;
574 struct strbuf err = STRBUF_INIT;
576 repo_read_index(r);
577 if (checkout_fast_forward(r, from, to, 1))
578 return -1; /* the callee should have complained already */
580 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
582 transaction = ref_transaction_begin(&err);
583 if (!transaction ||
584 ref_transaction_update(transaction, "HEAD",
585 to, unborn && !is_rebase_i(opts) ?
586 null_oid() : from,
587 0, sb.buf, &err) ||
588 ref_transaction_commit(transaction, &err)) {
589 ref_transaction_free(transaction);
590 error("%s", err.buf);
591 strbuf_release(&sb);
592 strbuf_release(&err);
593 return -1;
596 strbuf_release(&sb);
597 strbuf_release(&err);
598 ref_transaction_free(transaction);
599 update_abort_safety_file();
600 return 0;
603 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
604 int use_editor)
606 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
607 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
608 COMMIT_MSG_CLEANUP_SPACE;
609 else if (!strcmp(cleanup_arg, "verbatim"))
610 return COMMIT_MSG_CLEANUP_NONE;
611 else if (!strcmp(cleanup_arg, "whitespace"))
612 return COMMIT_MSG_CLEANUP_SPACE;
613 else if (!strcmp(cleanup_arg, "strip"))
614 return COMMIT_MSG_CLEANUP_ALL;
615 else if (!strcmp(cleanup_arg, "scissors"))
616 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
617 COMMIT_MSG_CLEANUP_SPACE;
618 else
619 die(_("Invalid cleanup mode %s"), cleanup_arg);
623 * NB using int rather than enum cleanup_mode to stop clang's
624 * -Wtautological-constant-out-of-range-compare complaining that the comparison
625 * is always true.
627 static const char *describe_cleanup_mode(int cleanup_mode)
629 static const char *modes[] = { "whitespace",
630 "verbatim",
631 "scissors",
632 "strip" };
634 if (cleanup_mode < ARRAY_SIZE(modes))
635 return modes[cleanup_mode];
637 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
640 void append_conflicts_hint(struct index_state *istate,
641 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
643 int i;
645 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
646 strbuf_addch(msgbuf, '\n');
647 wt_status_append_cut_line(msgbuf);
648 strbuf_addch(msgbuf, comment_line_char);
651 strbuf_addch(msgbuf, '\n');
652 strbuf_commented_addf(msgbuf, "Conflicts:\n");
653 for (i = 0; i < istate->cache_nr;) {
654 const struct cache_entry *ce = istate->cache[i++];
655 if (ce_stage(ce)) {
656 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
657 while (i < istate->cache_nr &&
658 !strcmp(ce->name, istate->cache[i]->name))
659 i++;
664 static int do_recursive_merge(struct repository *r,
665 struct commit *base, struct commit *next,
666 const char *base_label, const char *next_label,
667 struct object_id *head, struct strbuf *msgbuf,
668 struct replay_opts *opts)
670 struct merge_options o;
671 struct merge_result result;
672 struct tree *next_tree, *base_tree, *head_tree;
673 int clean, show_output;
674 int i;
675 struct lock_file index_lock = LOCK_INIT;
677 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
678 return -1;
680 repo_read_index(r);
682 init_merge_options(&o, r);
683 o.ancestor = base ? base_label : "(empty tree)";
684 o.branch1 = "HEAD";
685 o.branch2 = next ? next_label : "(empty tree)";
686 if (is_rebase_i(opts))
687 o.buffer_output = 2;
688 o.show_rename_progress = 1;
690 head_tree = parse_tree_indirect(head);
691 next_tree = next ? get_commit_tree(next) : empty_tree(r);
692 base_tree = base ? get_commit_tree(base) : empty_tree(r);
694 for (i = 0; i < opts->xopts.nr; i++)
695 parse_merge_opt(&o, opts->xopts.v[i]);
697 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
698 memset(&result, 0, sizeof(result));
699 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
700 &result);
701 show_output = !is_rebase_i(opts) || !result.clean;
703 * TODO: merge_switch_to_result will update index/working tree;
704 * we only really want to do that if !result.clean || this is
705 * the final patch to be picked. But determining this is the
706 * final patch would take some work, and "head_tree" would need
707 * to be replace with the tree the index matched before we
708 * started doing any picks.
710 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
711 clean = result.clean;
712 } else {
713 ensure_full_index(r->index);
714 clean = merge_trees(&o, head_tree, next_tree, base_tree);
715 if (is_rebase_i(opts) && clean <= 0)
716 fputs(o.obuf.buf, stdout);
717 strbuf_release(&o.obuf);
719 if (clean < 0) {
720 rollback_lock_file(&index_lock);
721 return clean;
724 if (write_locked_index(r->index, &index_lock,
725 COMMIT_LOCK | SKIP_IF_UNCHANGED))
727 * TRANSLATORS: %s will be "revert", "cherry-pick" or
728 * "rebase".
730 return error(_("%s: Unable to write new index file"),
731 _(action_name(opts)));
733 if (!clean)
734 append_conflicts_hint(r->index, msgbuf,
735 opts->default_msg_cleanup);
737 return !clean;
740 static struct object_id *get_cache_tree_oid(struct index_state *istate)
742 if (!cache_tree_fully_valid(istate->cache_tree))
743 if (cache_tree_update(istate, 0)) {
744 error(_("unable to update cache tree"));
745 return NULL;
748 return &istate->cache_tree->oid;
751 static int is_index_unchanged(struct repository *r)
753 struct object_id head_oid, *cache_tree_oid;
754 struct commit *head_commit;
755 struct index_state *istate = r->index;
757 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
758 return error(_("could not resolve HEAD commit"));
760 head_commit = lookup_commit(r, &head_oid);
763 * If head_commit is NULL, check_commit, called from
764 * lookup_commit, would have indicated that head_commit is not
765 * a commit object already. parse_commit() will return failure
766 * without further complaints in such a case. Otherwise, if
767 * the commit is invalid, parse_commit() will complain. So
768 * there is nothing for us to say here. Just return failure.
770 if (parse_commit(head_commit))
771 return -1;
773 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
774 return -1;
776 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
779 static int write_author_script(const char *message)
781 struct strbuf buf = STRBUF_INIT;
782 const char *eol;
783 int res;
785 for (;;)
786 if (!*message || starts_with(message, "\n")) {
787 missing_author:
788 /* Missing 'author' line? */
789 unlink(rebase_path_author_script());
790 return 0;
791 } else if (skip_prefix(message, "author ", &message))
792 break;
793 else if ((eol = strchr(message, '\n')))
794 message = eol + 1;
795 else
796 goto missing_author;
798 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
799 while (*message && *message != '\n' && *message != '\r')
800 if (skip_prefix(message, " <", &message))
801 break;
802 else if (*message != '\'')
803 strbuf_addch(&buf, *(message++));
804 else
805 strbuf_addf(&buf, "'\\%c'", *(message++));
806 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
807 while (*message && *message != '\n' && *message != '\r')
808 if (skip_prefix(message, "> ", &message))
809 break;
810 else if (*message != '\'')
811 strbuf_addch(&buf, *(message++));
812 else
813 strbuf_addf(&buf, "'\\%c'", *(message++));
814 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
815 while (*message && *message != '\n' && *message != '\r')
816 if (*message != '\'')
817 strbuf_addch(&buf, *(message++));
818 else
819 strbuf_addf(&buf, "'\\%c'", *(message++));
820 strbuf_addch(&buf, '\'');
821 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
822 strbuf_release(&buf);
823 return res;
827 * Take a series of KEY='VALUE' lines where VALUE part is
828 * sq-quoted, and append <KEY, VALUE> at the end of the string list
830 static int parse_key_value_squoted(char *buf, struct string_list *list)
832 while (*buf) {
833 struct string_list_item *item;
834 char *np;
835 char *cp = strchr(buf, '=');
836 if (!cp) {
837 np = strchrnul(buf, '\n');
838 return error(_("no key present in '%.*s'"),
839 (int) (np - buf), buf);
841 np = strchrnul(cp, '\n');
842 *cp++ = '\0';
843 item = string_list_append(list, buf);
845 buf = np + (*np == '\n');
846 *np = '\0';
847 cp = sq_dequote(cp);
848 if (!cp)
849 return error(_("unable to dequote value of '%s'"),
850 item->string);
851 item->util = xstrdup(cp);
853 return 0;
857 * Reads and parses the state directory's "author-script" file, and sets name,
858 * email and date accordingly.
859 * Returns 0 on success, -1 if the file could not be parsed.
861 * The author script is of the format:
863 * GIT_AUTHOR_NAME='$author_name'
864 * GIT_AUTHOR_EMAIL='$author_email'
865 * GIT_AUTHOR_DATE='$author_date'
867 * where $author_name, $author_email and $author_date are quoted. We are strict
868 * with our parsing, as the file was meant to be eval'd in the now-removed
869 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
870 * from what this function expects, it is better to bail out than to do
871 * something that the user does not expect.
873 int read_author_script(const char *path, char **name, char **email, char **date,
874 int allow_missing)
876 struct strbuf buf = STRBUF_INIT;
877 struct string_list kv = STRING_LIST_INIT_DUP;
878 int retval = -1; /* assume failure */
879 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
881 if (strbuf_read_file(&buf, path, 256) <= 0) {
882 strbuf_release(&buf);
883 if (errno == ENOENT && allow_missing)
884 return 0;
885 else
886 return error_errno(_("could not open '%s' for reading"),
887 path);
890 if (parse_key_value_squoted(buf.buf, &kv))
891 goto finish;
893 for (i = 0; i < kv.nr; i++) {
894 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
895 if (name_i != -2)
896 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
897 else
898 name_i = i;
899 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
900 if (email_i != -2)
901 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
902 else
903 email_i = i;
904 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
905 if (date_i != -2)
906 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
907 else
908 date_i = i;
909 } else {
910 err = error(_("unknown variable '%s'"),
911 kv.items[i].string);
914 if (name_i == -2)
915 error(_("missing 'GIT_AUTHOR_NAME'"));
916 if (email_i == -2)
917 error(_("missing 'GIT_AUTHOR_EMAIL'"));
918 if (date_i == -2)
919 error(_("missing 'GIT_AUTHOR_DATE'"));
920 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
921 goto finish;
922 *name = kv.items[name_i].util;
923 *email = kv.items[email_i].util;
924 *date = kv.items[date_i].util;
925 retval = 0;
926 finish:
927 string_list_clear(&kv, !!retval);
928 strbuf_release(&buf);
929 return retval;
933 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
934 * file with shell quoting into struct strvec. Returns -1 on
935 * error, 0 otherwise.
937 static int read_env_script(struct strvec *env)
939 char *name, *email, *date;
941 if (read_author_script(rebase_path_author_script(),
942 &name, &email, &date, 0))
943 return -1;
945 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
946 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
947 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
948 free(name);
949 free(email);
950 free(date);
952 return 0;
955 static char *get_author(const char *message)
957 size_t len;
958 const char *a;
960 a = find_commit_header(message, "author", &len);
961 if (a)
962 return xmemdupz(a, len);
964 return NULL;
967 static const char *author_date_from_env(const struct strvec *env)
969 int i;
970 const char *date;
972 for (i = 0; i < env->nr; i++)
973 if (skip_prefix(env->v[i],
974 "GIT_AUTHOR_DATE=", &date))
975 return date;
977 * If GIT_AUTHOR_DATE is missing we should have already errored out when
978 * reading the script
980 BUG("GIT_AUTHOR_DATE missing from author script");
983 static const char staged_changes_advice[] =
984 N_("you have staged changes in your working tree\n"
985 "If these changes are meant to be squashed into the previous commit, run:\n"
986 "\n"
987 " git commit --amend %s\n"
988 "\n"
989 "If they are meant to go into a new commit, run:\n"
990 "\n"
991 " git commit %s\n"
992 "\n"
993 "In both cases, once you're done, continue with:\n"
994 "\n"
995 " git rebase --continue\n");
997 #define ALLOW_EMPTY (1<<0)
998 #define EDIT_MSG (1<<1)
999 #define AMEND_MSG (1<<2)
1000 #define CLEANUP_MSG (1<<3)
1001 #define VERIFY_MSG (1<<4)
1002 #define CREATE_ROOT_COMMIT (1<<5)
1003 #define VERBATIM_MSG (1<<6)
1005 static int run_command_silent_on_success(struct child_process *cmd)
1007 struct strbuf buf = STRBUF_INIT;
1008 int rc;
1010 cmd->stdout_to_stderr = 1;
1011 rc = pipe_command(cmd,
1012 NULL, 0,
1013 NULL, 0,
1014 &buf, 0);
1016 if (rc)
1017 fputs(buf.buf, stderr);
1018 strbuf_release(&buf);
1019 return rc;
1023 * If we are cherry-pick, and if the merge did not result in
1024 * hand-editing, we will hit this commit and inherit the original
1025 * author date and name.
1027 * If we are revert, or if our cherry-pick results in a hand merge,
1028 * we had better say that the current user is responsible for that.
1030 * An exception is when run_git_commit() is called during an
1031 * interactive rebase: in that case, we will want to retain the
1032 * author metadata.
1034 static int run_git_commit(const char *defmsg,
1035 struct replay_opts *opts,
1036 unsigned int flags)
1038 struct child_process cmd = CHILD_PROCESS_INIT;
1040 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1041 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1043 cmd.git_cmd = 1;
1045 if (is_rebase_i(opts) &&
1046 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1047 !(!defmsg && (flags & AMEND_MSG))) &&
1048 read_env_script(&cmd.env)) {
1049 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1051 return error(_(staged_changes_advice),
1052 gpg_opt, gpg_opt);
1055 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1057 if (opts->committer_date_is_author_date)
1058 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1059 opts->ignore_date ?
1060 "" :
1061 author_date_from_env(&cmd.env));
1062 if (opts->ignore_date)
1063 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1065 strvec_push(&cmd.args, "commit");
1067 if (!(flags & VERIFY_MSG))
1068 strvec_push(&cmd.args, "-n");
1069 if ((flags & AMEND_MSG))
1070 strvec_push(&cmd.args, "--amend");
1071 if (opts->gpg_sign)
1072 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1073 else
1074 strvec_push(&cmd.args, "--no-gpg-sign");
1075 if (defmsg)
1076 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1077 else if (!(flags & EDIT_MSG))
1078 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1079 if ((flags & CLEANUP_MSG))
1080 strvec_push(&cmd.args, "--cleanup=strip");
1081 if ((flags & VERBATIM_MSG))
1082 strvec_push(&cmd.args, "--cleanup=verbatim");
1083 if ((flags & EDIT_MSG))
1084 strvec_push(&cmd.args, "-e");
1085 else if (!(flags & CLEANUP_MSG) &&
1086 !opts->signoff && !opts->record_origin &&
1087 !opts->explicit_cleanup)
1088 strvec_push(&cmd.args, "--cleanup=verbatim");
1090 if ((flags & ALLOW_EMPTY))
1091 strvec_push(&cmd.args, "--allow-empty");
1093 if (!(flags & EDIT_MSG))
1094 strvec_push(&cmd.args, "--allow-empty-message");
1096 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1097 return run_command_silent_on_success(&cmd);
1098 else
1099 return run_command(&cmd);
1102 static int rest_is_empty(const struct strbuf *sb, int start)
1104 int i, eol;
1105 const char *nl;
1107 /* Check if the rest is just whitespace and Signed-off-by's. */
1108 for (i = start; i < sb->len; i++) {
1109 nl = memchr(sb->buf + i, '\n', sb->len - i);
1110 if (nl)
1111 eol = nl - sb->buf;
1112 else
1113 eol = sb->len;
1115 if (strlen(sign_off_header) <= eol - i &&
1116 starts_with(sb->buf + i, sign_off_header)) {
1117 i = eol;
1118 continue;
1120 while (i < eol)
1121 if (!isspace(sb->buf[i++]))
1122 return 0;
1125 return 1;
1128 void cleanup_message(struct strbuf *msgbuf,
1129 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1131 if (verbose || /* Truncate the message just before the diff, if any. */
1132 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1133 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1134 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1135 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1139 * Find out if the message in the strbuf contains only whitespace and
1140 * Signed-off-by lines.
1142 int message_is_empty(const struct strbuf *sb,
1143 enum commit_msg_cleanup_mode cleanup_mode)
1145 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1146 return 0;
1147 return rest_is_empty(sb, 0);
1151 * See if the user edited the message in the editor or left what
1152 * was in the template intact
1154 int template_untouched(const struct strbuf *sb, const char *template_file,
1155 enum commit_msg_cleanup_mode cleanup_mode)
1157 struct strbuf tmpl = STRBUF_INIT;
1158 const char *start;
1160 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1161 return 0;
1163 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1164 return 0;
1166 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1167 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1168 start = sb->buf;
1169 strbuf_release(&tmpl);
1170 return rest_is_empty(sb, start - sb->buf);
1173 int update_head_with_reflog(const struct commit *old_head,
1174 const struct object_id *new_head,
1175 const char *action, const struct strbuf *msg,
1176 struct strbuf *err)
1178 struct ref_transaction *transaction;
1179 struct strbuf sb = STRBUF_INIT;
1180 const char *nl;
1181 int ret = 0;
1183 if (action) {
1184 strbuf_addstr(&sb, action);
1185 strbuf_addstr(&sb, ": ");
1188 nl = strchr(msg->buf, '\n');
1189 if (nl) {
1190 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1191 } else {
1192 strbuf_addbuf(&sb, msg);
1193 strbuf_addch(&sb, '\n');
1196 transaction = ref_transaction_begin(err);
1197 if (!transaction ||
1198 ref_transaction_update(transaction, "HEAD", new_head,
1199 old_head ? &old_head->object.oid : null_oid(),
1200 0, sb.buf, err) ||
1201 ref_transaction_commit(transaction, err)) {
1202 ret = -1;
1204 ref_transaction_free(transaction);
1205 strbuf_release(&sb);
1207 return ret;
1210 static int run_rewrite_hook(const struct object_id *oldoid,
1211 const struct object_id *newoid)
1213 struct child_process proc = CHILD_PROCESS_INIT;
1214 int code;
1215 struct strbuf sb = STRBUF_INIT;
1216 const char *hook_path = find_hook("post-rewrite");
1218 if (!hook_path)
1219 return 0;
1221 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1222 proc.in = -1;
1223 proc.stdout_to_stderr = 1;
1224 proc.trace2_hook_name = "post-rewrite";
1226 code = start_command(&proc);
1227 if (code)
1228 return code;
1229 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1230 sigchain_push(SIGPIPE, SIG_IGN);
1231 write_in_full(proc.in, sb.buf, sb.len);
1232 close(proc.in);
1233 strbuf_release(&sb);
1234 sigchain_pop(SIGPIPE);
1235 return finish_command(&proc);
1238 void commit_post_rewrite(struct repository *r,
1239 const struct commit *old_head,
1240 const struct object_id *new_head)
1242 struct notes_rewrite_cfg *cfg;
1244 cfg = init_copy_notes_for_rewrite("amend");
1245 if (cfg) {
1246 /* we are amending, so old_head is not NULL */
1247 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1248 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1250 run_rewrite_hook(&old_head->object.oid, new_head);
1253 static int run_prepare_commit_msg_hook(struct repository *r,
1254 struct strbuf *msg,
1255 const char *commit)
1257 int ret = 0;
1258 const char *name, *arg1 = NULL, *arg2 = NULL;
1260 name = git_path_commit_editmsg();
1261 if (write_message(msg->buf, msg->len, name, 0))
1262 return -1;
1264 if (commit) {
1265 arg1 = "commit";
1266 arg2 = commit;
1267 } else {
1268 arg1 = "message";
1270 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1271 arg1, arg2, NULL))
1272 ret = error(_("'prepare-commit-msg' hook failed"));
1274 return ret;
1277 static const char implicit_ident_advice_noconfig[] =
1278 N_("Your name and email address were configured automatically based\n"
1279 "on your username and hostname. Please check that they are accurate.\n"
1280 "You can suppress this message by setting them explicitly. Run the\n"
1281 "following command and follow the instructions in your editor to edit\n"
1282 "your configuration file:\n"
1283 "\n"
1284 " git config --global --edit\n"
1285 "\n"
1286 "After doing this, you may fix the identity used for this commit with:\n"
1287 "\n"
1288 " git commit --amend --reset-author\n");
1290 static const char implicit_ident_advice_config[] =
1291 N_("Your name and email address were configured automatically based\n"
1292 "on your username and hostname. Please check that they are accurate.\n"
1293 "You can suppress this message by setting them explicitly:\n"
1294 "\n"
1295 " git config --global user.name \"Your Name\"\n"
1296 " git config --global user.email you@example.com\n"
1297 "\n"
1298 "After doing this, you may fix the identity used for this commit with:\n"
1299 "\n"
1300 " git commit --amend --reset-author\n");
1302 static const char *implicit_ident_advice(void)
1304 char *user_config = interpolate_path("~/.gitconfig", 0);
1305 char *xdg_config = xdg_config_home("config");
1306 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1308 free(user_config);
1309 free(xdg_config);
1311 if (config_exists)
1312 return _(implicit_ident_advice_config);
1313 else
1314 return _(implicit_ident_advice_noconfig);
1318 void print_commit_summary(struct repository *r,
1319 const char *prefix,
1320 const struct object_id *oid,
1321 unsigned int flags)
1323 struct rev_info rev;
1324 struct commit *commit;
1325 struct strbuf format = STRBUF_INIT;
1326 const char *head;
1327 struct pretty_print_context pctx = {0};
1328 struct strbuf author_ident = STRBUF_INIT;
1329 struct strbuf committer_ident = STRBUF_INIT;
1330 struct ref_store *refs;
1332 commit = lookup_commit(r, oid);
1333 if (!commit)
1334 die(_("couldn't look up newly created commit"));
1335 if (parse_commit(commit))
1336 die(_("could not parse newly created commit"));
1338 strbuf_addstr(&format, "format:%h] %s");
1340 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1341 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1342 if (strbuf_cmp(&author_ident, &committer_ident)) {
1343 strbuf_addstr(&format, "\n Author: ");
1344 strbuf_addbuf_percentquote(&format, &author_ident);
1346 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1347 struct strbuf date = STRBUF_INIT;
1349 format_commit_message(commit, "%ad", &date, &pctx);
1350 strbuf_addstr(&format, "\n Date: ");
1351 strbuf_addbuf_percentquote(&format, &date);
1352 strbuf_release(&date);
1354 if (!committer_ident_sufficiently_given()) {
1355 strbuf_addstr(&format, "\n Committer: ");
1356 strbuf_addbuf_percentquote(&format, &committer_ident);
1357 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1358 strbuf_addch(&format, '\n');
1359 strbuf_addstr(&format, implicit_ident_advice());
1362 strbuf_release(&author_ident);
1363 strbuf_release(&committer_ident);
1365 repo_init_revisions(r, &rev, prefix);
1366 setup_revisions(0, NULL, &rev, NULL);
1368 rev.diff = 1;
1369 rev.diffopt.output_format =
1370 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1372 rev.verbose_header = 1;
1373 rev.show_root_diff = 1;
1374 get_commit_format(format.buf, &rev);
1375 rev.always_show_header = 0;
1376 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1377 diff_setup_done(&rev.diffopt);
1379 refs = get_main_ref_store(the_repository);
1380 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1381 if (!head)
1382 die(_("unable to resolve HEAD after creating commit"));
1383 if (!strcmp(head, "HEAD"))
1384 head = _("detached HEAD");
1385 else
1386 skip_prefix(head, "refs/heads/", &head);
1387 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1388 _(" (root-commit)") : "");
1390 if (!log_tree_commit(&rev, commit)) {
1391 rev.always_show_header = 1;
1392 rev.use_terminator = 1;
1393 log_tree_commit(&rev, commit);
1396 release_revisions(&rev);
1397 strbuf_release(&format);
1400 static int parse_head(struct repository *r, struct commit **head)
1402 struct commit *current_head;
1403 struct object_id oid;
1405 if (get_oid("HEAD", &oid)) {
1406 current_head = NULL;
1407 } else {
1408 current_head = lookup_commit_reference(r, &oid);
1409 if (!current_head)
1410 return error(_("could not parse HEAD"));
1411 if (!oideq(&oid, &current_head->object.oid)) {
1412 warning(_("HEAD %s is not a commit!"),
1413 oid_to_hex(&oid));
1415 if (parse_commit(current_head))
1416 return error(_("could not parse HEAD commit"));
1418 *head = current_head;
1420 return 0;
1424 * Try to commit without forking 'git commit'. In some cases we need
1425 * to run 'git commit' to display an error message
1427 * Returns:
1428 * -1 - error unable to commit
1429 * 0 - success
1430 * 1 - run 'git commit'
1432 static int try_to_commit(struct repository *r,
1433 struct strbuf *msg, const char *author,
1434 struct replay_opts *opts, unsigned int flags,
1435 struct object_id *oid)
1437 struct object_id tree;
1438 struct commit *current_head = NULL;
1439 struct commit_list *parents = NULL;
1440 struct commit_extra_header *extra = NULL;
1441 struct strbuf err = STRBUF_INIT;
1442 struct strbuf commit_msg = STRBUF_INIT;
1443 char *amend_author = NULL;
1444 const char *committer = NULL;
1445 const char *hook_commit = NULL;
1446 enum commit_msg_cleanup_mode cleanup;
1447 int res = 0;
1449 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1450 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1452 if (parse_head(r, &current_head))
1453 return -1;
1455 if (flags & AMEND_MSG) {
1456 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1457 const char *out_enc = get_commit_output_encoding();
1458 const char *message = logmsg_reencode(current_head, NULL,
1459 out_enc);
1461 if (!msg) {
1462 const char *orig_message = NULL;
1464 find_commit_subject(message, &orig_message);
1465 msg = &commit_msg;
1466 strbuf_addstr(msg, orig_message);
1467 hook_commit = "HEAD";
1469 author = amend_author = get_author(message);
1470 unuse_commit_buffer(current_head, message);
1471 if (!author) {
1472 res = error(_("unable to parse commit author"));
1473 goto out;
1475 parents = copy_commit_list(current_head->parents);
1476 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1477 } else if (current_head &&
1478 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1479 commit_list_insert(current_head, &parents);
1482 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1483 res = error(_("git write-tree failed to write a tree"));
1484 goto out;
1487 if (!(flags & ALLOW_EMPTY)) {
1488 struct commit *first_parent = current_head;
1490 if (flags & AMEND_MSG) {
1491 if (current_head->parents) {
1492 first_parent = current_head->parents->item;
1493 if (repo_parse_commit(r, first_parent)) {
1494 res = error(_("could not parse HEAD commit"));
1495 goto out;
1497 } else {
1498 first_parent = NULL;
1501 if (oideq(first_parent
1502 ? get_commit_tree_oid(first_parent)
1503 : the_hash_algo->empty_tree,
1504 &tree)) {
1505 res = 1; /* run 'git commit' to display error message */
1506 goto out;
1510 if (hook_exists("prepare-commit-msg")) {
1511 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1512 if (res)
1513 goto out;
1514 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1515 2048) < 0) {
1516 res = error_errno(_("unable to read commit message "
1517 "from '%s'"),
1518 git_path_commit_editmsg());
1519 goto out;
1521 msg = &commit_msg;
1524 if (flags & CLEANUP_MSG)
1525 cleanup = COMMIT_MSG_CLEANUP_ALL;
1526 else if (flags & VERBATIM_MSG)
1527 cleanup = COMMIT_MSG_CLEANUP_NONE;
1528 else if ((opts->signoff || opts->record_origin) &&
1529 !opts->explicit_cleanup)
1530 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1531 else
1532 cleanup = opts->default_msg_cleanup;
1534 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1535 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1536 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1537 res = 1; /* run 'git commit' to display error message */
1538 goto out;
1541 if (opts->committer_date_is_author_date) {
1542 struct ident_split id;
1543 struct strbuf date = STRBUF_INIT;
1545 if (!opts->ignore_date) {
1546 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1547 res = error(_("invalid author identity '%s'"),
1548 author);
1549 goto out;
1551 if (!id.date_begin) {
1552 res = error(_(
1553 "corrupt author: missing date information"));
1554 goto out;
1556 strbuf_addf(&date, "@%.*s %.*s",
1557 (int)(id.date_end - id.date_begin),
1558 id.date_begin,
1559 (int)(id.tz_end - id.tz_begin),
1560 id.tz_begin);
1561 } else {
1562 reset_ident_date();
1564 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1565 getenv("GIT_COMMITTER_EMAIL"),
1566 WANT_COMMITTER_IDENT,
1567 opts->ignore_date ? NULL : date.buf,
1568 IDENT_STRICT);
1569 strbuf_release(&date);
1570 } else {
1571 reset_ident_date();
1574 if (opts->ignore_date) {
1575 struct ident_split id;
1576 char *name, *email;
1578 if (split_ident_line(&id, author, strlen(author)) < 0) {
1579 error(_("invalid author identity '%s'"), author);
1580 goto out;
1582 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1583 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1584 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1585 IDENT_STRICT);
1586 free(name);
1587 free(email);
1590 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1591 author, committer, opts->gpg_sign, extra)) {
1592 res = error(_("failed to write commit object"));
1593 goto out;
1596 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1597 msg, &err)) {
1598 res = error("%s", err.buf);
1599 goto out;
1602 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1603 if (flags & AMEND_MSG)
1604 commit_post_rewrite(r, current_head, oid);
1606 out:
1607 free_commit_extra_headers(extra);
1608 strbuf_release(&err);
1609 strbuf_release(&commit_msg);
1610 free(amend_author);
1612 return res;
1615 static int write_rebase_head(struct object_id *oid)
1617 if (update_ref("rebase", "REBASE_HEAD", oid,
1618 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1619 return error(_("could not update %s"), "REBASE_HEAD");
1621 return 0;
1624 static int do_commit(struct repository *r,
1625 const char *msg_file, const char *author,
1626 struct replay_opts *opts, unsigned int flags,
1627 struct object_id *oid)
1629 int res = 1;
1631 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1632 struct object_id oid;
1633 struct strbuf sb = STRBUF_INIT;
1635 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1636 return error_errno(_("unable to read commit message "
1637 "from '%s'"),
1638 msg_file);
1640 res = try_to_commit(r, msg_file ? &sb : NULL,
1641 author, opts, flags, &oid);
1642 strbuf_release(&sb);
1643 if (!res) {
1644 refs_delete_ref(get_main_ref_store(r), "",
1645 "CHERRY_PICK_HEAD", NULL, 0);
1646 unlink(git_path_merge_msg(r));
1647 if (!is_rebase_i(opts))
1648 print_commit_summary(r, NULL, &oid,
1649 SUMMARY_SHOW_AUTHOR_DATE);
1650 return res;
1653 if (res == 1) {
1654 if (is_rebase_i(opts) && oid)
1655 if (write_rebase_head(oid))
1656 return -1;
1657 return run_git_commit(msg_file, opts, flags);
1660 return res;
1663 static int is_original_commit_empty(struct commit *commit)
1665 const struct object_id *ptree_oid;
1667 if (parse_commit(commit))
1668 return error(_("could not parse commit %s"),
1669 oid_to_hex(&commit->object.oid));
1670 if (commit->parents) {
1671 struct commit *parent = commit->parents->item;
1672 if (parse_commit(parent))
1673 return error(_("could not parse parent commit %s"),
1674 oid_to_hex(&parent->object.oid));
1675 ptree_oid = get_commit_tree_oid(parent);
1676 } else {
1677 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1680 return oideq(ptree_oid, get_commit_tree_oid(commit));
1684 * Should empty commits be allowed? Return status:
1685 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1686 * 0: Halt on empty commit
1687 * 1: Allow empty commit
1688 * 2: Drop empty commit
1690 static int allow_empty(struct repository *r,
1691 struct replay_opts *opts,
1692 struct commit *commit)
1694 int index_unchanged, originally_empty;
1697 * Four cases:
1699 * (1) we do not allow empty at all and error out.
1701 * (2) we allow ones that were initially empty, and
1702 * just drop the ones that become empty
1704 * (3) we allow ones that were initially empty, but
1705 * halt for the ones that become empty;
1707 * (4) we allow both.
1709 if (!opts->allow_empty)
1710 return 0; /* let "git commit" barf as necessary */
1712 index_unchanged = is_index_unchanged(r);
1713 if (index_unchanged < 0)
1714 return index_unchanged;
1715 if (!index_unchanged)
1716 return 0; /* we do not have to say --allow-empty */
1718 if (opts->keep_redundant_commits)
1719 return 1;
1721 originally_empty = is_original_commit_empty(commit);
1722 if (originally_empty < 0)
1723 return originally_empty;
1724 if (originally_empty)
1725 return 1;
1726 else if (opts->drop_redundant_commits)
1727 return 2;
1728 else
1729 return 0;
1732 static struct {
1733 char c;
1734 const char *str;
1735 } todo_command_info[] = {
1736 [TODO_PICK] = { 'p', "pick" },
1737 [TODO_REVERT] = { 0, "revert" },
1738 [TODO_EDIT] = { 'e', "edit" },
1739 [TODO_REWORD] = { 'r', "reword" },
1740 [TODO_FIXUP] = { 'f', "fixup" },
1741 [TODO_SQUASH] = { 's', "squash" },
1742 [TODO_EXEC] = { 'x', "exec" },
1743 [TODO_BREAK] = { 'b', "break" },
1744 [TODO_LABEL] = { 'l', "label" },
1745 [TODO_RESET] = { 't', "reset" },
1746 [TODO_MERGE] = { 'm', "merge" },
1747 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1748 [TODO_NOOP] = { 0, "noop" },
1749 [TODO_DROP] = { 'd', "drop" },
1750 [TODO_COMMENT] = { 0, NULL },
1753 static const char *command_to_string(const enum todo_command command)
1755 if (command < TODO_COMMENT)
1756 return todo_command_info[command].str;
1757 die(_("unknown command: %d"), command);
1760 static char command_to_char(const enum todo_command command)
1762 if (command < TODO_COMMENT)
1763 return todo_command_info[command].c;
1764 return comment_line_char;
1767 static int is_noop(const enum todo_command command)
1769 return TODO_NOOP <= command;
1772 static int is_fixup(enum todo_command command)
1774 return command == TODO_FIXUP || command == TODO_SQUASH;
1777 /* Does this command create a (non-merge) commit? */
1778 static int is_pick_or_similar(enum todo_command command)
1780 switch (command) {
1781 case TODO_PICK:
1782 case TODO_REVERT:
1783 case TODO_EDIT:
1784 case TODO_REWORD:
1785 case TODO_FIXUP:
1786 case TODO_SQUASH:
1787 return 1;
1788 default:
1789 return 0;
1793 enum todo_item_flags {
1794 TODO_EDIT_MERGE_MSG = (1 << 0),
1795 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1796 TODO_EDIT_FIXUP_MSG = (1 << 2),
1799 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1800 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1801 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1802 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1803 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1805 static int is_fixup_flag(enum todo_command command, unsigned flag)
1807 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1808 (flag & TODO_EDIT_FIXUP_MSG));
1812 * Wrapper around strbuf_add_commented_lines() which avoids double
1813 * commenting commit subjects.
1815 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1817 const char *s = str;
1818 while (len > 0 && s[0] == comment_line_char) {
1819 size_t count;
1820 const char *n = memchr(s, '\n', len);
1821 if (!n)
1822 count = len;
1823 else
1824 count = n - s + 1;
1825 strbuf_add(buf, s, count);
1826 s += count;
1827 len -= count;
1829 strbuf_add_commented_lines(buf, s, len);
1832 /* Does the current fixup chain contain a squash command? */
1833 static int seen_squash(struct replay_opts *opts)
1835 return starts_with(opts->current_fixups.buf, "squash") ||
1836 strstr(opts->current_fixups.buf, "\nsquash");
1839 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1841 strbuf_setlen(buf1, 2);
1842 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1843 strbuf_addch(buf1, '\n');
1844 strbuf_setlen(buf2, 2);
1845 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1846 strbuf_addch(buf2, '\n');
1850 * Comment out any un-commented commit messages, updating the message comments
1851 * to say they will be skipped but do not comment out the empty lines that
1852 * surround commit messages and their comments.
1854 static void update_squash_message_for_fixup(struct strbuf *msg)
1856 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1857 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1858 const char *s, *start;
1859 char *orig_msg;
1860 size_t orig_msg_len;
1861 int i = 1;
1863 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1864 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1865 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1866 while (s) {
1867 const char *next;
1868 size_t off;
1869 if (skip_prefix(s, buf1.buf, &next)) {
1871 * Copy the last message, preserving the blank line
1872 * preceding the current line
1874 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1875 copy_lines(msg, start, s - start - off);
1876 if (off)
1877 strbuf_addch(msg, '\n');
1879 * The next message needs to be commented out but the
1880 * message header is already commented out so just copy
1881 * it and the blank line that follows it.
1883 strbuf_addbuf(msg, &buf2);
1884 if (*next == '\n')
1885 strbuf_addch(msg, *next++);
1886 start = s = next;
1887 copy_lines = add_commented_lines;
1888 update_comment_bufs(&buf1, &buf2, ++i);
1889 } else if (skip_prefix(s, buf2.buf, &next)) {
1890 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1891 copy_lines(msg, start, s - start - off);
1892 start = s - off;
1893 s = next;
1894 copy_lines = strbuf_add;
1895 update_comment_bufs(&buf1, &buf2, ++i);
1896 } else {
1897 s = strchr(s, '\n');
1898 if (s)
1899 s++;
1902 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1903 free(orig_msg);
1904 strbuf_release(&buf1);
1905 strbuf_release(&buf2);
1908 static int append_squash_message(struct strbuf *buf, const char *body,
1909 enum todo_command command, struct replay_opts *opts,
1910 unsigned flag)
1912 const char *fixup_msg;
1913 size_t commented_len = 0, fixup_off;
1915 * amend is non-interactive and not normally used with fixup!
1916 * or squash! commits, so only comment out those subjects when
1917 * squashing commit messages.
1919 if (starts_with(body, "amend!") ||
1920 ((command == TODO_SQUASH || seen_squash(opts)) &&
1921 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1922 commented_len = commit_subject_length(body);
1924 strbuf_addf(buf, "\n%c ", comment_line_char);
1925 strbuf_addf(buf, _(nth_commit_msg_fmt),
1926 ++opts->current_fixup_count + 1);
1927 strbuf_addstr(buf, "\n\n");
1928 strbuf_add_commented_lines(buf, body, commented_len);
1929 /* buf->buf may be reallocated so store an offset into the buffer */
1930 fixup_off = buf->len;
1931 strbuf_addstr(buf, body + commented_len);
1933 /* fixup -C after squash behaves like squash */
1934 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1936 * We're replacing the commit message so we need to
1937 * append the Signed-off-by: trailer if the user
1938 * requested '--signoff'.
1940 if (opts->signoff)
1941 append_signoff(buf, 0, 0);
1943 if ((command == TODO_FIXUP) &&
1944 (flag & TODO_REPLACE_FIXUP_MSG) &&
1945 (file_exists(rebase_path_fixup_msg()) ||
1946 !file_exists(rebase_path_squash_msg()))) {
1947 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1948 if (write_message(fixup_msg, strlen(fixup_msg),
1949 rebase_path_fixup_msg(), 0) < 0)
1950 return error(_("cannot write '%s'"),
1951 rebase_path_fixup_msg());
1952 } else {
1953 unlink(rebase_path_fixup_msg());
1955 } else {
1956 unlink(rebase_path_fixup_msg());
1959 return 0;
1962 static int update_squash_messages(struct repository *r,
1963 enum todo_command command,
1964 struct commit *commit,
1965 struct replay_opts *opts,
1966 unsigned flag)
1968 struct strbuf buf = STRBUF_INIT;
1969 int res = 0;
1970 const char *message, *body;
1971 const char *encoding = get_commit_output_encoding();
1973 if (opts->current_fixup_count > 0) {
1974 struct strbuf header = STRBUF_INIT;
1975 char *eol;
1977 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1978 return error(_("could not read '%s'"),
1979 rebase_path_squash_msg());
1981 eol = buf.buf[0] != comment_line_char ?
1982 buf.buf : strchrnul(buf.buf, '\n');
1984 strbuf_addf(&header, "%c ", comment_line_char);
1985 strbuf_addf(&header, _(combined_commit_msg_fmt),
1986 opts->current_fixup_count + 2);
1987 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1988 strbuf_release(&header);
1989 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1990 update_squash_message_for_fixup(&buf);
1991 } else {
1992 struct object_id head;
1993 struct commit *head_commit;
1994 const char *head_message, *body;
1996 if (get_oid("HEAD", &head))
1997 return error(_("need a HEAD to fixup"));
1998 if (!(head_commit = lookup_commit_reference(r, &head)))
1999 return error(_("could not read HEAD"));
2000 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
2001 return error(_("could not read HEAD's commit message"));
2003 find_commit_subject(head_message, &body);
2004 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2005 rebase_path_fixup_msg(), 0) < 0) {
2006 unuse_commit_buffer(head_commit, head_message);
2007 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2009 strbuf_addf(&buf, "%c ", comment_line_char);
2010 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2011 strbuf_addf(&buf, "\n%c ", comment_line_char);
2012 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2013 _(skip_first_commit_msg_str) :
2014 _(first_commit_msg_str));
2015 strbuf_addstr(&buf, "\n\n");
2016 if (is_fixup_flag(command, flag))
2017 strbuf_add_commented_lines(&buf, body, strlen(body));
2018 else
2019 strbuf_addstr(&buf, body);
2021 unuse_commit_buffer(head_commit, head_message);
2024 if (!(message = logmsg_reencode(commit, NULL, encoding)))
2025 return error(_("could not read commit message of %s"),
2026 oid_to_hex(&commit->object.oid));
2027 find_commit_subject(message, &body);
2029 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2030 res = append_squash_message(&buf, body, command, opts, flag);
2031 } else if (command == TODO_FIXUP) {
2032 strbuf_addf(&buf, "\n%c ", comment_line_char);
2033 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2034 ++opts->current_fixup_count + 1);
2035 strbuf_addstr(&buf, "\n\n");
2036 strbuf_add_commented_lines(&buf, body, strlen(body));
2037 } else
2038 return error(_("unknown command: %d"), command);
2039 unuse_commit_buffer(commit, message);
2041 if (!res)
2042 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2044 strbuf_release(&buf);
2046 if (!res) {
2047 strbuf_addf(&opts->current_fixups, "%s%s %s",
2048 opts->current_fixups.len ? "\n" : "",
2049 command_to_string(command),
2050 oid_to_hex(&commit->object.oid));
2051 res = write_message(opts->current_fixups.buf,
2052 opts->current_fixups.len,
2053 rebase_path_current_fixups(), 0);
2056 return res;
2059 static void flush_rewritten_pending(void)
2061 struct strbuf buf = STRBUF_INIT;
2062 struct object_id newoid;
2063 FILE *out;
2065 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2066 !get_oid("HEAD", &newoid) &&
2067 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2068 char *bol = buf.buf, *eol;
2070 while (*bol) {
2071 eol = strchrnul(bol, '\n');
2072 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2073 bol, oid_to_hex(&newoid));
2074 if (!*eol)
2075 break;
2076 bol = eol + 1;
2078 fclose(out);
2079 unlink(rebase_path_rewritten_pending());
2081 strbuf_release(&buf);
2084 static void record_in_rewritten(struct object_id *oid,
2085 enum todo_command next_command)
2087 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2089 if (!out)
2090 return;
2092 fprintf(out, "%s\n", oid_to_hex(oid));
2093 fclose(out);
2095 if (!is_fixup(next_command))
2096 flush_rewritten_pending();
2099 static int should_edit(struct replay_opts *opts) {
2100 if (opts->edit < 0)
2102 * Note that we only handle the case of non-conflicted
2103 * commits; continue_single_pick() handles the conflicted
2104 * commits itself instead of calling this function.
2106 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2107 return opts->edit;
2110 static void refer_to_commit(struct replay_opts *opts,
2111 struct strbuf *msgbuf, struct commit *commit)
2113 if (opts->commit_use_reference) {
2114 struct pretty_print_context ctx = {
2115 .abbrev = DEFAULT_ABBREV,
2116 .date_mode.type = DATE_SHORT,
2118 format_commit_message(commit, "%h (%s, %ad)", msgbuf, &ctx);
2119 } else {
2120 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2124 static int do_pick_commit(struct repository *r,
2125 struct todo_item *item,
2126 struct replay_opts *opts,
2127 int final_fixup, int *check_todo)
2129 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2130 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2131 struct object_id head;
2132 struct commit *base, *next, *parent;
2133 const char *base_label, *next_label;
2134 char *author = NULL;
2135 struct commit_message msg = { NULL, NULL, NULL, NULL };
2136 struct strbuf msgbuf = STRBUF_INIT;
2137 int res, unborn = 0, reword = 0, allow, drop_commit;
2138 enum todo_command command = item->command;
2139 struct commit *commit = item->commit;
2141 if (opts->no_commit) {
2143 * We do not intend to commit immediately. We just want to
2144 * merge the differences in, so let's compute the tree
2145 * that represents the "current" state for the merge machinery
2146 * to work on.
2148 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2149 return error(_("your index file is unmerged."));
2150 } else {
2151 unborn = get_oid("HEAD", &head);
2152 /* Do we want to generate a root commit? */
2153 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2154 oideq(&head, &opts->squash_onto)) {
2155 if (is_fixup(command))
2156 return error(_("cannot fixup root commit"));
2157 flags |= CREATE_ROOT_COMMIT;
2158 unborn = 1;
2159 } else if (unborn)
2160 oidcpy(&head, the_hash_algo->empty_tree);
2161 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2162 NULL, 0))
2163 return error_dirty_index(r, opts);
2165 discard_index(r->index);
2167 if (!commit->parents)
2168 parent = NULL;
2169 else if (commit->parents->next) {
2170 /* Reverting or cherry-picking a merge commit */
2171 int cnt;
2172 struct commit_list *p;
2174 if (!opts->mainline)
2175 return error(_("commit %s is a merge but no -m option was given."),
2176 oid_to_hex(&commit->object.oid));
2178 for (cnt = 1, p = commit->parents;
2179 cnt != opts->mainline && p;
2180 cnt++)
2181 p = p->next;
2182 if (cnt != opts->mainline || !p)
2183 return error(_("commit %s does not have parent %d"),
2184 oid_to_hex(&commit->object.oid), opts->mainline);
2185 parent = p->item;
2186 } else if (1 < opts->mainline)
2188 * Non-first parent explicitly specified as mainline for
2189 * non-merge commit
2191 return error(_("commit %s does not have parent %d"),
2192 oid_to_hex(&commit->object.oid), opts->mainline);
2193 else
2194 parent = commit->parents->item;
2196 if (get_message(commit, &msg) != 0)
2197 return error(_("cannot get commit message for %s"),
2198 oid_to_hex(&commit->object.oid));
2200 if (opts->allow_ff && !is_fixup(command) &&
2201 ((parent && oideq(&parent->object.oid, &head)) ||
2202 (!parent && unborn))) {
2203 if (is_rebase_i(opts))
2204 write_author_script(msg.message);
2205 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2206 opts);
2207 if (res || command != TODO_REWORD)
2208 goto leave;
2209 reword = 1;
2210 msg_file = NULL;
2211 goto fast_forward_edit;
2213 if (parent && parse_commit(parent) < 0)
2214 /* TRANSLATORS: The first %s will be a "todo" command like
2215 "revert" or "pick", the second %s a SHA1. */
2216 return error(_("%s: cannot parse parent commit %s"),
2217 command_to_string(command),
2218 oid_to_hex(&parent->object.oid));
2221 * "commit" is an existing commit. We would want to apply
2222 * the difference it introduces since its first parent "prev"
2223 * on top of the current HEAD if we are cherry-pick. Or the
2224 * reverse of it if we are revert.
2227 if (command == TODO_REVERT) {
2228 base = commit;
2229 base_label = msg.label;
2230 next = parent;
2231 next_label = msg.parent_label;
2232 if (opts->commit_use_reference) {
2233 strbuf_addstr(&msgbuf,
2234 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2235 } else {
2236 strbuf_addstr(&msgbuf, "Revert \"");
2237 strbuf_addstr(&msgbuf, msg.subject);
2238 strbuf_addstr(&msgbuf, "\"");
2240 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2241 refer_to_commit(opts, &msgbuf, commit);
2243 if (commit->parents && commit->parents->next) {
2244 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2245 refer_to_commit(opts, &msgbuf, parent);
2247 strbuf_addstr(&msgbuf, ".\n");
2248 } else {
2249 const char *p;
2251 base = parent;
2252 base_label = msg.parent_label;
2253 next = commit;
2254 next_label = msg.label;
2256 /* Append the commit log message to msgbuf. */
2257 if (find_commit_subject(msg.message, &p))
2258 strbuf_addstr(&msgbuf, p);
2260 if (opts->record_origin) {
2261 strbuf_complete_line(&msgbuf);
2262 if (!has_conforming_footer(&msgbuf, NULL, 0))
2263 strbuf_addch(&msgbuf, '\n');
2264 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2265 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2266 strbuf_addstr(&msgbuf, ")\n");
2268 if (!is_fixup(command))
2269 author = get_author(msg.message);
2272 if (command == TODO_REWORD)
2273 reword = 1;
2274 else if (is_fixup(command)) {
2275 if (update_squash_messages(r, command, commit,
2276 opts, item->flags)) {
2277 res = -1;
2278 goto leave;
2280 flags |= AMEND_MSG;
2281 if (!final_fixup)
2282 msg_file = rebase_path_squash_msg();
2283 else if (file_exists(rebase_path_fixup_msg())) {
2284 flags |= VERBATIM_MSG;
2285 msg_file = rebase_path_fixup_msg();
2286 } else {
2287 const char *dest = git_path_squash_msg(r);
2288 unlink(dest);
2289 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2290 res = error(_("could not rename '%s' to '%s'"),
2291 rebase_path_squash_msg(), dest);
2292 goto leave;
2294 unlink(git_path_merge_msg(r));
2295 msg_file = dest;
2296 flags |= EDIT_MSG;
2300 if (opts->signoff && !is_fixup(command))
2301 append_signoff(&msgbuf, 0, 0);
2303 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2304 res = -1;
2305 else if (!opts->strategy ||
2306 !strcmp(opts->strategy, "recursive") ||
2307 !strcmp(opts->strategy, "ort") ||
2308 command == TODO_REVERT) {
2309 res = do_recursive_merge(r, base, next, base_label, next_label,
2310 &head, &msgbuf, opts);
2311 if (res < 0)
2312 goto leave;
2314 res |= write_message(msgbuf.buf, msgbuf.len,
2315 git_path_merge_msg(r), 0);
2316 } else {
2317 struct commit_list *common = NULL;
2318 struct commit_list *remotes = NULL;
2320 res = write_message(msgbuf.buf, msgbuf.len,
2321 git_path_merge_msg(r), 0);
2323 commit_list_insert(base, &common);
2324 commit_list_insert(next, &remotes);
2325 res |= try_merge_command(r, opts->strategy,
2326 opts->xopts.nr, opts->xopts.v,
2327 common, oid_to_hex(&head), remotes);
2328 free_commit_list(common);
2329 free_commit_list(remotes);
2333 * If the merge was clean or if it failed due to conflict, we write
2334 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2335 * However, if the merge did not even start, then we don't want to
2336 * write it at all.
2338 if ((command == TODO_PICK || command == TODO_REWORD ||
2339 command == TODO_EDIT) && !opts->no_commit &&
2340 (res == 0 || res == 1) &&
2341 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2342 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2343 res = -1;
2344 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2345 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2346 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2347 res = -1;
2349 if (res) {
2350 error(command == TODO_REVERT
2351 ? _("could not revert %s... %s")
2352 : _("could not apply %s... %s"),
2353 short_commit_name(commit), msg.subject);
2354 print_advice(r, res == 1, opts);
2355 repo_rerere(r, opts->allow_rerere_auto);
2356 goto leave;
2359 drop_commit = 0;
2360 allow = allow_empty(r, opts, commit);
2361 if (allow < 0) {
2362 res = allow;
2363 goto leave;
2364 } else if (allow == 1) {
2365 flags |= ALLOW_EMPTY;
2366 } else if (allow == 2) {
2367 drop_commit = 1;
2368 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2369 NULL, 0);
2370 unlink(git_path_merge_msg(r));
2371 unlink(git_path_auto_merge(r));
2372 fprintf(stderr,
2373 _("dropping %s %s -- patch contents already upstream\n"),
2374 oid_to_hex(&commit->object.oid), msg.subject);
2375 } /* else allow == 0 and there's nothing special to do */
2376 if (!opts->no_commit && !drop_commit) {
2377 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2378 res = do_commit(r, msg_file, author, opts, flags,
2379 commit? &commit->object.oid : NULL);
2380 else
2381 res = error(_("unable to parse commit author"));
2382 *check_todo = !!(flags & EDIT_MSG);
2383 if (!res && reword) {
2384 fast_forward_edit:
2385 res = run_git_commit(NULL, opts, EDIT_MSG |
2386 VERIFY_MSG | AMEND_MSG |
2387 (flags & ALLOW_EMPTY));
2388 *check_todo = 1;
2393 if (!res && final_fixup) {
2394 unlink(rebase_path_fixup_msg());
2395 unlink(rebase_path_squash_msg());
2396 unlink(rebase_path_current_fixups());
2397 strbuf_reset(&opts->current_fixups);
2398 opts->current_fixup_count = 0;
2401 leave:
2402 free_message(commit, &msg);
2403 free(author);
2404 strbuf_release(&msgbuf);
2405 update_abort_safety_file();
2407 return res;
2410 static int prepare_revs(struct replay_opts *opts)
2413 * picking (but not reverting) ranges (but not individual revisions)
2414 * should be done in reverse
2416 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2417 opts->revs->reverse ^= 1;
2419 if (prepare_revision_walk(opts->revs))
2420 return error(_("revision walk setup failed"));
2422 return 0;
2425 static int read_and_refresh_cache(struct repository *r,
2426 struct replay_opts *opts)
2428 struct lock_file index_lock = LOCK_INIT;
2429 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2430 if (repo_read_index(r) < 0) {
2431 rollback_lock_file(&index_lock);
2432 return error(_("git %s: failed to read the index"),
2433 action_name(opts));
2435 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2437 if (index_fd >= 0) {
2438 if (write_locked_index(r->index, &index_lock,
2439 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2440 return error(_("git %s: failed to refresh the index"),
2441 action_name(opts));
2446 * If we are resolving merges in any way other than "ort", then
2447 * expand the sparse index.
2449 if (opts->strategy && strcmp(opts->strategy, "ort"))
2450 ensure_full_index(r->index);
2451 return 0;
2454 void todo_list_release(struct todo_list *todo_list)
2456 strbuf_release(&todo_list->buf);
2457 FREE_AND_NULL(todo_list->items);
2458 todo_list->nr = todo_list->alloc = 0;
2461 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2463 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2464 todo_list->total_nr++;
2465 return todo_list->items + todo_list->nr++;
2468 const char *todo_item_get_arg(struct todo_list *todo_list,
2469 struct todo_item *item)
2471 return todo_list->buf.buf + item->arg_offset;
2474 static int is_command(enum todo_command command, const char **bol)
2476 const char *str = todo_command_info[command].str;
2477 const char nick = todo_command_info[command].c;
2478 const char *p = *bol;
2480 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2481 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2482 (*bol = p);
2485 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2487 switch (command) {
2488 case TODO_LABEL:
2490 * '#' is not a valid label as the merge command uses it to
2491 * separate merge parents from the commit subject.
2493 if (!strcmp(arg, "#") ||
2494 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2495 return error(_("'%s' is not a valid label"), arg);
2496 break;
2498 case TODO_UPDATE_REF:
2499 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2500 return error(_("'%s' is not a valid refname"), arg);
2501 if (check_refname_format(arg, 0))
2502 return error(_("update-ref requires a fully qualified "
2503 "refname e.g. refs/heads/%s"), arg);
2504 break;
2506 default:
2507 BUG("unexpected todo_command");
2510 return 0;
2513 static int parse_insn_line(struct repository *r, struct todo_item *item,
2514 const char *buf, const char *bol, char *eol)
2516 struct object_id commit_oid;
2517 char *end_of_object_name;
2518 int i, saved, status, padding;
2520 item->flags = 0;
2522 /* left-trim */
2523 bol += strspn(bol, " \t");
2525 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2526 item->command = TODO_COMMENT;
2527 item->commit = NULL;
2528 item->arg_offset = bol - buf;
2529 item->arg_len = eol - bol;
2530 return 0;
2533 for (i = 0; i < TODO_COMMENT; i++)
2534 if (is_command(i, &bol)) {
2535 item->command = i;
2536 break;
2538 if (i >= TODO_COMMENT)
2539 return error(_("invalid command '%.*s'"),
2540 (int)strcspn(bol, " \t\r\n"), bol);
2542 /* Eat up extra spaces/ tabs before object name */
2543 padding = strspn(bol, " \t");
2544 bol += padding;
2546 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2547 if (bol != eol)
2548 return error(_("%s does not accept arguments: '%s'"),
2549 command_to_string(item->command), bol);
2550 item->commit = NULL;
2551 item->arg_offset = bol - buf;
2552 item->arg_len = eol - bol;
2553 return 0;
2556 if (!padding)
2557 return error(_("missing arguments for %s"),
2558 command_to_string(item->command));
2560 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2561 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2562 int ret = 0;
2564 item->commit = NULL;
2565 item->arg_offset = bol - buf;
2566 item->arg_len = (int)(eol - bol);
2567 if (item->command == TODO_LABEL ||
2568 item->command == TODO_UPDATE_REF) {
2569 saved = *eol;
2570 *eol = '\0';
2571 ret = check_label_or_ref_arg(item->command, bol);
2572 *eol = saved;
2574 return ret;
2577 if (item->command == TODO_FIXUP) {
2578 if (skip_prefix(bol, "-C", &bol)) {
2579 bol += strspn(bol, " \t");
2580 item->flags |= TODO_REPLACE_FIXUP_MSG;
2581 } else if (skip_prefix(bol, "-c", &bol)) {
2582 bol += strspn(bol, " \t");
2583 item->flags |= TODO_EDIT_FIXUP_MSG;
2587 if (item->command == TODO_MERGE) {
2588 if (skip_prefix(bol, "-C", &bol))
2589 bol += strspn(bol, " \t");
2590 else if (skip_prefix(bol, "-c", &bol)) {
2591 bol += strspn(bol, " \t");
2592 item->flags |= TODO_EDIT_MERGE_MSG;
2593 } else {
2594 item->flags |= TODO_EDIT_MERGE_MSG;
2595 item->commit = NULL;
2596 item->arg_offset = bol - buf;
2597 item->arg_len = (int)(eol - bol);
2598 return 0;
2602 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2603 saved = *end_of_object_name;
2604 *end_of_object_name = '\0';
2605 status = get_oid(bol, &commit_oid);
2606 if (status < 0)
2607 error(_("could not parse '%s'"), bol); /* return later */
2608 *end_of_object_name = saved;
2610 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2611 item->arg_offset = bol - buf;
2612 item->arg_len = (int)(eol - bol);
2614 if (status < 0)
2615 return status;
2617 item->commit = lookup_commit_reference(r, &commit_oid);
2618 return item->commit ? 0 : -1;
2621 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2623 const char *todo_file, *bol;
2624 struct strbuf buf = STRBUF_INIT;
2625 int ret = 0;
2627 todo_file = git_path_todo_file();
2628 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2629 if (errno == ENOENT || errno == ENOTDIR)
2630 return -1;
2631 else
2632 return error_errno("unable to open '%s'", todo_file);
2634 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2635 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2636 *action = REPLAY_PICK;
2637 else if (is_command(TODO_REVERT, &bol) &&
2638 (*bol == ' ' || *bol == '\t'))
2639 *action = REPLAY_REVERT;
2640 else
2641 ret = -1;
2643 strbuf_release(&buf);
2645 return ret;
2648 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2649 struct todo_list *todo_list)
2651 struct todo_item *item;
2652 char *p = buf, *next_p;
2653 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2655 todo_list->current = todo_list->nr = 0;
2657 for (i = 1; *p; i++, p = next_p) {
2658 char *eol = strchrnul(p, '\n');
2660 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2662 if (p != eol && eol[-1] == '\r')
2663 eol--; /* strip Carriage Return */
2665 item = append_new_todo(todo_list);
2666 item->offset_in_buf = p - todo_list->buf.buf;
2667 if (parse_insn_line(r, item, buf, p, eol)) {
2668 res = error(_("invalid line %d: %.*s"),
2669 i, (int)(eol - p), p);
2670 item->command = TODO_COMMENT + 1;
2671 item->arg_offset = p - buf;
2672 item->arg_len = (int)(eol - p);
2673 item->commit = NULL;
2676 if (fixup_okay)
2677 ; /* do nothing */
2678 else if (is_fixup(item->command))
2679 return error(_("cannot '%s' without a previous commit"),
2680 command_to_string(item->command));
2681 else if (!is_noop(item->command))
2682 fixup_okay = 1;
2685 return res;
2688 static int count_commands(struct todo_list *todo_list)
2690 int count = 0, i;
2692 for (i = 0; i < todo_list->nr; i++)
2693 if (todo_list->items[i].command != TODO_COMMENT)
2694 count++;
2696 return count;
2699 static int get_item_line_offset(struct todo_list *todo_list, int index)
2701 return index < todo_list->nr ?
2702 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2705 static const char *get_item_line(struct todo_list *todo_list, int index)
2707 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2710 static int get_item_line_length(struct todo_list *todo_list, int index)
2712 return get_item_line_offset(todo_list, index + 1)
2713 - get_item_line_offset(todo_list, index);
2716 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2718 int fd;
2719 ssize_t len;
2721 fd = open(path, O_RDONLY);
2722 if (fd < 0)
2723 return error_errno(_("could not open '%s'"), path);
2724 len = strbuf_read(sb, fd, 0);
2725 close(fd);
2726 if (len < 0)
2727 return error(_("could not read '%s'."), path);
2728 return len;
2731 static int have_finished_the_last_pick(void)
2733 struct strbuf buf = STRBUF_INIT;
2734 const char *eol;
2735 const char *todo_path = git_path_todo_file();
2736 int ret = 0;
2738 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2739 if (errno == ENOENT) {
2740 return 0;
2741 } else {
2742 error_errno("unable to open '%s'", todo_path);
2743 return 0;
2746 /* If there is only one line then we are done */
2747 eol = strchr(buf.buf, '\n');
2748 if (!eol || !eol[1])
2749 ret = 1;
2751 strbuf_release(&buf);
2753 return ret;
2756 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2758 struct replay_opts opts = REPLAY_OPTS_INIT;
2759 int need_cleanup = 0;
2761 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2762 if (!refs_delete_ref(get_main_ref_store(r), "",
2763 "CHERRY_PICK_HEAD", NULL, 0) &&
2764 verbose)
2765 warning(_("cancelling a cherry picking in progress"));
2766 opts.action = REPLAY_PICK;
2767 need_cleanup = 1;
2770 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2771 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2772 NULL, 0) &&
2773 verbose)
2774 warning(_("cancelling a revert in progress"));
2775 opts.action = REPLAY_REVERT;
2776 need_cleanup = 1;
2779 unlink(git_path_auto_merge(r));
2781 if (!need_cleanup)
2782 return;
2784 if (!have_finished_the_last_pick())
2785 return;
2787 sequencer_remove_state(&opts);
2790 static void todo_list_write_total_nr(struct todo_list *todo_list)
2792 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2794 if (f) {
2795 fprintf(f, "%d\n", todo_list->total_nr);
2796 fclose(f);
2800 static int read_populate_todo(struct repository *r,
2801 struct todo_list *todo_list,
2802 struct replay_opts *opts)
2804 const char *todo_file = get_todo_path(opts);
2805 int res;
2807 strbuf_reset(&todo_list->buf);
2808 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2809 return -1;
2811 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2812 if (res) {
2813 if (is_rebase_i(opts))
2814 return error(_("please fix this using "
2815 "'git rebase --edit-todo'."));
2816 return error(_("unusable instruction sheet: '%s'"), todo_file);
2819 if (!todo_list->nr &&
2820 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2821 return error(_("no commits parsed."));
2823 if (!is_rebase_i(opts)) {
2824 enum todo_command valid =
2825 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2826 int i;
2828 for (i = 0; i < todo_list->nr; i++)
2829 if (valid == todo_list->items[i].command)
2830 continue;
2831 else if (valid == TODO_PICK)
2832 return error(_("cannot cherry-pick during a revert."));
2833 else
2834 return error(_("cannot revert during a cherry-pick."));
2837 if (is_rebase_i(opts)) {
2838 struct todo_list done = TODO_LIST_INIT;
2840 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2841 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2842 todo_list->done_nr = count_commands(&done);
2843 else
2844 todo_list->done_nr = 0;
2846 todo_list->total_nr = todo_list->done_nr
2847 + count_commands(todo_list);
2848 todo_list_release(&done);
2850 todo_list_write_total_nr(todo_list);
2853 return 0;
2856 static int git_config_string_dup(char **dest,
2857 const char *var, const char *value)
2859 if (!value)
2860 return config_error_nonbool(var);
2861 free(*dest);
2862 *dest = xstrdup(value);
2863 return 0;
2866 static int populate_opts_cb(const char *key, const char *value, void *data)
2868 struct replay_opts *opts = data;
2869 int error_flag = 1;
2871 if (!value)
2872 error_flag = 0;
2873 else if (!strcmp(key, "options.no-commit"))
2874 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2875 else if (!strcmp(key, "options.edit"))
2876 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2877 else if (!strcmp(key, "options.allow-empty"))
2878 opts->allow_empty =
2879 git_config_bool_or_int(key, value, &error_flag);
2880 else if (!strcmp(key, "options.allow-empty-message"))
2881 opts->allow_empty_message =
2882 git_config_bool_or_int(key, value, &error_flag);
2883 else if (!strcmp(key, "options.keep-redundant-commits"))
2884 opts->keep_redundant_commits =
2885 git_config_bool_or_int(key, value, &error_flag);
2886 else if (!strcmp(key, "options.signoff"))
2887 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2888 else if (!strcmp(key, "options.record-origin"))
2889 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2890 else if (!strcmp(key, "options.allow-ff"))
2891 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2892 else if (!strcmp(key, "options.mainline"))
2893 opts->mainline = git_config_int(key, value);
2894 else if (!strcmp(key, "options.strategy"))
2895 git_config_string_dup(&opts->strategy, key, value);
2896 else if (!strcmp(key, "options.gpg-sign"))
2897 git_config_string_dup(&opts->gpg_sign, key, value);
2898 else if (!strcmp(key, "options.strategy-option")) {
2899 strvec_push(&opts->xopts, value);
2900 } else if (!strcmp(key, "options.allow-rerere-auto"))
2901 opts->allow_rerere_auto =
2902 git_config_bool_or_int(key, value, &error_flag) ?
2903 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2904 else if (!strcmp(key, "options.default-msg-cleanup")) {
2905 opts->explicit_cleanup = 1;
2906 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2907 } else
2908 return error(_("invalid key: %s"), key);
2910 if (!error_flag)
2911 return error(_("invalid value for '%s': '%s'"), key, value);
2913 return 0;
2916 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2918 int i;
2919 int count;
2920 const char **argv;
2921 char *strategy_opts_string = raw_opts;
2923 if (*strategy_opts_string == ' ')
2924 strategy_opts_string++;
2926 count = split_cmdline(strategy_opts_string, &argv);
2927 if (count < 0)
2928 BUG("could not split '%s': %s", strategy_opts_string,
2929 split_cmdline_strerror(count));
2930 for (i = 0; i < count; i++) {
2931 const char *arg = argv[i];
2933 skip_prefix(arg, "--", &arg);
2934 strvec_push(&opts->xopts, arg);
2936 free(argv);
2939 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2941 strbuf_reset(buf);
2942 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2943 return;
2944 opts->strategy = strbuf_detach(buf, NULL);
2945 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2946 return;
2948 parse_strategy_opts(opts, buf->buf);
2951 static int read_populate_opts(struct replay_opts *opts)
2953 if (is_rebase_i(opts)) {
2954 struct strbuf buf = STRBUF_INIT;
2955 int ret = 0;
2957 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2958 READ_ONELINER_SKIP_IF_EMPTY)) {
2959 if (!starts_with(buf.buf, "-S"))
2960 strbuf_reset(&buf);
2961 else {
2962 free(opts->gpg_sign);
2963 opts->gpg_sign = xstrdup(buf.buf + 2);
2965 strbuf_reset(&buf);
2968 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2969 READ_ONELINER_SKIP_IF_EMPTY)) {
2970 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2971 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2972 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2973 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2974 strbuf_reset(&buf);
2977 if (file_exists(rebase_path_verbose()))
2978 opts->verbose = 1;
2980 if (file_exists(rebase_path_quiet()))
2981 opts->quiet = 1;
2983 if (file_exists(rebase_path_signoff())) {
2984 opts->allow_ff = 0;
2985 opts->signoff = 1;
2988 if (file_exists(rebase_path_cdate_is_adate())) {
2989 opts->allow_ff = 0;
2990 opts->committer_date_is_author_date = 1;
2993 if (file_exists(rebase_path_ignore_date())) {
2994 opts->allow_ff = 0;
2995 opts->ignore_date = 1;
2998 if (file_exists(rebase_path_reschedule_failed_exec()))
2999 opts->reschedule_failed_exec = 1;
3000 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3001 opts->reschedule_failed_exec = 0;
3003 if (file_exists(rebase_path_drop_redundant_commits()))
3004 opts->drop_redundant_commits = 1;
3006 if (file_exists(rebase_path_keep_redundant_commits()))
3007 opts->keep_redundant_commits = 1;
3009 read_strategy_opts(opts, &buf);
3010 strbuf_reset(&buf);
3012 if (read_oneliner(&opts->current_fixups,
3013 rebase_path_current_fixups(),
3014 READ_ONELINER_SKIP_IF_EMPTY)) {
3015 const char *p = opts->current_fixups.buf;
3016 opts->current_fixup_count = 1;
3017 while ((p = strchr(p, '\n'))) {
3018 opts->current_fixup_count++;
3019 p++;
3023 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3024 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
3025 ret = error(_("unusable squash-onto"));
3026 goto done_rebase_i;
3028 opts->have_squash_onto = 1;
3031 done_rebase_i:
3032 strbuf_release(&buf);
3033 return ret;
3036 if (!file_exists(git_path_opts_file()))
3037 return 0;
3039 * The function git_parse_source(), called from git_config_from_file(),
3040 * may die() in case of a syntactically incorrect file. We do not care
3041 * about this case, though, because we wrote that file ourselves, so we
3042 * are pretty certain that it is syntactically correct.
3044 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3045 return error(_("malformed options sheet: '%s'"),
3046 git_path_opts_file());
3047 return 0;
3050 static void write_strategy_opts(struct replay_opts *opts)
3052 struct strbuf buf = STRBUF_INIT;
3055 * Quote strategy options so that they can be read correctly
3056 * by split_cmdline().
3058 quote_cmdline(&buf, opts->xopts.v);
3059 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3060 strbuf_release(&buf);
3063 int write_basic_state(struct replay_opts *opts, const char *head_name,
3064 struct commit *onto, const struct object_id *orig_head)
3066 if (head_name)
3067 write_file(rebase_path_head_name(), "%s\n", head_name);
3068 if (onto)
3069 write_file(rebase_path_onto(), "%s\n",
3070 oid_to_hex(&onto->object.oid));
3071 if (orig_head)
3072 write_file(rebase_path_orig_head(), "%s\n",
3073 oid_to_hex(orig_head));
3075 if (opts->quiet)
3076 write_file(rebase_path_quiet(), "%s", "");
3077 if (opts->verbose)
3078 write_file(rebase_path_verbose(), "%s", "");
3079 if (opts->strategy)
3080 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3081 if (opts->xopts.nr > 0)
3082 write_strategy_opts(opts);
3084 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3085 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3086 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3087 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3089 if (opts->gpg_sign)
3090 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3091 if (opts->signoff)
3092 write_file(rebase_path_signoff(), "--signoff\n");
3093 if (opts->drop_redundant_commits)
3094 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3095 if (opts->keep_redundant_commits)
3096 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3097 if (opts->committer_date_is_author_date)
3098 write_file(rebase_path_cdate_is_adate(), "%s", "");
3099 if (opts->ignore_date)
3100 write_file(rebase_path_ignore_date(), "%s", "");
3101 if (opts->reschedule_failed_exec)
3102 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3103 else
3104 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3106 return 0;
3109 static int walk_revs_populate_todo(struct todo_list *todo_list,
3110 struct replay_opts *opts)
3112 enum todo_command command = opts->action == REPLAY_PICK ?
3113 TODO_PICK : TODO_REVERT;
3114 const char *command_string = todo_command_info[command].str;
3115 const char *encoding;
3116 struct commit *commit;
3118 if (prepare_revs(opts))
3119 return -1;
3121 encoding = get_log_output_encoding();
3123 while ((commit = get_revision(opts->revs))) {
3124 struct todo_item *item = append_new_todo(todo_list);
3125 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3126 const char *subject;
3127 int subject_len;
3129 item->command = command;
3130 item->commit = commit;
3131 item->arg_offset = 0;
3132 item->arg_len = 0;
3133 item->offset_in_buf = todo_list->buf.len;
3134 subject_len = find_commit_subject(commit_buffer, &subject);
3135 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3136 short_commit_name(commit), subject_len, subject);
3137 unuse_commit_buffer(commit, commit_buffer);
3140 if (!todo_list->nr)
3141 return error(_("empty commit set passed"));
3143 return 0;
3146 static int create_seq_dir(struct repository *r)
3148 enum replay_action action;
3149 const char *in_progress_error = NULL;
3150 const char *in_progress_advice = NULL;
3151 unsigned int advise_skip =
3152 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3153 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3155 if (!sequencer_get_last_command(r, &action)) {
3156 switch (action) {
3157 case REPLAY_REVERT:
3158 in_progress_error = _("revert is already in progress");
3159 in_progress_advice =
3160 _("try \"git revert (--continue | %s--abort | --quit)\"");
3161 break;
3162 case REPLAY_PICK:
3163 in_progress_error = _("cherry-pick is already in progress");
3164 in_progress_advice =
3165 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3166 break;
3167 default:
3168 BUG("unexpected action in create_seq_dir");
3171 if (in_progress_error) {
3172 error("%s", in_progress_error);
3173 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3174 advise(in_progress_advice,
3175 advise_skip ? "--skip | " : "");
3176 return -1;
3178 if (mkdir(git_path_seq_dir(), 0777) < 0)
3179 return error_errno(_("could not create sequencer directory '%s'"),
3180 git_path_seq_dir());
3182 return 0;
3185 static int save_head(const char *head)
3187 struct lock_file head_lock = LOCK_INIT;
3188 struct strbuf buf = STRBUF_INIT;
3189 int fd;
3190 ssize_t written;
3192 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3193 if (fd < 0)
3194 return error_errno(_("could not lock HEAD"));
3195 strbuf_addf(&buf, "%s\n", head);
3196 written = write_in_full(fd, buf.buf, buf.len);
3197 strbuf_release(&buf);
3198 if (written < 0) {
3199 error_errno(_("could not write to '%s'"), git_path_head_file());
3200 rollback_lock_file(&head_lock);
3201 return -1;
3203 if (commit_lock_file(&head_lock) < 0)
3204 return error(_("failed to finalize '%s'"), git_path_head_file());
3205 return 0;
3208 static int rollback_is_safe(void)
3210 struct strbuf sb = STRBUF_INIT;
3211 struct object_id expected_head, actual_head;
3213 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3214 strbuf_trim(&sb);
3215 if (get_oid_hex(sb.buf, &expected_head)) {
3216 strbuf_release(&sb);
3217 die(_("could not parse %s"), git_path_abort_safety_file());
3219 strbuf_release(&sb);
3221 else if (errno == ENOENT)
3222 oidclr(&expected_head);
3223 else
3224 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3226 if (get_oid("HEAD", &actual_head))
3227 oidclr(&actual_head);
3229 return oideq(&actual_head, &expected_head);
3232 static int reset_merge(const struct object_id *oid)
3234 struct child_process cmd = CHILD_PROCESS_INIT;
3236 cmd.git_cmd = 1;
3237 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3239 if (!is_null_oid(oid))
3240 strvec_push(&cmd.args, oid_to_hex(oid));
3242 return run_command(&cmd);
3245 static int rollback_single_pick(struct repository *r)
3247 struct object_id head_oid;
3249 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3250 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3251 return error(_("no cherry-pick or revert in progress"));
3252 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3253 return error(_("cannot resolve HEAD"));
3254 if (is_null_oid(&head_oid))
3255 return error(_("cannot abort from a branch yet to be born"));
3256 return reset_merge(&head_oid);
3259 static int skip_single_pick(void)
3261 struct object_id head;
3263 if (read_ref_full("HEAD", 0, &head, NULL))
3264 return error(_("cannot resolve HEAD"));
3265 return reset_merge(&head);
3268 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3270 FILE *f;
3271 struct object_id oid;
3272 struct strbuf buf = STRBUF_INIT;
3273 const char *p;
3275 f = fopen(git_path_head_file(), "r");
3276 if (!f && errno == ENOENT) {
3278 * There is no multiple-cherry-pick in progress.
3279 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3280 * a single-cherry-pick in progress, abort that.
3282 return rollback_single_pick(r);
3284 if (!f)
3285 return error_errno(_("cannot open '%s'"), git_path_head_file());
3286 if (strbuf_getline_lf(&buf, f)) {
3287 error(_("cannot read '%s': %s"), git_path_head_file(),
3288 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3289 fclose(f);
3290 goto fail;
3292 fclose(f);
3293 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3294 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3295 git_path_head_file());
3296 goto fail;
3298 if (is_null_oid(&oid)) {
3299 error(_("cannot abort from a branch yet to be born"));
3300 goto fail;
3303 if (!rollback_is_safe()) {
3304 /* Do not error, just do not rollback */
3305 warning(_("You seem to have moved HEAD. "
3306 "Not rewinding, check your HEAD!"));
3307 } else
3308 if (reset_merge(&oid))
3309 goto fail;
3310 strbuf_release(&buf);
3311 return sequencer_remove_state(opts);
3312 fail:
3313 strbuf_release(&buf);
3314 return -1;
3317 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3319 enum replay_action action = -1;
3320 sequencer_get_last_command(r, &action);
3323 * Check whether the subcommand requested to skip the commit is actually
3324 * in progress and that it's safe to skip the commit.
3326 * opts->action tells us which subcommand requested to skip the commit.
3327 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3328 * action is in progress and we can skip the commit.
3330 * Otherwise we check that the last instruction was related to the
3331 * particular subcommand we're trying to execute and barf if that's not
3332 * the case.
3334 * Finally we check that the rollback is "safe", i.e., has the HEAD
3335 * moved? In this case, it doesn't make sense to "reset the merge" and
3336 * "skip the commit" as the user already handled this by committing. But
3337 * we'd not want to barf here, instead give advice on how to proceed. We
3338 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3339 * it gets removed when the user commits, so if it still exists we're
3340 * sure the user can't have committed before.
3342 switch (opts->action) {
3343 case REPLAY_REVERT:
3344 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3345 if (action != REPLAY_REVERT)
3346 return error(_("no revert in progress"));
3347 if (!rollback_is_safe())
3348 goto give_advice;
3350 break;
3351 case REPLAY_PICK:
3352 if (!refs_ref_exists(get_main_ref_store(r),
3353 "CHERRY_PICK_HEAD")) {
3354 if (action != REPLAY_PICK)
3355 return error(_("no cherry-pick in progress"));
3356 if (!rollback_is_safe())
3357 goto give_advice;
3359 break;
3360 default:
3361 BUG("unexpected action in sequencer_skip");
3364 if (skip_single_pick())
3365 return error(_("failed to skip the commit"));
3366 if (!is_directory(git_path_seq_dir()))
3367 return 0;
3369 return sequencer_continue(r, opts);
3371 give_advice:
3372 error(_("there is nothing to skip"));
3374 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3375 advise(_("have you committed already?\n"
3376 "try \"git %s --continue\""),
3377 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3379 return -1;
3382 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3384 struct lock_file todo_lock = LOCK_INIT;
3385 const char *todo_path = get_todo_path(opts);
3386 int next = todo_list->current, offset, fd;
3389 * rebase -i writes "git-rebase-todo" without the currently executing
3390 * command, appending it to "done" instead.
3392 if (is_rebase_i(opts))
3393 next++;
3395 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3396 if (fd < 0)
3397 return error_errno(_("could not lock '%s'"), todo_path);
3398 offset = get_item_line_offset(todo_list, next);
3399 if (write_in_full(fd, todo_list->buf.buf + offset,
3400 todo_list->buf.len - offset) < 0)
3401 return error_errno(_("could not write to '%s'"), todo_path);
3402 if (commit_lock_file(&todo_lock) < 0)
3403 return error(_("failed to finalize '%s'"), todo_path);
3405 if (is_rebase_i(opts) && next > 0) {
3406 const char *done = rebase_path_done();
3407 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3408 int ret = 0;
3410 if (fd < 0)
3411 return 0;
3412 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3413 get_item_line_length(todo_list, next - 1))
3414 < 0)
3415 ret = error_errno(_("could not write to '%s'"), done);
3416 if (close(fd) < 0)
3417 ret = error_errno(_("failed to finalize '%s'"), done);
3418 return ret;
3420 return 0;
3423 static int save_opts(struct replay_opts *opts)
3425 const char *opts_file = git_path_opts_file();
3426 int res = 0;
3428 if (opts->no_commit)
3429 res |= git_config_set_in_file_gently(opts_file,
3430 "options.no-commit", "true");
3431 if (opts->edit >= 0)
3432 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3433 opts->edit ? "true" : "false");
3434 if (opts->allow_empty)
3435 res |= git_config_set_in_file_gently(opts_file,
3436 "options.allow-empty", "true");
3437 if (opts->allow_empty_message)
3438 res |= git_config_set_in_file_gently(opts_file,
3439 "options.allow-empty-message", "true");
3440 if (opts->keep_redundant_commits)
3441 res |= git_config_set_in_file_gently(opts_file,
3442 "options.keep-redundant-commits", "true");
3443 if (opts->signoff)
3444 res |= git_config_set_in_file_gently(opts_file,
3445 "options.signoff", "true");
3446 if (opts->record_origin)
3447 res |= git_config_set_in_file_gently(opts_file,
3448 "options.record-origin", "true");
3449 if (opts->allow_ff)
3450 res |= git_config_set_in_file_gently(opts_file,
3451 "options.allow-ff", "true");
3452 if (opts->mainline) {
3453 struct strbuf buf = STRBUF_INIT;
3454 strbuf_addf(&buf, "%d", opts->mainline);
3455 res |= git_config_set_in_file_gently(opts_file,
3456 "options.mainline", buf.buf);
3457 strbuf_release(&buf);
3459 if (opts->strategy)
3460 res |= git_config_set_in_file_gently(opts_file,
3461 "options.strategy", opts->strategy);
3462 if (opts->gpg_sign)
3463 res |= git_config_set_in_file_gently(opts_file,
3464 "options.gpg-sign", opts->gpg_sign);
3465 for (size_t i = 0; i < opts->xopts.nr; i++)
3466 res |= git_config_set_multivar_in_file_gently(opts_file,
3467 "options.strategy-option",
3468 opts->xopts.v[i], "^$", 0);
3469 if (opts->allow_rerere_auto)
3470 res |= git_config_set_in_file_gently(opts_file,
3471 "options.allow-rerere-auto",
3472 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3473 "true" : "false");
3475 if (opts->explicit_cleanup)
3476 res |= git_config_set_in_file_gently(opts_file,
3477 "options.default-msg-cleanup",
3478 describe_cleanup_mode(opts->default_msg_cleanup));
3479 return res;
3482 static int make_patch(struct repository *r,
3483 struct commit *commit,
3484 struct replay_opts *opts)
3486 struct strbuf buf = STRBUF_INIT;
3487 struct rev_info log_tree_opt;
3488 const char *subject;
3489 char hex[GIT_MAX_HEXSZ + 1];
3490 int res = 0;
3492 oid_to_hex_r(hex, &commit->object.oid);
3493 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3494 return -1;
3495 res |= write_rebase_head(&commit->object.oid);
3497 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3498 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3499 repo_init_revisions(r, &log_tree_opt, NULL);
3500 log_tree_opt.abbrev = 0;
3501 log_tree_opt.diff = 1;
3502 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3503 log_tree_opt.disable_stdin = 1;
3504 log_tree_opt.no_commit_id = 1;
3505 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3506 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3507 if (!log_tree_opt.diffopt.file)
3508 res |= error_errno(_("could not open '%s'"), buf.buf);
3509 else {
3510 res |= log_tree_commit(&log_tree_opt, commit);
3511 fclose(log_tree_opt.diffopt.file);
3513 strbuf_reset(&buf);
3515 strbuf_addf(&buf, "%s/message", get_dir(opts));
3516 if (!file_exists(buf.buf)) {
3517 const char *encoding = get_commit_output_encoding();
3518 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3519 find_commit_subject(commit_buffer, &subject);
3520 res |= write_message(subject, strlen(subject), buf.buf, 1);
3521 unuse_commit_buffer(commit, commit_buffer);
3523 strbuf_release(&buf);
3524 release_revisions(&log_tree_opt);
3526 return res;
3529 static int intend_to_amend(void)
3531 struct object_id head;
3532 char *p;
3534 if (get_oid("HEAD", &head))
3535 return error(_("cannot read HEAD"));
3537 p = oid_to_hex(&head);
3538 return write_message(p, strlen(p), rebase_path_amend(), 1);
3541 static int error_with_patch(struct repository *r,
3542 struct commit *commit,
3543 const char *subject, int subject_len,
3544 struct replay_opts *opts,
3545 int exit_code, int to_amend)
3547 if (commit) {
3548 if (make_patch(r, commit, opts))
3549 return -1;
3550 } else if (copy_file(rebase_path_message(),
3551 git_path_merge_msg(r), 0666))
3552 return error(_("unable to copy '%s' to '%s'"),
3553 git_path_merge_msg(r), rebase_path_message());
3555 if (to_amend) {
3556 if (intend_to_amend())
3557 return -1;
3559 fprintf(stderr,
3560 _("You can amend the commit now, with\n"
3561 "\n"
3562 " git commit --amend %s\n"
3563 "\n"
3564 "Once you are satisfied with your changes, run\n"
3565 "\n"
3566 " git rebase --continue\n"),
3567 gpg_sign_opt_quoted(opts));
3568 } else if (exit_code) {
3569 if (commit)
3570 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3571 short_commit_name(commit), subject_len, subject);
3572 else
3574 * We don't have the hash of the parent so
3575 * just print the line from the todo file.
3577 fprintf_ln(stderr, _("Could not merge %.*s"),
3578 subject_len, subject);
3581 return exit_code;
3584 static int error_failed_squash(struct repository *r,
3585 struct commit *commit,
3586 struct replay_opts *opts,
3587 int subject_len,
3588 const char *subject)
3590 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3591 return error(_("could not copy '%s' to '%s'"),
3592 rebase_path_squash_msg(), rebase_path_message());
3593 unlink(git_path_merge_msg(r));
3594 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3595 return error(_("could not copy '%s' to '%s'"),
3596 rebase_path_message(),
3597 git_path_merge_msg(r));
3598 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3601 static int do_exec(struct repository *r, const char *command_line)
3603 struct child_process cmd = CHILD_PROCESS_INIT;
3604 int dirty, status;
3606 fprintf(stderr, _("Executing: %s\n"), command_line);
3607 cmd.use_shell = 1;
3608 strvec_push(&cmd.args, command_line);
3609 status = run_command(&cmd);
3611 /* force re-reading of the cache */
3612 discard_index(r->index);
3613 if (repo_read_index(r) < 0)
3614 return error(_("could not read index"));
3616 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3618 if (status) {
3619 warning(_("execution failed: %s\n%s"
3620 "You can fix the problem, and then run\n"
3621 "\n"
3622 " git rebase --continue\n"
3623 "\n"),
3624 command_line,
3625 dirty ? N_("and made changes to the index and/or the "
3626 "working tree\n") : "");
3627 if (status == 127)
3628 /* command not found */
3629 status = 1;
3630 } else if (dirty) {
3631 warning(_("execution succeeded: %s\nbut "
3632 "left changes to the index and/or the working tree\n"
3633 "Commit or stash your changes, and then run\n"
3634 "\n"
3635 " git rebase --continue\n"
3636 "\n"), command_line);
3637 status = 1;
3640 return status;
3643 __attribute__((format (printf, 2, 3)))
3644 static int safe_append(const char *filename, const char *fmt, ...)
3646 va_list ap;
3647 struct lock_file lock = LOCK_INIT;
3648 int fd = hold_lock_file_for_update(&lock, filename,
3649 LOCK_REPORT_ON_ERROR);
3650 struct strbuf buf = STRBUF_INIT;
3652 if (fd < 0)
3653 return -1;
3655 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3656 error_errno(_("could not read '%s'"), filename);
3657 rollback_lock_file(&lock);
3658 return -1;
3660 strbuf_complete(&buf, '\n');
3661 va_start(ap, fmt);
3662 strbuf_vaddf(&buf, fmt, ap);
3663 va_end(ap);
3665 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3666 error_errno(_("could not write to '%s'"), filename);
3667 strbuf_release(&buf);
3668 rollback_lock_file(&lock);
3669 return -1;
3671 if (commit_lock_file(&lock) < 0) {
3672 strbuf_release(&buf);
3673 rollback_lock_file(&lock);
3674 return error(_("failed to finalize '%s'"), filename);
3677 strbuf_release(&buf);
3678 return 0;
3681 static int do_label(struct repository *r, const char *name, int len)
3683 struct ref_store *refs = get_main_ref_store(r);
3684 struct ref_transaction *transaction;
3685 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3686 struct strbuf msg = STRBUF_INIT;
3687 int ret = 0;
3688 struct object_id head_oid;
3690 if (len == 1 && *name == '#')
3691 return error(_("illegal label name: '%.*s'"), len, name);
3693 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3694 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3696 transaction = ref_store_transaction_begin(refs, &err);
3697 if (!transaction) {
3698 error("%s", err.buf);
3699 ret = -1;
3700 } else if (get_oid("HEAD", &head_oid)) {
3701 error(_("could not read HEAD"));
3702 ret = -1;
3703 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3704 NULL, 0, msg.buf, &err) < 0 ||
3705 ref_transaction_commit(transaction, &err)) {
3706 error("%s", err.buf);
3707 ret = -1;
3709 ref_transaction_free(transaction);
3710 strbuf_release(&err);
3711 strbuf_release(&msg);
3713 if (!ret)
3714 ret = safe_append(rebase_path_refs_to_delete(),
3715 "%s\n", ref_name.buf);
3716 strbuf_release(&ref_name);
3718 return ret;
3721 static const char *sequencer_reflog_action(struct replay_opts *opts)
3723 if (!opts->reflog_action) {
3724 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3725 opts->reflog_action =
3726 xstrdup(opts->reflog_action ? opts->reflog_action
3727 : action_name(opts));
3730 return opts->reflog_action;
3733 __attribute__((format (printf, 3, 4)))
3734 static const char *reflog_message(struct replay_opts *opts,
3735 const char *sub_action, const char *fmt, ...)
3737 va_list ap;
3738 static struct strbuf buf = STRBUF_INIT;
3740 va_start(ap, fmt);
3741 strbuf_reset(&buf);
3742 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3743 if (sub_action)
3744 strbuf_addf(&buf, " (%s)", sub_action);
3745 if (fmt) {
3746 strbuf_addstr(&buf, ": ");
3747 strbuf_vaddf(&buf, fmt, ap);
3749 va_end(ap);
3751 return buf.buf;
3754 static struct commit *lookup_label(struct repository *r, const char *label,
3755 int len, struct strbuf *buf)
3757 struct commit *commit;
3758 struct object_id oid;
3760 strbuf_reset(buf);
3761 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3762 if (!read_ref(buf->buf, &oid)) {
3763 commit = lookup_commit_object(r, &oid);
3764 } else {
3765 /* fall back to non-rewritten ref or commit */
3766 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3767 commit = lookup_commit_reference_by_name(buf->buf);
3770 if (!commit)
3771 error(_("could not resolve '%s'"), buf->buf);
3773 return commit;
3776 static int do_reset(struct repository *r,
3777 const char *name, int len,
3778 struct replay_opts *opts)
3780 struct strbuf ref_name = STRBUF_INIT;
3781 struct object_id oid;
3782 struct lock_file lock = LOCK_INIT;
3783 struct tree_desc desc = { 0 };
3784 struct tree *tree;
3785 struct unpack_trees_options unpack_tree_opts = { 0 };
3786 int ret = 0;
3788 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3789 return -1;
3791 if (len == 10 && !strncmp("[new root]", name, len)) {
3792 if (!opts->have_squash_onto) {
3793 const char *hex;
3794 if (commit_tree("", 0, the_hash_algo->empty_tree,
3795 NULL, &opts->squash_onto,
3796 NULL, NULL))
3797 return error(_("writing fake root commit"));
3798 opts->have_squash_onto = 1;
3799 hex = oid_to_hex(&opts->squash_onto);
3800 if (write_message(hex, strlen(hex),
3801 rebase_path_squash_onto(), 0))
3802 return error(_("writing squash-onto"));
3804 oidcpy(&oid, &opts->squash_onto);
3805 } else {
3806 int i;
3807 struct commit *commit;
3809 /* Determine the length of the label */
3810 for (i = 0; i < len; i++)
3811 if (isspace(name[i]))
3812 break;
3813 len = i;
3815 commit = lookup_label(r, name, len, &ref_name);
3816 if (!commit) {
3817 ret = -1;
3818 goto cleanup;
3820 oid = commit->object.oid;
3823 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3824 unpack_tree_opts.head_idx = 1;
3825 unpack_tree_opts.src_index = r->index;
3826 unpack_tree_opts.dst_index = r->index;
3827 unpack_tree_opts.fn = oneway_merge;
3828 unpack_tree_opts.merge = 1;
3829 unpack_tree_opts.update = 1;
3830 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3831 unpack_tree_opts.skip_cache_tree_update = 1;
3832 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3834 if (repo_read_index_unmerged(r)) {
3835 ret = error_resolve_conflict(action_name(opts));
3836 goto cleanup;
3839 if (!fill_tree_descriptor(r, &desc, &oid)) {
3840 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3841 goto cleanup;
3844 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3845 ret = -1;
3846 goto cleanup;
3849 tree = parse_tree_indirect(&oid);
3850 prime_cache_tree(r, r->index, tree);
3852 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3853 ret = error(_("could not write index"));
3855 if (!ret)
3856 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3857 len, name), "HEAD", &oid,
3858 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3859 cleanup:
3860 free((void *)desc.buffer);
3861 if (ret < 0)
3862 rollback_lock_file(&lock);
3863 strbuf_release(&ref_name);
3864 clear_unpack_trees_porcelain(&unpack_tree_opts);
3865 return ret;
3868 static int do_merge(struct repository *r,
3869 struct commit *commit,
3870 const char *arg, int arg_len,
3871 int flags, int *check_todo, struct replay_opts *opts)
3873 int run_commit_flags = 0;
3874 struct strbuf ref_name = STRBUF_INIT;
3875 struct commit *head_commit, *merge_commit, *i;
3876 struct commit_list *bases, *j;
3877 struct commit_list *to_merge = NULL, **tail = &to_merge;
3878 const char *strategy = !opts->xopts.nr &&
3879 (!opts->strategy ||
3880 !strcmp(opts->strategy, "recursive") ||
3881 !strcmp(opts->strategy, "ort")) ?
3882 NULL : opts->strategy;
3883 struct merge_options o;
3884 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3885 static struct lock_file lock;
3886 const char *p;
3888 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3889 ret = -1;
3890 goto leave_merge;
3893 head_commit = lookup_commit_reference_by_name("HEAD");
3894 if (!head_commit) {
3895 ret = error(_("cannot merge without a current revision"));
3896 goto leave_merge;
3900 * For octopus merges, the arg starts with the list of revisions to be
3901 * merged. The list is optionally followed by '#' and the oneline.
3903 merge_arg_len = oneline_offset = arg_len;
3904 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3905 if (!*p)
3906 break;
3907 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3908 p += 1 + strspn(p + 1, " \t\n");
3909 oneline_offset = p - arg;
3910 break;
3912 k = strcspn(p, " \t\n");
3913 if (!k)
3914 continue;
3915 merge_commit = lookup_label(r, p, k, &ref_name);
3916 if (!merge_commit) {
3917 ret = error(_("unable to parse '%.*s'"), k, p);
3918 goto leave_merge;
3920 tail = &commit_list_insert(merge_commit, tail)->next;
3921 p += k;
3922 merge_arg_len = p - arg;
3925 if (!to_merge) {
3926 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3927 goto leave_merge;
3930 if (opts->have_squash_onto &&
3931 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3933 * When the user tells us to "merge" something into a
3934 * "[new root]", let's simply fast-forward to the merge head.
3936 rollback_lock_file(&lock);
3937 if (to_merge->next)
3938 ret = error(_("octopus merge cannot be executed on "
3939 "top of a [new root]"));
3940 else
3941 ret = fast_forward_to(r, &to_merge->item->object.oid,
3942 &head_commit->object.oid, 0,
3943 opts);
3944 goto leave_merge;
3948 * If HEAD is not identical to the first parent of the original merge
3949 * commit, we cannot fast-forward.
3951 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3952 oideq(&commit->parents->item->object.oid,
3953 &head_commit->object.oid);
3956 * If any merge head is different from the original one, we cannot
3957 * fast-forward.
3959 if (can_fast_forward) {
3960 struct commit_list *p = commit->parents->next;
3962 for (j = to_merge; j && p; j = j->next, p = p->next)
3963 if (!oideq(&j->item->object.oid,
3964 &p->item->object.oid)) {
3965 can_fast_forward = 0;
3966 break;
3969 * If the number of merge heads differs from the original merge
3970 * commit, we cannot fast-forward.
3972 if (j || p)
3973 can_fast_forward = 0;
3976 if (can_fast_forward) {
3977 rollback_lock_file(&lock);
3978 ret = fast_forward_to(r, &commit->object.oid,
3979 &head_commit->object.oid, 0, opts);
3980 if (flags & TODO_EDIT_MERGE_MSG)
3981 goto fast_forward_edit;
3983 goto leave_merge;
3986 if (commit) {
3987 const char *encoding = get_commit_output_encoding();
3988 const char *message = logmsg_reencode(commit, NULL, encoding);
3989 const char *body;
3990 int len;
3992 if (!message) {
3993 ret = error(_("could not get commit message of '%s'"),
3994 oid_to_hex(&commit->object.oid));
3995 goto leave_merge;
3997 write_author_script(message);
3998 find_commit_subject(message, &body);
3999 len = strlen(body);
4000 ret = write_message(body, len, git_path_merge_msg(r), 0);
4001 unuse_commit_buffer(commit, message);
4002 if (ret) {
4003 error_errno(_("could not write '%s'"),
4004 git_path_merge_msg(r));
4005 goto leave_merge;
4007 } else {
4008 struct strbuf buf = STRBUF_INIT;
4009 int len;
4011 strbuf_addf(&buf, "author %s", git_author_info(0));
4012 write_author_script(buf.buf);
4013 strbuf_reset(&buf);
4015 if (oneline_offset < arg_len) {
4016 p = arg + oneline_offset;
4017 len = arg_len - oneline_offset;
4018 } else {
4019 strbuf_addf(&buf, "Merge %s '%.*s'",
4020 to_merge->next ? "branches" : "branch",
4021 merge_arg_len, arg);
4022 p = buf.buf;
4023 len = buf.len;
4026 ret = write_message(p, len, git_path_merge_msg(r), 0);
4027 strbuf_release(&buf);
4028 if (ret) {
4029 error_errno(_("could not write '%s'"),
4030 git_path_merge_msg(r));
4031 goto leave_merge;
4035 if (strategy || to_merge->next) {
4036 /* Octopus merge */
4037 struct child_process cmd = CHILD_PROCESS_INIT;
4039 if (read_env_script(&cmd.env)) {
4040 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4042 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4043 goto leave_merge;
4046 if (opts->committer_date_is_author_date)
4047 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4048 opts->ignore_date ?
4049 "" :
4050 author_date_from_env(&cmd.env));
4051 if (opts->ignore_date)
4052 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4054 cmd.git_cmd = 1;
4055 strvec_push(&cmd.args, "merge");
4056 strvec_push(&cmd.args, "-s");
4057 if (!strategy)
4058 strvec_push(&cmd.args, "octopus");
4059 else {
4060 strvec_push(&cmd.args, strategy);
4061 for (k = 0; k < opts->xopts.nr; k++)
4062 strvec_pushf(&cmd.args,
4063 "-X%s", opts->xopts.v[k]);
4065 if (!(flags & TODO_EDIT_MERGE_MSG))
4066 strvec_push(&cmd.args, "--no-edit");
4067 else
4068 strvec_push(&cmd.args, "--edit");
4069 strvec_push(&cmd.args, "--no-ff");
4070 strvec_push(&cmd.args, "--no-log");
4071 strvec_push(&cmd.args, "--no-stat");
4072 strvec_push(&cmd.args, "-F");
4073 strvec_push(&cmd.args, git_path_merge_msg(r));
4074 if (opts->gpg_sign)
4075 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4076 else
4077 strvec_push(&cmd.args, "--no-gpg-sign");
4079 /* Add the tips to be merged */
4080 for (j = to_merge; j; j = j->next)
4081 strvec_push(&cmd.args,
4082 oid_to_hex(&j->item->object.oid));
4084 strbuf_release(&ref_name);
4085 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4086 NULL, 0);
4087 rollback_lock_file(&lock);
4089 ret = run_command(&cmd);
4091 /* force re-reading of the cache */
4092 if (!ret) {
4093 discard_index(r->index);
4094 if (repo_read_index(r) < 0)
4095 ret = error(_("could not read index"));
4097 goto leave_merge;
4100 merge_commit = to_merge->item;
4101 bases = get_merge_bases(head_commit, merge_commit);
4102 if (bases && oideq(&merge_commit->object.oid,
4103 &bases->item->object.oid)) {
4104 ret = 0;
4105 /* skip merging an ancestor of HEAD */
4106 goto leave_merge;
4109 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4110 git_path_merge_head(r), 0);
4111 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4113 bases = reverse_commit_list(bases);
4115 repo_read_index(r);
4116 init_merge_options(&o, r);
4117 o.branch1 = "HEAD";
4118 o.branch2 = ref_name.buf;
4119 o.buffer_output = 2;
4121 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4123 * TODO: Should use merge_incore_recursive() and
4124 * merge_switch_to_result(), skipping the call to
4125 * merge_switch_to_result() when we don't actually need to
4126 * update the index and working copy immediately.
4128 ret = merge_ort_recursive(&o,
4129 head_commit, merge_commit, bases,
4130 &i);
4131 } else {
4132 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4133 &i);
4135 if (ret <= 0)
4136 fputs(o.obuf.buf, stdout);
4137 strbuf_release(&o.obuf);
4138 if (ret < 0) {
4139 error(_("could not even attempt to merge '%.*s'"),
4140 merge_arg_len, arg);
4141 goto leave_merge;
4144 * The return value of merge_recursive() is 1 on clean, and 0 on
4145 * unclean merge.
4147 * Let's reverse that, so that do_merge() returns 0 upon success and
4148 * 1 upon failed merge (keeping the return value -1 for the cases where
4149 * we will want to reschedule the `merge` command).
4151 ret = !ret;
4153 if (r->index->cache_changed &&
4154 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4155 ret = error(_("merge: Unable to write new index file"));
4156 goto leave_merge;
4159 rollback_lock_file(&lock);
4160 if (ret)
4161 repo_rerere(r, opts->allow_rerere_auto);
4162 else
4164 * In case of problems, we now want to return a positive
4165 * value (a negative one would indicate that the `merge`
4166 * command needs to be rescheduled).
4168 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4169 run_commit_flags);
4171 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4172 fast_forward_edit:
4173 *check_todo = 1;
4174 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4175 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4179 leave_merge:
4180 strbuf_release(&ref_name);
4181 rollback_lock_file(&lock);
4182 free_commit_list(to_merge);
4183 return ret;
4186 static int write_update_refs_state(struct string_list *refs_to_oids)
4188 int result = 0;
4189 struct lock_file lock = LOCK_INIT;
4190 FILE *fp = NULL;
4191 struct string_list_item *item;
4192 char *path;
4194 path = rebase_path_update_refs(the_repository->gitdir);
4196 if (!refs_to_oids->nr) {
4197 if (unlink(path) && errno != ENOENT)
4198 result = error_errno(_("could not unlink: %s"), path);
4199 goto cleanup;
4202 if (safe_create_leading_directories(path)) {
4203 result = error(_("unable to create leading directories of %s"),
4204 path);
4205 goto cleanup;
4208 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4209 result = error(_("another 'rebase' process appears to be running; "
4210 "'%s.lock' already exists"),
4211 path);
4212 goto cleanup;
4215 fp = fdopen_lock_file(&lock, "w");
4216 if (!fp) {
4217 result = error_errno(_("could not open '%s' for writing"), path);
4218 rollback_lock_file(&lock);
4219 goto cleanup;
4222 for_each_string_list_item(item, refs_to_oids) {
4223 struct update_ref_record *rec = item->util;
4224 fprintf(fp, "%s\n%s\n%s\n", item->string,
4225 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4228 result = commit_lock_file(&lock);
4230 cleanup:
4231 free(path);
4232 return result;
4236 * Parse the update-refs file for the current rebase, then remove the
4237 * refs that do not appear in the todo_list (and have not had updated
4238 * values stored) and add refs that are in the todo_list but not
4239 * represented in the update-refs file.
4241 * If there are changes to the update-refs list, then write the new state
4242 * to disk.
4244 void todo_list_filter_update_refs(struct repository *r,
4245 struct todo_list *todo_list)
4247 int i;
4248 int updated = 0;
4249 struct string_list update_refs = STRING_LIST_INIT_DUP;
4251 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4254 * For each item in the update_refs list, if it has no updated
4255 * value and does not appear in the todo_list, then remove it
4256 * from the update_refs list.
4258 for (i = 0; i < update_refs.nr; i++) {
4259 int j;
4260 int found = 0;
4261 const char *ref = update_refs.items[i].string;
4262 size_t reflen = strlen(ref);
4263 struct update_ref_record *rec = update_refs.items[i].util;
4265 /* OID already stored as updated. */
4266 if (!is_null_oid(&rec->after))
4267 continue;
4269 for (j = 0; !found && j < todo_list->total_nr; j++) {
4270 struct todo_item *item = &todo_list->items[j];
4271 const char *arg = todo_list->buf.buf + item->arg_offset;
4273 if (item->command != TODO_UPDATE_REF)
4274 continue;
4276 if (item->arg_len != reflen ||
4277 strncmp(arg, ref, reflen))
4278 continue;
4280 found = 1;
4283 if (!found) {
4284 free(update_refs.items[i].string);
4285 free(update_refs.items[i].util);
4287 update_refs.nr--;
4288 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4290 updated = 1;
4291 i--;
4296 * For each todo_item, check if its ref is in the update_refs list.
4297 * If not, then add it as an un-updated ref.
4299 for (i = 0; i < todo_list->total_nr; i++) {
4300 struct todo_item *item = &todo_list->items[i];
4301 const char *arg = todo_list->buf.buf + item->arg_offset;
4302 int j, found = 0;
4304 if (item->command != TODO_UPDATE_REF)
4305 continue;
4307 for (j = 0; !found && j < update_refs.nr; j++) {
4308 const char *ref = update_refs.items[j].string;
4310 found = strlen(ref) == item->arg_len &&
4311 !strncmp(ref, arg, item->arg_len);
4314 if (!found) {
4315 struct string_list_item *inserted;
4316 struct strbuf argref = STRBUF_INIT;
4318 strbuf_add(&argref, arg, item->arg_len);
4319 inserted = string_list_insert(&update_refs, argref.buf);
4320 inserted->util = init_update_ref_record(argref.buf);
4321 strbuf_release(&argref);
4322 updated = 1;
4326 if (updated)
4327 write_update_refs_state(&update_refs);
4328 string_list_clear(&update_refs, 1);
4331 static int do_update_ref(struct repository *r, const char *refname)
4333 struct string_list_item *item;
4334 struct string_list list = STRING_LIST_INIT_DUP;
4336 if (sequencer_get_update_refs_state(r->gitdir, &list))
4337 return -1;
4339 for_each_string_list_item(item, &list) {
4340 if (!strcmp(item->string, refname)) {
4341 struct update_ref_record *rec = item->util;
4342 if (read_ref("HEAD", &rec->after))
4343 return -1;
4344 break;
4348 write_update_refs_state(&list);
4349 string_list_clear(&list, 1);
4350 return 0;
4353 static int do_update_refs(struct repository *r, int quiet)
4355 int res = 0;
4356 struct string_list_item *item;
4357 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4358 struct ref_store *refs = get_main_ref_store(r);
4359 struct strbuf update_msg = STRBUF_INIT;
4360 struct strbuf error_msg = STRBUF_INIT;
4362 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4363 return res;
4365 for_each_string_list_item(item, &refs_to_oids) {
4366 struct update_ref_record *rec = item->util;
4367 int loop_res;
4369 loop_res = refs_update_ref(refs, "rewritten during rebase",
4370 item->string,
4371 &rec->after, &rec->before,
4372 0, UPDATE_REFS_MSG_ON_ERR);
4373 res |= loop_res;
4375 if (quiet)
4376 continue;
4378 if (loop_res)
4379 strbuf_addf(&error_msg, "\t%s\n", item->string);
4380 else
4381 strbuf_addf(&update_msg, "\t%s\n", item->string);
4384 if (!quiet &&
4385 (update_msg.len || error_msg.len)) {
4386 fprintf(stderr,
4387 _("Updated the following refs with %s:\n%s"),
4388 "--update-refs",
4389 update_msg.buf);
4391 if (res)
4392 fprintf(stderr,
4393 _("Failed to update the following refs with %s:\n%s"),
4394 "--update-refs",
4395 error_msg.buf);
4398 string_list_clear(&refs_to_oids, 1);
4399 strbuf_release(&update_msg);
4400 strbuf_release(&error_msg);
4401 return res;
4404 static int is_final_fixup(struct todo_list *todo_list)
4406 int i = todo_list->current;
4408 if (!is_fixup(todo_list->items[i].command))
4409 return 0;
4411 while (++i < todo_list->nr)
4412 if (is_fixup(todo_list->items[i].command))
4413 return 0;
4414 else if (!is_noop(todo_list->items[i].command))
4415 break;
4416 return 1;
4419 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4421 int i;
4423 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4424 if (!is_noop(todo_list->items[i].command))
4425 return todo_list->items[i].command;
4427 return -1;
4430 void create_autostash(struct repository *r, const char *path)
4432 struct strbuf buf = STRBUF_INIT;
4433 struct lock_file lock_file = LOCK_INIT;
4434 int fd;
4436 fd = repo_hold_locked_index(r, &lock_file, 0);
4437 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4438 if (0 <= fd)
4439 repo_update_index_if_able(r, &lock_file);
4440 rollback_lock_file(&lock_file);
4442 if (has_unstaged_changes(r, 1) ||
4443 has_uncommitted_changes(r, 1)) {
4444 struct child_process stash = CHILD_PROCESS_INIT;
4445 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4446 struct object_id oid;
4448 strvec_pushl(&stash.args,
4449 "stash", "create", "autostash", NULL);
4450 stash.git_cmd = 1;
4451 stash.no_stdin = 1;
4452 strbuf_reset(&buf);
4453 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4454 die(_("Cannot autostash"));
4455 strbuf_trim_trailing_newline(&buf);
4456 if (get_oid(buf.buf, &oid))
4457 die(_("Unexpected stash response: '%s'"),
4458 buf.buf);
4459 strbuf_reset(&buf);
4460 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4462 if (safe_create_leading_directories_const(path))
4463 die(_("Could not create directory for '%s'"),
4464 path);
4465 write_file(path, "%s", oid_to_hex(&oid));
4466 printf(_("Created autostash: %s\n"), buf.buf);
4467 if (reset_head(r, &ropts) < 0)
4468 die(_("could not reset --hard"));
4469 discard_index(r->index);
4470 if (repo_read_index(r) < 0)
4471 die(_("could not read index"));
4473 strbuf_release(&buf);
4476 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4478 struct child_process child = CHILD_PROCESS_INIT;
4479 int ret = 0;
4481 if (attempt_apply) {
4482 child.git_cmd = 1;
4483 child.no_stdout = 1;
4484 child.no_stderr = 1;
4485 strvec_push(&child.args, "stash");
4486 strvec_push(&child.args, "apply");
4487 strvec_push(&child.args, stash_oid);
4488 ret = run_command(&child);
4491 if (attempt_apply && !ret)
4492 fprintf(stderr, _("Applied autostash.\n"));
4493 else {
4494 struct child_process store = CHILD_PROCESS_INIT;
4496 store.git_cmd = 1;
4497 strvec_push(&store.args, "stash");
4498 strvec_push(&store.args, "store");
4499 strvec_push(&store.args, "-m");
4500 strvec_push(&store.args, "autostash");
4501 strvec_push(&store.args, "-q");
4502 strvec_push(&store.args, stash_oid);
4503 if (run_command(&store))
4504 ret = error(_("cannot store %s"), stash_oid);
4505 else
4506 fprintf(stderr,
4507 _("%s\n"
4508 "Your changes are safe in the stash.\n"
4509 "You can run \"git stash pop\" or"
4510 " \"git stash drop\" at any time.\n"),
4511 attempt_apply ?
4512 _("Applying autostash resulted in conflicts.") :
4513 _("Autostash exists; creating a new stash entry."));
4516 return ret;
4519 static int apply_save_autostash(const char *path, int attempt_apply)
4521 struct strbuf stash_oid = STRBUF_INIT;
4522 int ret = 0;
4524 if (!read_oneliner(&stash_oid, path,
4525 READ_ONELINER_SKIP_IF_EMPTY)) {
4526 strbuf_release(&stash_oid);
4527 return 0;
4529 strbuf_trim(&stash_oid);
4531 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4533 unlink(path);
4534 strbuf_release(&stash_oid);
4535 return ret;
4538 int save_autostash(const char *path)
4540 return apply_save_autostash(path, 0);
4543 int apply_autostash(const char *path)
4545 return apply_save_autostash(path, 1);
4548 int apply_autostash_oid(const char *stash_oid)
4550 return apply_save_autostash_oid(stash_oid, 1);
4553 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4554 const char *onto_name, const struct object_id *onto,
4555 const struct object_id *orig_head)
4557 struct reset_head_opts ropts = {
4558 .oid = onto,
4559 .orig_head = orig_head,
4560 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4561 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4562 .head_msg = reflog_message(opts, "start", "checkout %s",
4563 onto_name),
4564 .default_reflog_action = sequencer_reflog_action(opts)
4566 if (reset_head(r, &ropts)) {
4567 apply_autostash(rebase_path_autostash());
4568 sequencer_remove_state(opts);
4569 return error(_("could not detach HEAD"));
4572 return 0;
4575 static int stopped_at_head(struct repository *r)
4577 struct object_id head;
4578 struct commit *commit;
4579 struct commit_message message;
4581 if (get_oid("HEAD", &head) ||
4582 !(commit = lookup_commit(r, &head)) ||
4583 parse_commit(commit) || get_message(commit, &message))
4584 fprintf(stderr, _("Stopped at HEAD\n"));
4585 else {
4586 fprintf(stderr, _("Stopped at %s\n"), message.label);
4587 free_message(commit, &message);
4589 return 0;
4593 static int reread_todo_if_changed(struct repository *r,
4594 struct todo_list *todo_list,
4595 struct replay_opts *opts)
4597 int offset;
4598 struct strbuf buf = STRBUF_INIT;
4600 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4601 return -1;
4602 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4603 if (buf.len != todo_list->buf.len - offset ||
4604 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4605 /* Reread the todo file if it has changed. */
4606 todo_list_release(todo_list);
4607 if (read_populate_todo(r, todo_list, opts))
4608 return -1; /* message was printed */
4609 /* `current` will be incremented on return */
4610 todo_list->current = -1;
4612 strbuf_release(&buf);
4614 return 0;
4617 static const char rescheduled_advice[] =
4618 N_("Could not execute the todo command\n"
4619 "\n"
4620 " %.*s"
4621 "\n"
4622 "It has been rescheduled; To edit the command before continuing, please\n"
4623 "edit the todo list first:\n"
4624 "\n"
4625 " git rebase --edit-todo\n"
4626 " git rebase --continue\n");
4628 static int pick_commits(struct repository *r,
4629 struct todo_list *todo_list,
4630 struct replay_opts *opts)
4632 int res = 0, reschedule = 0;
4634 opts->reflog_message = sequencer_reflog_action(opts);
4635 if (opts->allow_ff)
4636 assert(!(opts->signoff || opts->no_commit ||
4637 opts->record_origin || should_edit(opts) ||
4638 opts->committer_date_is_author_date ||
4639 opts->ignore_date));
4640 if (read_and_refresh_cache(r, opts))
4641 return -1;
4643 while (todo_list->current < todo_list->nr) {
4644 struct todo_item *item = todo_list->items + todo_list->current;
4645 const char *arg = todo_item_get_arg(todo_list, item);
4646 int check_todo = 0;
4648 if (save_todo(todo_list, opts))
4649 return -1;
4650 if (is_rebase_i(opts)) {
4651 if (item->command != TODO_COMMENT) {
4652 FILE *f = fopen(rebase_path_msgnum(), "w");
4654 todo_list->done_nr++;
4656 if (f) {
4657 fprintf(f, "%d\n", todo_list->done_nr);
4658 fclose(f);
4660 if (!opts->quiet)
4661 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4662 todo_list->done_nr,
4663 todo_list->total_nr,
4664 opts->verbose ? "\n" : "\r");
4666 unlink(rebase_path_message());
4667 unlink(rebase_path_author_script());
4668 unlink(rebase_path_stopped_sha());
4669 unlink(rebase_path_amend());
4670 unlink(git_path_merge_head(r));
4671 unlink(git_path_auto_merge(r));
4672 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4674 if (item->command == TODO_BREAK) {
4675 if (!opts->verbose)
4676 term_clear_line();
4677 return stopped_at_head(r);
4680 if (item->command <= TODO_SQUASH) {
4681 if (is_rebase_i(opts))
4682 opts->reflog_message = reflog_message(opts,
4683 command_to_string(item->command), NULL);
4685 res = do_pick_commit(r, item, opts,
4686 is_final_fixup(todo_list),
4687 &check_todo);
4688 if (is_rebase_i(opts) && res < 0) {
4689 /* Reschedule */
4690 advise(_(rescheduled_advice),
4691 get_item_line_length(todo_list,
4692 todo_list->current),
4693 get_item_line(todo_list,
4694 todo_list->current));
4695 todo_list->current--;
4696 if (save_todo(todo_list, opts))
4697 return -1;
4699 if (item->command == TODO_EDIT) {
4700 struct commit *commit = item->commit;
4701 if (!res) {
4702 if (!opts->verbose)
4703 term_clear_line();
4704 fprintf(stderr,
4705 _("Stopped at %s... %.*s\n"),
4706 short_commit_name(commit),
4707 item->arg_len, arg);
4709 return error_with_patch(r, commit,
4710 arg, item->arg_len, opts, res, !res);
4712 if (is_rebase_i(opts) && !res)
4713 record_in_rewritten(&item->commit->object.oid,
4714 peek_command(todo_list, 1));
4715 if (res && is_fixup(item->command)) {
4716 if (res == 1)
4717 intend_to_amend();
4718 return error_failed_squash(r, item->commit, opts,
4719 item->arg_len, arg);
4720 } else if (res && is_rebase_i(opts) && item->commit) {
4721 int to_amend = 0;
4722 struct object_id oid;
4725 * If we are rewording and have either
4726 * fast-forwarded already, or are about to
4727 * create a new root commit, we want to amend,
4728 * otherwise we do not.
4730 if (item->command == TODO_REWORD &&
4731 !get_oid("HEAD", &oid) &&
4732 (oideq(&item->commit->object.oid, &oid) ||
4733 (opts->have_squash_onto &&
4734 oideq(&opts->squash_onto, &oid))))
4735 to_amend = 1;
4737 return res | error_with_patch(r, item->commit,
4738 arg, item->arg_len, opts,
4739 res, to_amend);
4741 } else if (item->command == TODO_EXEC) {
4742 char *end_of_arg = (char *)(arg + item->arg_len);
4743 int saved = *end_of_arg;
4745 if (!opts->verbose)
4746 term_clear_line();
4747 *end_of_arg = '\0';
4748 res = do_exec(r, arg);
4749 *end_of_arg = saved;
4751 if (res) {
4752 if (opts->reschedule_failed_exec)
4753 reschedule = 1;
4755 check_todo = 1;
4756 } else if (item->command == TODO_LABEL) {
4757 if ((res = do_label(r, arg, item->arg_len)))
4758 reschedule = 1;
4759 } else if (item->command == TODO_RESET) {
4760 if ((res = do_reset(r, arg, item->arg_len, opts)))
4761 reschedule = 1;
4762 } else if (item->command == TODO_MERGE) {
4763 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4764 item->flags, &check_todo, opts)) < 0)
4765 reschedule = 1;
4766 else if (item->commit)
4767 record_in_rewritten(&item->commit->object.oid,
4768 peek_command(todo_list, 1));
4769 if (res > 0)
4770 /* failed with merge conflicts */
4771 return error_with_patch(r, item->commit,
4772 arg, item->arg_len,
4773 opts, res, 0);
4774 } else if (item->command == TODO_UPDATE_REF) {
4775 struct strbuf ref = STRBUF_INIT;
4776 strbuf_add(&ref, arg, item->arg_len);
4777 if ((res = do_update_ref(r, ref.buf)))
4778 reschedule = 1;
4779 strbuf_release(&ref);
4780 } else if (!is_noop(item->command))
4781 return error(_("unknown command %d"), item->command);
4783 if (reschedule) {
4784 advise(_(rescheduled_advice),
4785 get_item_line_length(todo_list,
4786 todo_list->current),
4787 get_item_line(todo_list, todo_list->current));
4788 todo_list->current--;
4789 if (save_todo(todo_list, opts))
4790 return -1;
4791 if (item->commit)
4792 return error_with_patch(r,
4793 item->commit,
4794 arg, item->arg_len,
4795 opts, res, 0);
4796 } else if (is_rebase_i(opts) && check_todo && !res &&
4797 reread_todo_if_changed(r, todo_list, opts)) {
4798 return -1;
4801 todo_list->current++;
4802 if (res)
4803 return res;
4806 if (is_rebase_i(opts)) {
4807 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4808 struct stat st;
4810 /* Stopped in the middle, as planned? */
4811 if (todo_list->current < todo_list->nr)
4812 return 0;
4814 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4815 starts_with(head_ref.buf, "refs/")) {
4816 const char *msg;
4817 struct object_id head, orig;
4818 int res;
4820 if (get_oid("HEAD", &head)) {
4821 res = error(_("cannot read HEAD"));
4822 cleanup_head_ref:
4823 strbuf_release(&head_ref);
4824 strbuf_release(&buf);
4825 return res;
4827 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4828 get_oid_hex(buf.buf, &orig)) {
4829 res = error(_("could not read orig-head"));
4830 goto cleanup_head_ref;
4832 strbuf_reset(&buf);
4833 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4834 res = error(_("could not read 'onto'"));
4835 goto cleanup_head_ref;
4837 msg = reflog_message(opts, "finish", "%s onto %s",
4838 head_ref.buf, buf.buf);
4839 if (update_ref(msg, head_ref.buf, &head, &orig,
4840 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4841 res = error(_("could not update %s"),
4842 head_ref.buf);
4843 goto cleanup_head_ref;
4845 msg = reflog_message(opts, "finish", "returning to %s",
4846 head_ref.buf);
4847 if (create_symref("HEAD", head_ref.buf, msg)) {
4848 res = error(_("could not update HEAD to %s"),
4849 head_ref.buf);
4850 goto cleanup_head_ref;
4852 strbuf_reset(&buf);
4855 if (opts->verbose) {
4856 struct rev_info log_tree_opt;
4857 struct object_id orig, head;
4859 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4860 repo_init_revisions(r, &log_tree_opt, NULL);
4861 log_tree_opt.diff = 1;
4862 log_tree_opt.diffopt.output_format =
4863 DIFF_FORMAT_DIFFSTAT;
4864 log_tree_opt.disable_stdin = 1;
4866 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4867 !get_oid(buf.buf, &orig) &&
4868 !get_oid("HEAD", &head)) {
4869 diff_tree_oid(&orig, &head, "",
4870 &log_tree_opt.diffopt);
4871 log_tree_diff_flush(&log_tree_opt);
4873 release_revisions(&log_tree_opt);
4875 flush_rewritten_pending();
4876 if (!stat(rebase_path_rewritten_list(), &st) &&
4877 st.st_size > 0) {
4878 struct child_process child = CHILD_PROCESS_INIT;
4879 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4881 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4882 child.git_cmd = 1;
4883 strvec_push(&child.args, "notes");
4884 strvec_push(&child.args, "copy");
4885 strvec_push(&child.args, "--for-rewrite=rebase");
4886 /* we don't care if this copying failed */
4887 run_command(&child);
4889 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4890 strvec_push(&hook_opt.args, "rebase");
4891 run_hooks_opt("post-rewrite", &hook_opt);
4893 apply_autostash(rebase_path_autostash());
4895 if (!opts->quiet) {
4896 if (!opts->verbose)
4897 term_clear_line();
4898 fprintf(stderr,
4899 _("Successfully rebased and updated %s.\n"),
4900 head_ref.buf);
4903 strbuf_release(&buf);
4904 strbuf_release(&head_ref);
4906 if (do_update_refs(r, opts->quiet))
4907 return -1;
4911 * Sequence of picks finished successfully; cleanup by
4912 * removing the .git/sequencer directory
4914 return sequencer_remove_state(opts);
4917 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4919 struct child_process cmd = CHILD_PROCESS_INIT;
4921 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4922 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4923 return error(_("no cherry-pick or revert in progress"));
4925 cmd.git_cmd = 1;
4926 strvec_push(&cmd.args, "commit");
4929 * continue_single_pick() handles the case of recovering from a
4930 * conflict. should_edit() doesn't handle that case; for a conflict,
4931 * we want to edit if the user asked for it, or if they didn't specify
4932 * and stdin is a tty.
4934 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4936 * Include --cleanup=strip as well because we don't want the
4937 * "# Conflicts:" messages.
4939 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4941 return run_command(&cmd);
4944 static int commit_staged_changes(struct repository *r,
4945 struct replay_opts *opts,
4946 struct todo_list *todo_list)
4948 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4949 unsigned int final_fixup = 0, is_clean;
4951 if (has_unstaged_changes(r, 1))
4952 return error(_("cannot rebase: You have unstaged changes."));
4954 is_clean = !has_uncommitted_changes(r, 0);
4956 if (file_exists(rebase_path_amend())) {
4957 struct strbuf rev = STRBUF_INIT;
4958 struct object_id head, to_amend;
4960 if (get_oid("HEAD", &head))
4961 return error(_("cannot amend non-existing commit"));
4962 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4963 return error(_("invalid file: '%s'"), rebase_path_amend());
4964 if (get_oid_hex(rev.buf, &to_amend))
4965 return error(_("invalid contents: '%s'"),
4966 rebase_path_amend());
4967 if (!is_clean && !oideq(&head, &to_amend))
4968 return error(_("\nYou have uncommitted changes in your "
4969 "working tree. Please, commit them\n"
4970 "first and then run 'git rebase "
4971 "--continue' again."));
4973 * When skipping a failed fixup/squash, we need to edit the
4974 * commit message, the current fixup list and count, and if it
4975 * was the last fixup/squash in the chain, we need to clean up
4976 * the commit message and if there was a squash, let the user
4977 * edit it.
4979 if (!is_clean || !opts->current_fixup_count)
4980 ; /* this is not the final fixup */
4981 else if (!oideq(&head, &to_amend) ||
4982 !file_exists(rebase_path_stopped_sha())) {
4983 /* was a final fixup or squash done manually? */
4984 if (!is_fixup(peek_command(todo_list, 0))) {
4985 unlink(rebase_path_fixup_msg());
4986 unlink(rebase_path_squash_msg());
4987 unlink(rebase_path_current_fixups());
4988 strbuf_reset(&opts->current_fixups);
4989 opts->current_fixup_count = 0;
4991 } else {
4992 /* we are in a fixup/squash chain */
4993 const char *p = opts->current_fixups.buf;
4994 int len = opts->current_fixups.len;
4996 opts->current_fixup_count--;
4997 if (!len)
4998 BUG("Incorrect current_fixups:\n%s", p);
4999 while (len && p[len - 1] != '\n')
5000 len--;
5001 strbuf_setlen(&opts->current_fixups, len);
5002 if (write_message(p, len, rebase_path_current_fixups(),
5003 0) < 0)
5004 return error(_("could not write file: '%s'"),
5005 rebase_path_current_fixups());
5008 * If a fixup/squash in a fixup/squash chain failed, the
5009 * commit message is already correct, no need to commit
5010 * it again.
5012 * Only if it is the final command in the fixup/squash
5013 * chain, and only if the chain is longer than a single
5014 * fixup/squash command (which was just skipped), do we
5015 * actually need to re-commit with a cleaned up commit
5016 * message.
5018 if (opts->current_fixup_count > 0 &&
5019 !is_fixup(peek_command(todo_list, 0))) {
5020 final_fixup = 1;
5022 * If there was not a single "squash" in the
5023 * chain, we only need to clean up the commit
5024 * message, no need to bother the user with
5025 * opening the commit message in the editor.
5027 if (!starts_with(p, "squash ") &&
5028 !strstr(p, "\nsquash "))
5029 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5030 } else if (is_fixup(peek_command(todo_list, 0))) {
5032 * We need to update the squash message to skip
5033 * the latest commit message.
5035 struct commit *commit;
5036 const char *path = rebase_path_squash_msg();
5037 const char *encoding = get_commit_output_encoding();
5039 if (parse_head(r, &commit) ||
5040 !(p = logmsg_reencode(commit, NULL, encoding)) ||
5041 write_message(p, strlen(p), path, 0)) {
5042 unuse_commit_buffer(commit, p);
5043 return error(_("could not write file: "
5044 "'%s'"), path);
5046 unuse_commit_buffer(commit, p);
5050 strbuf_release(&rev);
5051 flags |= AMEND_MSG;
5054 if (is_clean) {
5055 if (refs_ref_exists(get_main_ref_store(r),
5056 "CHERRY_PICK_HEAD") &&
5057 refs_delete_ref(get_main_ref_store(r), "",
5058 "CHERRY_PICK_HEAD", NULL, 0))
5059 return error(_("could not remove CHERRY_PICK_HEAD"));
5060 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5061 return error_errno(_("could not remove '%s'"),
5062 git_path_merge_msg(r));
5063 if (!final_fixup)
5064 return 0;
5067 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5068 opts, flags))
5069 return error(_("could not commit staged changes."));
5070 unlink(rebase_path_amend());
5071 unlink(git_path_merge_head(r));
5072 unlink(git_path_auto_merge(r));
5073 if (final_fixup) {
5074 unlink(rebase_path_fixup_msg());
5075 unlink(rebase_path_squash_msg());
5077 if (opts->current_fixup_count > 0) {
5079 * Whether final fixup or not, we just cleaned up the commit
5080 * message...
5082 unlink(rebase_path_current_fixups());
5083 strbuf_reset(&opts->current_fixups);
5084 opts->current_fixup_count = 0;
5086 return 0;
5089 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5091 struct todo_list todo_list = TODO_LIST_INIT;
5092 int res;
5094 if (read_and_refresh_cache(r, opts))
5095 return -1;
5097 if (read_populate_opts(opts))
5098 return -1;
5099 if (is_rebase_i(opts)) {
5100 if ((res = read_populate_todo(r, &todo_list, opts)))
5101 goto release_todo_list;
5103 if (file_exists(rebase_path_dropped())) {
5104 if ((res = todo_list_check_against_backup(r, &todo_list)))
5105 goto release_todo_list;
5107 unlink(rebase_path_dropped());
5110 opts->reflog_message = reflog_message(opts, "continue", NULL);
5111 if (commit_staged_changes(r, opts, &todo_list)) {
5112 res = -1;
5113 goto release_todo_list;
5115 } else if (!file_exists(get_todo_path(opts)))
5116 return continue_single_pick(r, opts);
5117 else if ((res = read_populate_todo(r, &todo_list, opts)))
5118 goto release_todo_list;
5120 if (!is_rebase_i(opts)) {
5121 /* Verify that the conflict has been resolved */
5122 if (refs_ref_exists(get_main_ref_store(r),
5123 "CHERRY_PICK_HEAD") ||
5124 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5125 res = continue_single_pick(r, opts);
5126 if (res)
5127 goto release_todo_list;
5129 if (index_differs_from(r, "HEAD", NULL, 0)) {
5130 res = error_dirty_index(r, opts);
5131 goto release_todo_list;
5133 todo_list.current++;
5134 } else if (file_exists(rebase_path_stopped_sha())) {
5135 struct strbuf buf = STRBUF_INIT;
5136 struct object_id oid;
5138 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5139 READ_ONELINER_SKIP_IF_EMPTY) &&
5140 !get_oid_hex(buf.buf, &oid))
5141 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5142 strbuf_release(&buf);
5145 res = pick_commits(r, &todo_list, opts);
5146 release_todo_list:
5147 todo_list_release(&todo_list);
5148 return res;
5151 static int single_pick(struct repository *r,
5152 struct commit *cmit,
5153 struct replay_opts *opts)
5155 int check_todo;
5156 struct todo_item item;
5158 item.command = opts->action == REPLAY_PICK ?
5159 TODO_PICK : TODO_REVERT;
5160 item.commit = cmit;
5162 opts->reflog_message = sequencer_reflog_action(opts);
5163 return do_pick_commit(r, &item, opts, 0, &check_todo);
5166 int sequencer_pick_revisions(struct repository *r,
5167 struct replay_opts *opts)
5169 struct todo_list todo_list = TODO_LIST_INIT;
5170 struct object_id oid;
5171 int i, res;
5173 assert(opts->revs);
5174 if (read_and_refresh_cache(r, opts))
5175 return -1;
5177 for (i = 0; i < opts->revs->pending.nr; i++) {
5178 struct object_id oid;
5179 const char *name = opts->revs->pending.objects[i].name;
5181 /* This happens when using --stdin. */
5182 if (!strlen(name))
5183 continue;
5185 if (!get_oid(name, &oid)) {
5186 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5187 enum object_type type = oid_object_info(r,
5188 &oid,
5189 NULL);
5190 return error(_("%s: can't cherry-pick a %s"),
5191 name, type_name(type));
5193 } else
5194 return error(_("%s: bad revision"), name);
5198 * If we were called as "git cherry-pick <commit>", just
5199 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5200 * REVERT_HEAD, and don't touch the sequencer state.
5201 * This means it is possible to cherry-pick in the middle
5202 * of a cherry-pick sequence.
5204 if (opts->revs->cmdline.nr == 1 &&
5205 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5206 opts->revs->no_walk &&
5207 !opts->revs->cmdline.rev->flags) {
5208 struct commit *cmit;
5209 if (prepare_revision_walk(opts->revs))
5210 return error(_("revision walk setup failed"));
5211 cmit = get_revision(opts->revs);
5212 if (!cmit)
5213 return error(_("empty commit set passed"));
5214 if (get_revision(opts->revs))
5215 BUG("unexpected extra commit from walk");
5216 return single_pick(r, cmit, opts);
5220 * Start a new cherry-pick/ revert sequence; but
5221 * first, make sure that an existing one isn't in
5222 * progress
5225 if (walk_revs_populate_todo(&todo_list, opts) ||
5226 create_seq_dir(r) < 0)
5227 return -1;
5228 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
5229 return error(_("can't revert as initial commit"));
5230 if (save_head(oid_to_hex(&oid)))
5231 return -1;
5232 if (save_opts(opts))
5233 return -1;
5234 update_abort_safety_file();
5235 res = pick_commits(r, &todo_list, opts);
5236 todo_list_release(&todo_list);
5237 return res;
5240 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5242 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5243 struct strbuf sob = STRBUF_INIT;
5244 int has_footer;
5246 strbuf_addstr(&sob, sign_off_header);
5247 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5248 strbuf_addch(&sob, '\n');
5250 if (!ignore_footer)
5251 strbuf_complete_line(msgbuf);
5254 * If the whole message buffer is equal to the sob, pretend that we
5255 * found a conforming footer with a matching sob
5257 if (msgbuf->len - ignore_footer == sob.len &&
5258 !strncmp(msgbuf->buf, sob.buf, sob.len))
5259 has_footer = 3;
5260 else
5261 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5263 if (!has_footer) {
5264 const char *append_newlines = NULL;
5265 size_t len = msgbuf->len - ignore_footer;
5267 if (!len) {
5269 * The buffer is completely empty. Leave foom for
5270 * the title and body to be filled in by the user.
5272 append_newlines = "\n\n";
5273 } else if (len == 1) {
5275 * Buffer contains a single newline. Add another
5276 * so that we leave room for the title and body.
5278 append_newlines = "\n";
5279 } else if (msgbuf->buf[len - 2] != '\n') {
5281 * Buffer ends with a single newline. Add another
5282 * so that there is an empty line between the message
5283 * body and the sob.
5285 append_newlines = "\n";
5286 } /* else, the buffer already ends with two newlines. */
5288 if (append_newlines)
5289 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5290 append_newlines, strlen(append_newlines));
5293 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5294 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5295 sob.buf, sob.len);
5297 strbuf_release(&sob);
5300 struct labels_entry {
5301 struct hashmap_entry entry;
5302 char label[FLEX_ARRAY];
5305 static int labels_cmp(const void *fndata UNUSED,
5306 const struct hashmap_entry *eptr,
5307 const struct hashmap_entry *entry_or_key, const void *key)
5309 const struct labels_entry *a, *b;
5311 a = container_of(eptr, const struct labels_entry, entry);
5312 b = container_of(entry_or_key, const struct labels_entry, entry);
5314 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5317 struct string_entry {
5318 struct oidmap_entry entry;
5319 char string[FLEX_ARRAY];
5322 struct label_state {
5323 struct oidmap commit2label;
5324 struct hashmap labels;
5325 struct strbuf buf;
5328 static const char *label_oid(struct object_id *oid, const char *label,
5329 struct label_state *state)
5331 struct labels_entry *labels_entry;
5332 struct string_entry *string_entry;
5333 struct object_id dummy;
5334 int i;
5336 string_entry = oidmap_get(&state->commit2label, oid);
5337 if (string_entry)
5338 return string_entry->string;
5341 * For "uninteresting" commits, i.e. commits that are not to be
5342 * rebased, and which can therefore not be labeled, we use a unique
5343 * abbreviation of the commit name. This is slightly more complicated
5344 * than calling find_unique_abbrev() because we also need to make
5345 * sure that the abbreviation does not conflict with any other
5346 * label.
5348 * We disallow "interesting" commits to be labeled by a string that
5349 * is a valid full-length hash, to ensure that we always can find an
5350 * abbreviation for any uninteresting commit's names that does not
5351 * clash with any other label.
5353 strbuf_reset(&state->buf);
5354 if (!label) {
5355 char *p;
5357 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5358 label = p = state->buf.buf;
5360 find_unique_abbrev_r(p, oid, default_abbrev);
5363 * We may need to extend the abbreviated hash so that there is
5364 * no conflicting label.
5366 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5367 size_t i = strlen(p) + 1;
5369 oid_to_hex_r(p, oid);
5370 for (; i < the_hash_algo->hexsz; i++) {
5371 char save = p[i];
5372 p[i] = '\0';
5373 if (!hashmap_get_from_hash(&state->labels,
5374 strihash(p), p))
5375 break;
5376 p[i] = save;
5379 } else {
5380 struct strbuf *buf = &state->buf;
5383 * Sanitize labels by replacing non-alpha-numeric characters
5384 * (including white-space ones) by dashes, as they might be
5385 * illegal in file names (and hence in ref names).
5387 * Note that we retain non-ASCII UTF-8 characters (identified
5388 * via the most significant bit). They should be all acceptable
5389 * in file names. We do not validate the UTF-8 here, that's not
5390 * the job of this function.
5392 for (; *label; label++)
5393 if ((*label & 0x80) || isalnum(*label))
5394 strbuf_addch(buf, *label);
5395 /* avoid leading dash and double-dashes */
5396 else if (buf->len && buf->buf[buf->len - 1] != '-')
5397 strbuf_addch(buf, '-');
5398 if (!buf->len) {
5399 strbuf_addstr(buf, "rev-");
5400 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5402 label = buf->buf;
5404 if ((buf->len == the_hash_algo->hexsz &&
5405 !get_oid_hex(label, &dummy)) ||
5406 (buf->len == 1 && *label == '#') ||
5407 hashmap_get_from_hash(&state->labels,
5408 strihash(label), label)) {
5410 * If the label already exists, or if the label is a
5411 * valid full OID, or the label is a '#' (which we use
5412 * as a separator between merge heads and oneline), we
5413 * append a dash and a number to make it unique.
5415 size_t len = buf->len;
5417 for (i = 2; ; i++) {
5418 strbuf_setlen(buf, len);
5419 strbuf_addf(buf, "-%d", i);
5420 if (!hashmap_get_from_hash(&state->labels,
5421 strihash(buf->buf),
5422 buf->buf))
5423 break;
5426 label = buf->buf;
5430 FLEX_ALLOC_STR(labels_entry, label, label);
5431 hashmap_entry_init(&labels_entry->entry, strihash(label));
5432 hashmap_add(&state->labels, &labels_entry->entry);
5434 FLEX_ALLOC_STR(string_entry, string, label);
5435 oidcpy(&string_entry->entry.oid, oid);
5436 oidmap_put(&state->commit2label, string_entry);
5438 return string_entry->string;
5441 static int make_script_with_merges(struct pretty_print_context *pp,
5442 struct rev_info *revs, struct strbuf *out,
5443 unsigned flags)
5445 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5446 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5447 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5448 int skipped_commit = 0;
5449 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5450 struct strbuf label = STRBUF_INIT;
5451 struct commit_list *commits = NULL, **tail = &commits, *iter;
5452 struct commit_list *tips = NULL, **tips_tail = &tips;
5453 struct commit *commit;
5454 struct oidmap commit2todo = OIDMAP_INIT;
5455 struct string_entry *entry;
5456 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5457 shown = OIDSET_INIT;
5458 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5460 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5461 const char *cmd_pick = abbr ? "p" : "pick",
5462 *cmd_label = abbr ? "l" : "label",
5463 *cmd_reset = abbr ? "t" : "reset",
5464 *cmd_merge = abbr ? "m" : "merge";
5466 oidmap_init(&commit2todo, 0);
5467 oidmap_init(&state.commit2label, 0);
5468 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5469 strbuf_init(&state.buf, 32);
5471 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5472 struct labels_entry *onto_label_entry;
5473 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5474 FLEX_ALLOC_STR(entry, string, "onto");
5475 oidcpy(&entry->entry.oid, oid);
5476 oidmap_put(&state.commit2label, entry);
5478 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5479 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5480 hashmap_add(&state.labels, &onto_label_entry->entry);
5484 * First phase:
5485 * - get onelines for all commits
5486 * - gather all branch tips (i.e. 2nd or later parents of merges)
5487 * - label all branch tips
5489 while ((commit = get_revision(revs))) {
5490 struct commit_list *to_merge;
5491 const char *p1, *p2;
5492 struct object_id *oid;
5493 int is_empty;
5495 tail = &commit_list_insert(commit, tail)->next;
5496 oidset_insert(&interesting, &commit->object.oid);
5498 is_empty = is_original_commit_empty(commit);
5499 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5500 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5501 warning(_("skipped previously applied commit %s"),
5502 short_commit_name(commit));
5503 skipped_commit = 1;
5504 continue;
5506 if (is_empty && !keep_empty)
5507 continue;
5509 strbuf_reset(&oneline);
5510 pretty_print_commit(pp, commit, &oneline);
5512 to_merge = commit->parents ? commit->parents->next : NULL;
5513 if (!to_merge) {
5514 /* non-merge commit: easy case */
5515 strbuf_reset(&buf);
5516 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5517 oid_to_hex(&commit->object.oid),
5518 oneline.buf);
5519 if (is_empty)
5520 strbuf_addf(&buf, " %c empty",
5521 comment_line_char);
5523 FLEX_ALLOC_STR(entry, string, buf.buf);
5524 oidcpy(&entry->entry.oid, &commit->object.oid);
5525 oidmap_put(&commit2todo, entry);
5527 continue;
5530 /* Create a label */
5531 strbuf_reset(&label);
5532 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5533 (p1 = strchr(p1, '\'')) &&
5534 (p2 = strchr(++p1, '\'')))
5535 strbuf_add(&label, p1, p2 - p1);
5536 else if (skip_prefix(oneline.buf, "Merge pull request ",
5537 &p1) &&
5538 (p1 = strstr(p1, " from ")))
5539 strbuf_addstr(&label, p1 + strlen(" from "));
5540 else
5541 strbuf_addbuf(&label, &oneline);
5543 strbuf_reset(&buf);
5544 strbuf_addf(&buf, "%s -C %s",
5545 cmd_merge, oid_to_hex(&commit->object.oid));
5547 /* label the tips of merged branches */
5548 for (; to_merge; to_merge = to_merge->next) {
5549 oid = &to_merge->item->object.oid;
5550 strbuf_addch(&buf, ' ');
5552 if (!oidset_contains(&interesting, oid)) {
5553 strbuf_addstr(&buf, label_oid(oid, NULL,
5554 &state));
5555 continue;
5558 tips_tail = &commit_list_insert(to_merge->item,
5559 tips_tail)->next;
5561 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5563 strbuf_addf(&buf, " # %s", oneline.buf);
5565 FLEX_ALLOC_STR(entry, string, buf.buf);
5566 oidcpy(&entry->entry.oid, &commit->object.oid);
5567 oidmap_put(&commit2todo, entry);
5569 if (skipped_commit)
5570 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5571 _("use --reapply-cherry-picks to include skipped commits"));
5574 * Second phase:
5575 * - label branch points
5576 * - add HEAD to the branch tips
5578 for (iter = commits; iter; iter = iter->next) {
5579 struct commit_list *parent = iter->item->parents;
5580 for (; parent; parent = parent->next) {
5581 struct object_id *oid = &parent->item->object.oid;
5582 if (!oidset_contains(&interesting, oid))
5583 continue;
5584 if (oidset_insert(&child_seen, oid))
5585 label_oid(oid, "branch-point", &state);
5588 /* Add HEAD as implicit "tip of branch" */
5589 if (!iter->next)
5590 tips_tail = &commit_list_insert(iter->item,
5591 tips_tail)->next;
5595 * Third phase: output the todo list. This is a bit tricky, as we
5596 * want to avoid jumping back and forth between revisions. To
5597 * accomplish that goal, we walk backwards from the branch tips,
5598 * gathering commits not yet shown, reversing the list on the fly,
5599 * then outputting that list (labeling revisions as needed).
5601 strbuf_addf(out, "%s onto\n", cmd_label);
5602 for (iter = tips; iter; iter = iter->next) {
5603 struct commit_list *list = NULL, *iter2;
5605 commit = iter->item;
5606 if (oidset_contains(&shown, &commit->object.oid))
5607 continue;
5608 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5610 if (entry)
5611 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5612 else
5613 strbuf_addch(out, '\n');
5615 while (oidset_contains(&interesting, &commit->object.oid) &&
5616 !oidset_contains(&shown, &commit->object.oid)) {
5617 commit_list_insert(commit, &list);
5618 if (!commit->parents) {
5619 commit = NULL;
5620 break;
5622 commit = commit->parents->item;
5625 if (!commit)
5626 strbuf_addf(out, "%s %s\n", cmd_reset,
5627 rebase_cousins || root_with_onto ?
5628 "onto" : "[new root]");
5629 else {
5630 const char *to = NULL;
5632 entry = oidmap_get(&state.commit2label,
5633 &commit->object.oid);
5634 if (entry)
5635 to = entry->string;
5636 else if (!rebase_cousins)
5637 to = label_oid(&commit->object.oid, NULL,
5638 &state);
5640 if (!to || !strcmp(to, "onto"))
5641 strbuf_addf(out, "%s onto\n", cmd_reset);
5642 else {
5643 strbuf_reset(&oneline);
5644 pretty_print_commit(pp, commit, &oneline);
5645 strbuf_addf(out, "%s %s # %s\n",
5646 cmd_reset, to, oneline.buf);
5650 for (iter2 = list; iter2; iter2 = iter2->next) {
5651 struct object_id *oid = &iter2->item->object.oid;
5652 entry = oidmap_get(&commit2todo, oid);
5653 /* only show if not already upstream */
5654 if (entry)
5655 strbuf_addf(out, "%s\n", entry->string);
5656 entry = oidmap_get(&state.commit2label, oid);
5657 if (entry)
5658 strbuf_addf(out, "%s %s\n",
5659 cmd_label, entry->string);
5660 oidset_insert(&shown, oid);
5663 free_commit_list(list);
5666 free_commit_list(commits);
5667 free_commit_list(tips);
5669 strbuf_release(&label);
5670 strbuf_release(&oneline);
5671 strbuf_release(&buf);
5673 oidmap_free(&commit2todo, 1);
5674 oidmap_free(&state.commit2label, 1);
5675 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5676 strbuf_release(&state.buf);
5678 return 0;
5681 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5682 const char **argv, unsigned flags)
5684 char *format = NULL;
5685 struct pretty_print_context pp = {0};
5686 struct rev_info revs;
5687 struct commit *commit;
5688 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5689 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5690 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5691 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5692 int skipped_commit = 0;
5693 int ret = 0;
5695 repo_init_revisions(r, &revs, NULL);
5696 revs.verbose_header = 1;
5697 if (!rebase_merges)
5698 revs.max_parents = 1;
5699 revs.cherry_mark = !reapply_cherry_picks;
5700 revs.limited = 1;
5701 revs.reverse = 1;
5702 revs.right_only = 1;
5703 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5704 revs.topo_order = 1;
5706 revs.pretty_given = 1;
5707 git_config_get_string("rebase.instructionFormat", &format);
5708 if (!format || !*format) {
5709 free(format);
5710 format = xstrdup("%s");
5712 get_commit_format(format, &revs);
5713 free(format);
5714 pp.fmt = revs.commit_format;
5715 pp.output_encoding = get_log_output_encoding();
5717 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5718 ret = error(_("make_script: unhandled options"));
5719 goto cleanup;
5722 if (prepare_revision_walk(&revs) < 0) {
5723 ret = error(_("make_script: error preparing revisions"));
5724 goto cleanup;
5727 if (rebase_merges) {
5728 ret = make_script_with_merges(&pp, &revs, out, flags);
5729 goto cleanup;
5732 while ((commit = get_revision(&revs))) {
5733 int is_empty = is_original_commit_empty(commit);
5735 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5736 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5737 warning(_("skipped previously applied commit %s"),
5738 short_commit_name(commit));
5739 skipped_commit = 1;
5740 continue;
5742 if (is_empty && !keep_empty)
5743 continue;
5744 strbuf_addf(out, "%s %s ", insn,
5745 oid_to_hex(&commit->object.oid));
5746 pretty_print_commit(&pp, commit, out);
5747 if (is_empty)
5748 strbuf_addf(out, " %c empty", comment_line_char);
5749 strbuf_addch(out, '\n');
5751 if (skipped_commit)
5752 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5753 _("use --reapply-cherry-picks to include skipped commits"));
5754 cleanup:
5755 release_revisions(&revs);
5756 return ret;
5760 * Add commands after pick and (series of) squash/fixup commands
5761 * in the todo list.
5763 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5764 struct string_list *commands)
5766 struct strbuf *buf = &todo_list->buf;
5767 size_t base_offset = buf->len;
5768 int i, insert, nr = 0, alloc = 0;
5769 struct todo_item *items = NULL, *base_items = NULL;
5771 CALLOC_ARRAY(base_items, commands->nr);
5772 for (i = 0; i < commands->nr; i++) {
5773 size_t command_len = strlen(commands->items[i].string);
5775 strbuf_addstr(buf, commands->items[i].string);
5776 strbuf_addch(buf, '\n');
5778 base_items[i].command = TODO_EXEC;
5779 base_items[i].offset_in_buf = base_offset;
5780 base_items[i].arg_offset = base_offset;
5781 base_items[i].arg_len = command_len;
5783 base_offset += command_len + 1;
5787 * Insert <commands> after every pick. Here, fixup/squash chains
5788 * are considered part of the pick, so we insert the commands *after*
5789 * those chains if there are any.
5791 * As we insert the exec commands immediately after rearranging
5792 * any fixups and before the user edits the list, a fixup chain
5793 * can never contain comments (any comments are empty picks that
5794 * have been commented out because the user did not specify
5795 * --keep-empty). So, it is safe to insert an exec command
5796 * without looking at the command following a comment.
5798 insert = 0;
5799 for (i = 0; i < todo_list->nr; i++) {
5800 enum todo_command command = todo_list->items[i].command;
5801 if (insert && !is_fixup(command)) {
5802 ALLOC_GROW(items, nr + commands->nr, alloc);
5803 COPY_ARRAY(items + nr, base_items, commands->nr);
5804 nr += commands->nr;
5806 insert = 0;
5809 ALLOC_GROW(items, nr + 1, alloc);
5810 items[nr++] = todo_list->items[i];
5812 if (command == TODO_PICK || command == TODO_MERGE)
5813 insert = 1;
5816 /* insert or append final <commands> */
5817 if (insert) {
5818 ALLOC_GROW(items, nr + commands->nr, alloc);
5819 COPY_ARRAY(items + nr, base_items, commands->nr);
5820 nr += commands->nr;
5823 free(base_items);
5824 FREE_AND_NULL(todo_list->items);
5825 todo_list->items = items;
5826 todo_list->nr = nr;
5827 todo_list->alloc = alloc;
5830 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5831 struct strbuf *buf, int num, unsigned flags)
5833 struct todo_item *item;
5834 int i, max = todo_list->nr;
5836 if (num > 0 && num < max)
5837 max = num;
5839 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5840 char cmd;
5842 /* if the item is not a command write it and continue */
5843 if (item->command >= TODO_COMMENT) {
5844 strbuf_addf(buf, "%.*s\n", item->arg_len,
5845 todo_item_get_arg(todo_list, item));
5846 continue;
5849 /* add command to the buffer */
5850 cmd = command_to_char(item->command);
5851 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5852 strbuf_addch(buf, cmd);
5853 else
5854 strbuf_addstr(buf, command_to_string(item->command));
5856 /* add commit id */
5857 if (item->commit) {
5858 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5859 short_commit_name(item->commit) :
5860 oid_to_hex(&item->commit->object.oid);
5862 if (item->command == TODO_FIXUP) {
5863 if (item->flags & TODO_EDIT_FIXUP_MSG)
5864 strbuf_addstr(buf, " -c");
5865 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5866 strbuf_addstr(buf, " -C");
5870 if (item->command == TODO_MERGE) {
5871 if (item->flags & TODO_EDIT_MERGE_MSG)
5872 strbuf_addstr(buf, " -c");
5873 else
5874 strbuf_addstr(buf, " -C");
5877 strbuf_addf(buf, " %s", oid);
5880 /* add all the rest */
5881 if (!item->arg_len)
5882 strbuf_addch(buf, '\n');
5883 else
5884 strbuf_addf(buf, " %.*s\n", item->arg_len,
5885 todo_item_get_arg(todo_list, item));
5889 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5890 const char *file, const char *shortrevisions,
5891 const char *shortonto, int num, unsigned flags)
5893 int res;
5894 struct strbuf buf = STRBUF_INIT;
5896 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5897 if (flags & TODO_LIST_APPEND_TODO_HELP)
5898 append_todo_help(count_commands(todo_list),
5899 shortrevisions, shortonto, &buf);
5901 res = write_message(buf.buf, buf.len, file, 0);
5902 strbuf_release(&buf);
5904 return res;
5907 /* skip picking commits whose parents are unchanged */
5908 static int skip_unnecessary_picks(struct repository *r,
5909 struct todo_list *todo_list,
5910 struct object_id *base_oid)
5912 struct object_id *parent_oid;
5913 int i;
5915 for (i = 0; i < todo_list->nr; i++) {
5916 struct todo_item *item = todo_list->items + i;
5918 if (item->command >= TODO_NOOP)
5919 continue;
5920 if (item->command != TODO_PICK)
5921 break;
5922 if (parse_commit(item->commit)) {
5923 return error(_("could not parse commit '%s'"),
5924 oid_to_hex(&item->commit->object.oid));
5926 if (!item->commit->parents)
5927 break; /* root commit */
5928 if (item->commit->parents->next)
5929 break; /* merge commit */
5930 parent_oid = &item->commit->parents->item->object.oid;
5931 if (!oideq(parent_oid, base_oid))
5932 break;
5933 oidcpy(base_oid, &item->commit->object.oid);
5935 if (i > 0) {
5936 const char *done_path = rebase_path_done();
5938 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5939 error_errno(_("could not write to '%s'"), done_path);
5940 return -1;
5943 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5944 todo_list->nr -= i;
5945 todo_list->current = 0;
5946 todo_list->done_nr += i;
5948 if (is_fixup(peek_command(todo_list, 0)))
5949 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5952 return 0;
5955 struct todo_add_branch_context {
5956 struct todo_item *items;
5957 size_t items_nr;
5958 size_t items_alloc;
5959 struct strbuf *buf;
5960 struct commit *commit;
5961 struct string_list refs_to_oids;
5964 static int add_decorations_to_list(const struct commit *commit,
5965 struct todo_add_branch_context *ctx)
5967 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5968 const char *head_ref = resolve_ref_unsafe("HEAD",
5969 RESOLVE_REF_READING,
5970 NULL,
5971 NULL);
5973 while (decoration) {
5974 struct todo_item *item;
5975 const char *path;
5976 size_t base_offset = ctx->buf->len;
5979 * If the branch is the current HEAD, then it will be
5980 * updated by the default rebase behavior.
5982 if (head_ref && !strcmp(head_ref, decoration->name)) {
5983 decoration = decoration->next;
5984 continue;
5987 ALLOC_GROW(ctx->items,
5988 ctx->items_nr + 1,
5989 ctx->items_alloc);
5990 item = &ctx->items[ctx->items_nr];
5991 memset(item, 0, sizeof(*item));
5993 /* If the branch is checked out, then leave a comment instead. */
5994 if ((path = branch_checked_out(decoration->name))) {
5995 item->command = TODO_COMMENT;
5996 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
5997 decoration->name, path);
5998 } else {
5999 struct string_list_item *sti;
6000 item->command = TODO_UPDATE_REF;
6001 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6003 sti = string_list_insert(&ctx->refs_to_oids,
6004 decoration->name);
6005 sti->util = init_update_ref_record(decoration->name);
6008 item->offset_in_buf = base_offset;
6009 item->arg_offset = base_offset;
6010 item->arg_len = ctx->buf->len - base_offset;
6011 ctx->items_nr++;
6013 decoration = decoration->next;
6016 return 0;
6020 * For each 'pick' command, find out if the commit has a decoration in
6021 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6023 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6025 int i, res;
6026 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6027 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6028 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6029 struct decoration_filter decoration_filter = {
6030 .include_ref_pattern = &decorate_refs_include,
6031 .exclude_ref_pattern = &decorate_refs_exclude,
6032 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6034 struct todo_add_branch_context ctx = {
6035 .buf = &todo_list->buf,
6036 .refs_to_oids = STRING_LIST_INIT_DUP,
6039 ctx.items_alloc = 2 * todo_list->nr + 1;
6040 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6042 string_list_append(&decorate_refs_include, "refs/heads/");
6043 load_ref_decorations(&decoration_filter, 0);
6045 for (i = 0; i < todo_list->nr; ) {
6046 struct todo_item *item = &todo_list->items[i];
6048 /* insert ith item into new list */
6049 ALLOC_GROW(ctx.items,
6050 ctx.items_nr + 1,
6051 ctx.items_alloc);
6053 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6055 if (item->commit) {
6056 ctx.commit = item->commit;
6057 add_decorations_to_list(item->commit, &ctx);
6061 res = write_update_refs_state(&ctx.refs_to_oids);
6063 string_list_clear(&ctx.refs_to_oids, 1);
6065 if (res) {
6066 /* we failed, so clean up the new list. */
6067 free(ctx.items);
6068 return res;
6071 free(todo_list->items);
6072 todo_list->items = ctx.items;
6073 todo_list->nr = ctx.items_nr;
6074 todo_list->alloc = ctx.items_alloc;
6076 return 0;
6079 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6080 const char *shortrevisions, const char *onto_name,
6081 struct commit *onto, const struct object_id *orig_head,
6082 struct string_list *commands, unsigned autosquash,
6083 unsigned update_refs,
6084 struct todo_list *todo_list)
6086 char shortonto[GIT_MAX_HEXSZ + 1];
6087 const char *todo_file = rebase_path_todo();
6088 struct todo_list new_todo = TODO_LIST_INIT;
6089 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6090 struct object_id oid = onto->object.oid;
6091 int res;
6093 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
6095 if (buf->len == 0) {
6096 struct todo_item *item = append_new_todo(todo_list);
6097 item->command = TODO_NOOP;
6098 item->commit = NULL;
6099 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6102 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6103 return -1;
6105 if (autosquash && todo_list_rearrange_squash(todo_list))
6106 return -1;
6108 if (commands->nr)
6109 todo_list_add_exec_commands(todo_list, commands);
6111 if (count_commands(todo_list) == 0) {
6112 apply_autostash(rebase_path_autostash());
6113 sequencer_remove_state(opts);
6115 return error(_("nothing to do"));
6118 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6119 shortonto, flags);
6120 if (res == -1)
6121 return -1;
6122 else if (res == -2) {
6123 apply_autostash(rebase_path_autostash());
6124 sequencer_remove_state(opts);
6126 return -1;
6127 } else if (res == -3) {
6128 apply_autostash(rebase_path_autostash());
6129 sequencer_remove_state(opts);
6130 todo_list_release(&new_todo);
6132 return error(_("nothing to do"));
6133 } else if (res == -4) {
6134 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6135 todo_list_release(&new_todo);
6137 return -1;
6140 /* Expand the commit IDs */
6141 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6142 strbuf_swap(&new_todo.buf, &buf2);
6143 strbuf_release(&buf2);
6144 new_todo.total_nr -= new_todo.nr;
6145 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6146 BUG("invalid todo list after expanding IDs:\n%s",
6147 new_todo.buf.buf);
6149 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6150 todo_list_release(&new_todo);
6151 return error(_("could not skip unnecessary pick commands"));
6154 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6155 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6156 todo_list_release(&new_todo);
6157 return error_errno(_("could not write '%s'"), todo_file);
6160 res = -1;
6162 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6163 goto cleanup;
6165 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6166 goto cleanup;
6168 todo_list_write_total_nr(&new_todo);
6169 res = pick_commits(r, &new_todo, opts);
6171 cleanup:
6172 todo_list_release(&new_todo);
6174 return res;
6177 struct subject2item_entry {
6178 struct hashmap_entry entry;
6179 int i;
6180 char subject[FLEX_ARRAY];
6183 static int subject2item_cmp(const void *fndata UNUSED,
6184 const struct hashmap_entry *eptr,
6185 const struct hashmap_entry *entry_or_key,
6186 const void *key)
6188 const struct subject2item_entry *a, *b;
6190 a = container_of(eptr, const struct subject2item_entry, entry);
6191 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6193 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6196 define_commit_slab(commit_todo_item, struct todo_item *);
6198 static int skip_fixupish(const char *subject, const char **p) {
6199 return skip_prefix(subject, "fixup! ", p) ||
6200 skip_prefix(subject, "amend! ", p) ||
6201 skip_prefix(subject, "squash! ", p);
6205 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6206 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6207 * after the former, and change "pick" to "fixup"/"squash".
6209 * Note that if the config has specified a custom instruction format, each log
6210 * message will have to be retrieved from the commit (as the oneline in the
6211 * script cannot be trusted) in order to normalize the autosquash arrangement.
6213 int todo_list_rearrange_squash(struct todo_list *todo_list)
6215 struct hashmap subject2item;
6216 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6217 char **subjects;
6218 struct commit_todo_item commit_todo;
6219 struct todo_item *items = NULL;
6221 init_commit_todo_item(&commit_todo);
6223 * The hashmap maps onelines to the respective todo list index.
6225 * If any items need to be rearranged, the next[i] value will indicate
6226 * which item was moved directly after the i'th.
6228 * In that case, last[i] will indicate the index of the latest item to
6229 * be moved to appear after the i'th.
6231 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6232 ALLOC_ARRAY(next, todo_list->nr);
6233 ALLOC_ARRAY(tail, todo_list->nr);
6234 ALLOC_ARRAY(subjects, todo_list->nr);
6235 for (i = 0; i < todo_list->nr; i++) {
6236 struct strbuf buf = STRBUF_INIT;
6237 struct todo_item *item = todo_list->items + i;
6238 const char *commit_buffer, *subject, *p;
6239 size_t subject_len;
6240 int i2 = -1;
6241 struct subject2item_entry *entry;
6243 next[i] = tail[i] = -1;
6244 if (!item->commit || item->command == TODO_DROP) {
6245 subjects[i] = NULL;
6246 continue;
6249 if (is_fixup(item->command)) {
6250 clear_commit_todo_item(&commit_todo);
6251 return error(_("the script was already rearranged."));
6254 parse_commit(item->commit);
6255 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
6256 find_commit_subject(commit_buffer, &subject);
6257 format_subject(&buf, subject, " ");
6258 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6259 unuse_commit_buffer(item->commit, commit_buffer);
6260 if (skip_fixupish(subject, &p)) {
6261 struct commit *commit2;
6263 for (;;) {
6264 while (isspace(*p))
6265 p++;
6266 if (!skip_fixupish(p, &p))
6267 break;
6270 entry = hashmap_get_entry_from_hash(&subject2item,
6271 strhash(p), p,
6272 struct subject2item_entry,
6273 entry);
6274 if (entry)
6275 /* found by title */
6276 i2 = entry->i;
6277 else if (!strchr(p, ' ') &&
6278 (commit2 =
6279 lookup_commit_reference_by_name(p)) &&
6280 *commit_todo_item_at(&commit_todo, commit2))
6281 /* found by commit name */
6282 i2 = *commit_todo_item_at(&commit_todo, commit2)
6283 - todo_list->items;
6284 else {
6285 /* copy can be a prefix of the commit subject */
6286 for (i2 = 0; i2 < i; i2++)
6287 if (subjects[i2] &&
6288 starts_with(subjects[i2], p))
6289 break;
6290 if (i2 == i)
6291 i2 = -1;
6294 if (i2 >= 0) {
6295 rearranged = 1;
6296 if (starts_with(subject, "fixup!")) {
6297 todo_list->items[i].command = TODO_FIXUP;
6298 } else if (starts_with(subject, "amend!")) {
6299 todo_list->items[i].command = TODO_FIXUP;
6300 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6301 } else {
6302 todo_list->items[i].command = TODO_SQUASH;
6304 if (tail[i2] < 0) {
6305 next[i] = next[i2];
6306 next[i2] = i;
6307 } else {
6308 next[i] = next[tail[i2]];
6309 next[tail[i2]] = i;
6311 tail[i2] = i;
6312 } else if (!hashmap_get_from_hash(&subject2item,
6313 strhash(subject), subject)) {
6314 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6315 entry->i = i;
6316 hashmap_entry_init(&entry->entry,
6317 strhash(entry->subject));
6318 hashmap_put(&subject2item, &entry->entry);
6321 *commit_todo_item_at(&commit_todo, item->commit) = item;
6324 if (rearranged) {
6325 for (i = 0; i < todo_list->nr; i++) {
6326 enum todo_command command = todo_list->items[i].command;
6327 int cur = i;
6330 * Initially, all commands are 'pick's. If it is a
6331 * fixup or a squash now, we have rearranged it.
6333 if (is_fixup(command))
6334 continue;
6336 while (cur >= 0) {
6337 ALLOC_GROW(items, nr + 1, alloc);
6338 items[nr++] = todo_list->items[cur];
6339 cur = next[cur];
6343 FREE_AND_NULL(todo_list->items);
6344 todo_list->items = items;
6345 todo_list->nr = nr;
6346 todo_list->alloc = alloc;
6349 free(next);
6350 free(tail);
6351 for (i = 0; i < todo_list->nr; i++)
6352 free(subjects[i]);
6353 free(subjects);
6354 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6356 clear_commit_todo_item(&commit_todo);
6358 return 0;
6361 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6363 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6364 struct object_id cherry_pick_head, rebase_head;
6366 if (file_exists(git_path_seq_dir()))
6367 *whence = FROM_CHERRY_PICK_MULTI;
6368 if (file_exists(rebase_path()) &&
6369 !get_oid("REBASE_HEAD", &rebase_head) &&
6370 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
6371 oideq(&rebase_head, &cherry_pick_head))
6372 *whence = FROM_REBASE_PICK;
6373 else
6374 *whence = FROM_CHERRY_PICK_SINGLE;
6376 return 1;
6379 return 0;
6382 int sequencer_get_update_refs_state(const char *wt_dir,
6383 struct string_list *refs)
6385 int result = 0;
6386 FILE *fp = NULL;
6387 struct strbuf ref = STRBUF_INIT;
6388 struct strbuf hash = STRBUF_INIT;
6389 struct update_ref_record *rec = NULL;
6391 char *path = rebase_path_update_refs(wt_dir);
6393 fp = fopen(path, "r");
6394 if (!fp)
6395 goto cleanup;
6397 while (strbuf_getline(&ref, fp) != EOF) {
6398 struct string_list_item *item;
6400 CALLOC_ARRAY(rec, 1);
6402 if (strbuf_getline(&hash, fp) == EOF ||
6403 get_oid_hex(hash.buf, &rec->before)) {
6404 warning(_("update-refs file at '%s' is invalid"),
6405 path);
6406 result = -1;
6407 goto cleanup;
6410 if (strbuf_getline(&hash, fp) == EOF ||
6411 get_oid_hex(hash.buf, &rec->after)) {
6412 warning(_("update-refs file at '%s' is invalid"),
6413 path);
6414 result = -1;
6415 goto cleanup;
6418 item = string_list_insert(refs, ref.buf);
6419 item->util = rec;
6420 rec = NULL;
6423 cleanup:
6424 if (fp)
6425 fclose(fp);
6426 free(path);
6427 free(rec);
6428 strbuf_release(&ref);
6429 strbuf_release(&hash);
6430 return result;