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