cocci: remove 'unused.cocci'
[git.git] / sequencer.c
blobd2c7698c48ceb92f1bd1ceb03496033cc78f35a0
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "lockfile.h"
9 #include "dir.h"
10 #include "object-store.h"
11 #include "object.h"
12 #include "commit.h"
13 #include "sequencer.h"
14 #include "tag.h"
15 #include "run-command.h"
16 #include "hook.h"
17 #include "exec-cmd.h"
18 #include "utf8.h"
19 #include "cache-tree.h"
20 #include "diff.h"
21 #include "revision.h"
22 #include "rerere.h"
23 #include "merge-ort.h"
24 #include "merge-ort-wrappers.h"
25 #include "refs.h"
26 #include "strvec.h"
27 #include "quote.h"
28 #include "trailer.h"
29 #include "log-tree.h"
30 #include "wt-status.h"
31 #include "hashmap.h"
32 #include "notes-utils.h"
33 #include "sigchain.h"
34 #include "unpack-trees.h"
35 #include "worktree.h"
36 #include "oidmap.h"
37 #include "oidset.h"
38 #include "commit-slab.h"
39 #include "alias.h"
40 #include "commit-reach.h"
41 #include "rebase-interactive.h"
42 #include "reset.h"
43 #include "branch.h"
44 #include "wrapper.h"
46 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
48 static const char sign_off_header[] = "Signed-off-by: ";
49 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
51 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
53 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
55 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
56 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
57 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
58 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
60 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
62 * The file containing rebase commands, comments, and empty lines.
63 * This file is created by "git rebase -i" then edited by the user. As
64 * the lines are processed, they are removed from the front of this
65 * file and written to the tail of 'done'.
67 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
68 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
70 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
73 * The rebase command lines that have already been processed. A line
74 * is moved here when it is first handled, before any associated user
75 * actions.
77 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
79 * The file to keep track of how many commands were already processed (e.g.
80 * for the prompt).
82 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
84 * The file to keep track of how many commands are to be processed in total
85 * (e.g. for the prompt).
87 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
89 * The commit message that is planned to be used for any changes that
90 * need to be committed following a user interaction.
92 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
94 * The file into which is accumulated the suggested commit message for
95 * squash/fixup commands. When the first of a series of squash/fixups
96 * is seen, the file is created and the commit message from the
97 * previous commit and from the first squash/fixup commit are written
98 * to it. The commit message for each subsequent squash/fixup commit
99 * is appended to the file as it is processed.
101 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
103 * If the current series of squash/fixups has not yet included a squash
104 * command, then this file exists and holds the commit message of the
105 * original "pick" commit. (If the series ends without a "squash"
106 * command, then this can be used as the commit message of the combined
107 * commit without opening the editor.)
109 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
111 * This file contains the list fixup/squash commands that have been
112 * accumulated into message-fixup or message-squash so far.
114 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
116 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
117 * GIT_AUTHOR_DATE that will be used for the commit that is currently
118 * being rebased.
120 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
122 * When an "edit" rebase command is being processed, the SHA1 of the
123 * commit to be edited is recorded in this file. When "git rebase
124 * --continue" is executed, if there are any staged changes then they
125 * will be amended to the HEAD commit, but only provided the HEAD
126 * commit is still the commit to be edited. When any other rebase
127 * command is processed, this file is deleted.
129 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
131 * When we stop at a given patch via the "edit" command, this file contains
132 * the commit object name of the corresponding patch.
134 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
136 * For the post-rewrite hook, we make a list of rewritten commits and
137 * their new sha1s. The rewritten-pending list keeps the sha1s of
138 * commits that have been processed, but not committed yet,
139 * e.g. because they are waiting for a 'squash' command.
141 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
142 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
143 "rebase-merge/rewritten-pending")
146 * The path of the file containing the OID of the "squash onto" commit, i.e.
147 * the dummy commit used for `reset [new root]`.
149 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
152 * The path of the file listing refs that need to be deleted after the rebase
153 * finishes. This is used by the `label` command to record the need for cleanup.
155 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
158 * The update-refs file stores a list of refs that will be updated at the end
159 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
160 * update the OIDs for the refs in this file, but the refs are not updated
161 * until the end of the rebase sequence.
163 * rebase_path_update_refs() returns the path to this file for a given
164 * worktree directory. For the current worktree, pass the_repository->gitdir.
166 static char *rebase_path_update_refs(const char *wt_git_dir)
168 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
172 * The following files are written by git-rebase just after parsing the
173 * command-line.
175 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
176 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
177 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
178 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
179 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
180 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
181 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
182 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
183 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
184 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
185 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
186 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
187 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
188 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
189 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
190 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
191 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
194 * A 'struct update_refs_record' represents a value in the update-refs
195 * list. We use a string_list to map refs to these (before, after) pairs.
197 struct update_ref_record {
198 struct object_id before;
199 struct object_id after;
202 static struct update_ref_record *init_update_ref_record(const char *ref)
204 struct update_ref_record *rec;
206 CALLOC_ARRAY(rec, 1);
208 oidcpy(&rec->before, null_oid());
209 oidcpy(&rec->after, null_oid());
211 /* This may fail, but that's fine, we will keep the null OID. */
212 read_ref(ref, &rec->before);
214 return rec;
217 static int git_sequencer_config(const char *k, const char *v, void *cb)
219 struct replay_opts *opts = cb;
220 int status;
222 if (!strcmp(k, "commit.cleanup")) {
223 const char *s;
225 status = git_config_string(&s, k, v);
226 if (status)
227 return status;
229 if (!strcmp(s, "verbatim")) {
230 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
231 opts->explicit_cleanup = 1;
232 } else if (!strcmp(s, "whitespace")) {
233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
234 opts->explicit_cleanup = 1;
235 } else if (!strcmp(s, "strip")) {
236 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
237 opts->explicit_cleanup = 1;
238 } else if (!strcmp(s, "scissors")) {
239 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
240 opts->explicit_cleanup = 1;
241 } else {
242 warning(_("invalid commit message cleanup mode '%s'"),
246 free((char *)s);
247 return status;
250 if (!strcmp(k, "commit.gpgsign")) {
251 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
252 return 0;
255 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
256 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
257 if (ret == 0) {
259 * pull.twohead is allowed to be multi-valued; we only
260 * care about the first value.
262 char *tmp = strchr(opts->default_strategy, ' ');
263 if (tmp)
264 *tmp = '\0';
266 return ret;
269 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
270 opts->commit_use_reference = git_config_bool(k, v);
272 return git_diff_basic_config(k, v, NULL);
275 void sequencer_init_config(struct replay_opts *opts)
277 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
278 git_config(git_sequencer_config, opts);
281 static inline int is_rebase_i(const struct replay_opts *opts)
283 return opts->action == REPLAY_INTERACTIVE_REBASE;
286 static const char *get_dir(const struct replay_opts *opts)
288 if (is_rebase_i(opts))
289 return rebase_path();
290 return git_path_seq_dir();
293 static const char *get_todo_path(const struct replay_opts *opts)
295 if (is_rebase_i(opts))
296 return rebase_path_todo();
297 return git_path_todo_file();
301 * Returns 0 for non-conforming footer
302 * Returns 1 for conforming footer
303 * Returns 2 when sob exists within conforming footer
304 * Returns 3 when sob exists within conforming footer as last entry
306 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
307 size_t ignore_footer)
309 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
310 struct trailer_info info;
311 size_t i;
312 int found_sob = 0, found_sob_last = 0;
313 char saved_char;
315 opts.no_divider = 1;
317 if (ignore_footer) {
318 saved_char = sb->buf[sb->len - ignore_footer];
319 sb->buf[sb->len - ignore_footer] = '\0';
322 trailer_info_get(&info, sb->buf, &opts);
324 if (ignore_footer)
325 sb->buf[sb->len - ignore_footer] = saved_char;
327 if (info.trailer_start == info.trailer_end)
328 return 0;
330 for (i = 0; i < info.trailer_nr; i++)
331 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
332 found_sob = 1;
333 if (i == info.trailer_nr - 1)
334 found_sob_last = 1;
337 trailer_info_release(&info);
339 if (found_sob_last)
340 return 3;
341 if (found_sob)
342 return 2;
343 return 1;
346 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
348 static struct strbuf buf = STRBUF_INIT;
350 strbuf_reset(&buf);
351 if (opts->gpg_sign)
352 sq_quotef(&buf, "-S%s", opts->gpg_sign);
353 return buf.buf;
356 void replay_opts_release(struct replay_opts *opts)
358 free(opts->gpg_sign);
359 free(opts->reflog_action);
360 free(opts->default_strategy);
361 free(opts->strategy);
362 strvec_clear (&opts->xopts);
363 strbuf_release(&opts->current_fixups);
364 if (opts->revs)
365 release_revisions(opts->revs);
366 free(opts->revs);
369 int sequencer_remove_state(struct replay_opts *opts)
371 struct strbuf buf = STRBUF_INIT;
372 int ret = 0;
374 if (is_rebase_i(opts) &&
375 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
376 char *p = buf.buf;
377 while (*p) {
378 char *eol = strchr(p, '\n');
379 if (eol)
380 *eol = '\0';
381 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
382 warning(_("could not delete '%s'"), p);
383 ret = -1;
385 if (!eol)
386 break;
387 p = eol + 1;
391 strbuf_reset(&buf);
392 strbuf_addstr(&buf, get_dir(opts));
393 if (remove_dir_recursively(&buf, 0))
394 ret = error(_("could not remove '%s'"), buf.buf);
395 strbuf_release(&buf);
397 return ret;
400 static const char *action_name(const struct replay_opts *opts)
402 switch (opts->action) {
403 case REPLAY_REVERT:
404 return N_("revert");
405 case REPLAY_PICK:
406 return N_("cherry-pick");
407 case REPLAY_INTERACTIVE_REBASE:
408 return N_("rebase");
410 die(_("unknown action: %d"), opts->action);
413 struct commit_message {
414 char *parent_label;
415 char *label;
416 char *subject;
417 const char *message;
420 static const char *short_commit_name(struct commit *commit)
422 return repo_find_unique_abbrev(the_repository, &commit->object.oid,
423 DEFAULT_ABBREV);
426 static int get_message(struct commit *commit, struct commit_message *out)
428 const char *abbrev, *subject;
429 int subject_len;
431 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
432 get_commit_output_encoding());
433 abbrev = short_commit_name(commit);
435 subject_len = find_commit_subject(out->message, &subject);
437 out->subject = xmemdupz(subject, subject_len);
438 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
439 out->parent_label = xstrfmt("parent of %s", out->label);
441 return 0;
444 static void free_message(struct commit *commit, struct commit_message *msg)
446 free(msg->parent_label);
447 free(msg->label);
448 free(msg->subject);
449 repo_unuse_commit_buffer(the_repository, commit, msg->message);
452 static void print_advice(struct repository *r, int show_hint,
453 struct replay_opts *opts)
455 char *msg = getenv("GIT_CHERRY_PICK_HELP");
457 if (msg) {
458 advise("%s\n", msg);
460 * A conflict has occurred but the porcelain
461 * (typically rebase --interactive) wants to take care
462 * of the commit itself so remove CHERRY_PICK_HEAD
464 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
465 NULL, 0);
466 return;
469 if (show_hint) {
470 if (opts->no_commit)
471 advise(_("after resolving the conflicts, mark the corrected paths\n"
472 "with 'git add <paths>' or 'git rm <paths>'"));
473 else if (opts->action == REPLAY_PICK)
474 advise(_("After resolving the conflicts, mark them with\n"
475 "\"git add/rm <pathspec>\", then run\n"
476 "\"git cherry-pick --continue\".\n"
477 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
478 "To abort and get back to the state before \"git cherry-pick\",\n"
479 "run \"git cherry-pick --abort\"."));
480 else if (opts->action == REPLAY_REVERT)
481 advise(_("After resolving the conflicts, mark them with\n"
482 "\"git add/rm <pathspec>\", then run\n"
483 "\"git revert --continue\".\n"
484 "You can instead skip this commit with \"git revert --skip\".\n"
485 "To abort and get back to the state before \"git revert\",\n"
486 "run \"git revert --abort\"."));
487 else
488 BUG("unexpected pick action in print_advice()");
492 static int write_message(const void *buf, size_t len, const char *filename,
493 int append_eol)
495 struct lock_file msg_file = LOCK_INIT;
497 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
498 if (msg_fd < 0)
499 return error_errno(_("could not lock '%s'"), filename);
500 if (write_in_full(msg_fd, buf, len) < 0) {
501 error_errno(_("could not write to '%s'"), filename);
502 rollback_lock_file(&msg_file);
503 return -1;
505 if (append_eol && write(msg_fd, "\n", 1) < 0) {
506 error_errno(_("could not write eol to '%s'"), filename);
507 rollback_lock_file(&msg_file);
508 return -1;
510 if (commit_lock_file(&msg_file) < 0)
511 return error(_("failed to finalize '%s'"), filename);
513 return 0;
516 int read_oneliner(struct strbuf *buf,
517 const char *path, unsigned flags)
519 int orig_len = buf->len;
521 if (strbuf_read_file(buf, path, 0) < 0) {
522 if ((flags & READ_ONELINER_WARN_MISSING) ||
523 (errno != ENOENT && errno != ENOTDIR))
524 warning_errno(_("could not read '%s'"), path);
525 return 0;
528 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
529 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
530 --buf->len;
531 buf->buf[buf->len] = '\0';
534 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
535 return 0;
537 return 1;
540 static struct tree *empty_tree(struct repository *r)
542 return lookup_tree(r, the_hash_algo->empty_tree);
545 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
547 if (repo_read_index_unmerged(repo))
548 return error_resolve_conflict(action_name(opts));
550 error(_("your local changes would be overwritten by %s."),
551 _(action_name(opts)));
553 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
554 advise(_("commit your changes or stash them to proceed."));
555 return -1;
558 static void update_abort_safety_file(void)
560 struct object_id head;
562 /* Do nothing on a single-pick */
563 if (!file_exists(git_path_seq_dir()))
564 return;
566 if (!repo_get_oid(the_repository, "HEAD", &head))
567 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
568 else
569 write_file(git_path_abort_safety_file(), "%s", "");
572 static int fast_forward_to(struct repository *r,
573 const struct object_id *to,
574 const struct object_id *from,
575 int unborn,
576 struct replay_opts *opts)
578 struct ref_transaction *transaction;
579 struct strbuf sb = STRBUF_INIT;
580 struct strbuf err = STRBUF_INIT;
582 repo_read_index(r);
583 if (checkout_fast_forward(r, from, to, 1))
584 return -1; /* the callee should have complained already */
586 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
588 transaction = ref_transaction_begin(&err);
589 if (!transaction ||
590 ref_transaction_update(transaction, "HEAD",
591 to, unborn && !is_rebase_i(opts) ?
592 null_oid() : from,
593 0, sb.buf, &err) ||
594 ref_transaction_commit(transaction, &err)) {
595 ref_transaction_free(transaction);
596 error("%s", err.buf);
597 strbuf_release(&sb);
598 strbuf_release(&err);
599 return -1;
602 strbuf_release(&sb);
603 strbuf_release(&err);
604 ref_transaction_free(transaction);
605 update_abort_safety_file();
606 return 0;
609 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
610 int use_editor)
612 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
613 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
614 COMMIT_MSG_CLEANUP_SPACE;
615 else if (!strcmp(cleanup_arg, "verbatim"))
616 return COMMIT_MSG_CLEANUP_NONE;
617 else if (!strcmp(cleanup_arg, "whitespace"))
618 return COMMIT_MSG_CLEANUP_SPACE;
619 else if (!strcmp(cleanup_arg, "strip"))
620 return COMMIT_MSG_CLEANUP_ALL;
621 else if (!strcmp(cleanup_arg, "scissors"))
622 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
623 COMMIT_MSG_CLEANUP_SPACE;
624 else
625 die(_("Invalid cleanup mode %s"), cleanup_arg);
629 * NB using int rather than enum cleanup_mode to stop clang's
630 * -Wtautological-constant-out-of-range-compare complaining that the comparison
631 * is always true.
633 static const char *describe_cleanup_mode(int cleanup_mode)
635 static const char *modes[] = { "whitespace",
636 "verbatim",
637 "scissors",
638 "strip" };
640 if (cleanup_mode < ARRAY_SIZE(modes))
641 return modes[cleanup_mode];
643 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
646 void append_conflicts_hint(struct index_state *istate,
647 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
649 int i;
651 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
652 strbuf_addch(msgbuf, '\n');
653 wt_status_append_cut_line(msgbuf);
654 strbuf_addch(msgbuf, comment_line_char);
657 strbuf_addch(msgbuf, '\n');
658 strbuf_commented_addf(msgbuf, "Conflicts:\n");
659 for (i = 0; i < istate->cache_nr;) {
660 const struct cache_entry *ce = istate->cache[i++];
661 if (ce_stage(ce)) {
662 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
663 while (i < istate->cache_nr &&
664 !strcmp(ce->name, istate->cache[i]->name))
665 i++;
670 static int do_recursive_merge(struct repository *r,
671 struct commit *base, struct commit *next,
672 const char *base_label, const char *next_label,
673 struct object_id *head, struct strbuf *msgbuf,
674 struct replay_opts *opts)
676 struct merge_options o;
677 struct merge_result result;
678 struct tree *next_tree, *base_tree, *head_tree;
679 int clean, show_output;
680 int i;
681 struct lock_file index_lock = LOCK_INIT;
683 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
684 return -1;
686 repo_read_index(r);
688 init_merge_options(&o, r);
689 o.ancestor = base ? base_label : "(empty tree)";
690 o.branch1 = "HEAD";
691 o.branch2 = next ? next_label : "(empty tree)";
692 if (is_rebase_i(opts))
693 o.buffer_output = 2;
694 o.show_rename_progress = 1;
696 head_tree = parse_tree_indirect(head);
697 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
698 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
700 for (i = 0; i < opts->xopts.nr; i++)
701 parse_merge_opt(&o, opts->xopts.v[i]);
703 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
704 memset(&result, 0, sizeof(result));
705 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
706 &result);
707 show_output = !is_rebase_i(opts) || !result.clean;
709 * TODO: merge_switch_to_result will update index/working tree;
710 * we only really want to do that if !result.clean || this is
711 * the final patch to be picked. But determining this is the
712 * final patch would take some work, and "head_tree" would need
713 * to be replace with the tree the index matched before we
714 * started doing any picks.
716 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
717 clean = result.clean;
718 } else {
719 ensure_full_index(r->index);
720 clean = merge_trees(&o, head_tree, next_tree, base_tree);
721 if (is_rebase_i(opts) && clean <= 0)
722 fputs(o.obuf.buf, stdout);
723 strbuf_release(&o.obuf);
725 if (clean < 0) {
726 rollback_lock_file(&index_lock);
727 return clean;
730 if (write_locked_index(r->index, &index_lock,
731 COMMIT_LOCK | SKIP_IF_UNCHANGED))
733 * TRANSLATORS: %s will be "revert", "cherry-pick" or
734 * "rebase".
736 return error(_("%s: Unable to write new index file"),
737 _(action_name(opts)));
739 if (!clean)
740 append_conflicts_hint(r->index, msgbuf,
741 opts->default_msg_cleanup);
743 return !clean;
746 static struct object_id *get_cache_tree_oid(struct index_state *istate)
748 if (!cache_tree_fully_valid(istate->cache_tree))
749 if (cache_tree_update(istate, 0)) {
750 error(_("unable to update cache tree"));
751 return NULL;
754 return &istate->cache_tree->oid;
757 static int is_index_unchanged(struct repository *r)
759 struct object_id head_oid, *cache_tree_oid;
760 struct commit *head_commit;
761 struct index_state *istate = r->index;
763 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
764 return error(_("could not resolve HEAD commit"));
766 head_commit = lookup_commit(r, &head_oid);
769 * If head_commit is NULL, check_commit, called from
770 * lookup_commit, would have indicated that head_commit is not
771 * a commit object already. repo_parse_commit() will return failure
772 * without further complaints in such a case. Otherwise, if
773 * the commit is invalid, repo_parse_commit() will complain. So
774 * there is nothing for us to say here. Just return failure.
776 if (repo_parse_commit(r, head_commit))
777 return -1;
779 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
780 return -1;
782 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
785 static int write_author_script(const char *message)
787 struct strbuf buf = STRBUF_INIT;
788 const char *eol;
789 int res;
791 for (;;)
792 if (!*message || starts_with(message, "\n")) {
793 missing_author:
794 /* Missing 'author' line? */
795 unlink(rebase_path_author_script());
796 return 0;
797 } else if (skip_prefix(message, "author ", &message))
798 break;
799 else if ((eol = strchr(message, '\n')))
800 message = eol + 1;
801 else
802 goto missing_author;
804 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
805 while (*message && *message != '\n' && *message != '\r')
806 if (skip_prefix(message, " <", &message))
807 break;
808 else if (*message != '\'')
809 strbuf_addch(&buf, *(message++));
810 else
811 strbuf_addf(&buf, "'\\%c'", *(message++));
812 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
813 while (*message && *message != '\n' && *message != '\r')
814 if (skip_prefix(message, "> ", &message))
815 break;
816 else if (*message != '\'')
817 strbuf_addch(&buf, *(message++));
818 else
819 strbuf_addf(&buf, "'\\%c'", *(message++));
820 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
821 while (*message && *message != '\n' && *message != '\r')
822 if (*message != '\'')
823 strbuf_addch(&buf, *(message++));
824 else
825 strbuf_addf(&buf, "'\\%c'", *(message++));
826 strbuf_addch(&buf, '\'');
827 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
828 strbuf_release(&buf);
829 return res;
833 * Take a series of KEY='VALUE' lines where VALUE part is
834 * sq-quoted, and append <KEY, VALUE> at the end of the string list
836 static int parse_key_value_squoted(char *buf, struct string_list *list)
838 while (*buf) {
839 struct string_list_item *item;
840 char *np;
841 char *cp = strchr(buf, '=');
842 if (!cp) {
843 np = strchrnul(buf, '\n');
844 return error(_("no key present in '%.*s'"),
845 (int) (np - buf), buf);
847 np = strchrnul(cp, '\n');
848 *cp++ = '\0';
849 item = string_list_append(list, buf);
851 buf = np + (*np == '\n');
852 *np = '\0';
853 cp = sq_dequote(cp);
854 if (!cp)
855 return error(_("unable to dequote value of '%s'"),
856 item->string);
857 item->util = xstrdup(cp);
859 return 0;
863 * Reads and parses the state directory's "author-script" file, and sets name,
864 * email and date accordingly.
865 * Returns 0 on success, -1 if the file could not be parsed.
867 * The author script is of the format:
869 * GIT_AUTHOR_NAME='$author_name'
870 * GIT_AUTHOR_EMAIL='$author_email'
871 * GIT_AUTHOR_DATE='$author_date'
873 * where $author_name, $author_email and $author_date are quoted. We are strict
874 * with our parsing, as the file was meant to be eval'd in the now-removed
875 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
876 * from what this function expects, it is better to bail out than to do
877 * something that the user does not expect.
879 int read_author_script(const char *path, char **name, char **email, char **date,
880 int allow_missing)
882 struct strbuf buf = STRBUF_INIT;
883 struct string_list kv = STRING_LIST_INIT_DUP;
884 int retval = -1; /* assume failure */
885 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
887 if (strbuf_read_file(&buf, path, 256) <= 0) {
888 strbuf_release(&buf);
889 if (errno == ENOENT && allow_missing)
890 return 0;
891 else
892 return error_errno(_("could not open '%s' for reading"),
893 path);
896 if (parse_key_value_squoted(buf.buf, &kv))
897 goto finish;
899 for (i = 0; i < kv.nr; i++) {
900 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
901 if (name_i != -2)
902 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
903 else
904 name_i = i;
905 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
906 if (email_i != -2)
907 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
908 else
909 email_i = i;
910 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
911 if (date_i != -2)
912 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
913 else
914 date_i = i;
915 } else {
916 err = error(_("unknown variable '%s'"),
917 kv.items[i].string);
920 if (name_i == -2)
921 error(_("missing 'GIT_AUTHOR_NAME'"));
922 if (email_i == -2)
923 error(_("missing 'GIT_AUTHOR_EMAIL'"));
924 if (date_i == -2)
925 error(_("missing 'GIT_AUTHOR_DATE'"));
926 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
927 goto finish;
928 *name = kv.items[name_i].util;
929 *email = kv.items[email_i].util;
930 *date = kv.items[date_i].util;
931 retval = 0;
932 finish:
933 string_list_clear(&kv, !!retval);
934 strbuf_release(&buf);
935 return retval;
939 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
940 * file with shell quoting into struct strvec. Returns -1 on
941 * error, 0 otherwise.
943 static int read_env_script(struct strvec *env)
945 char *name, *email, *date;
947 if (read_author_script(rebase_path_author_script(),
948 &name, &email, &date, 0))
949 return -1;
951 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
952 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
953 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
954 free(name);
955 free(email);
956 free(date);
958 return 0;
961 static char *get_author(const char *message)
963 size_t len;
964 const char *a;
966 a = find_commit_header(message, "author", &len);
967 if (a)
968 return xmemdupz(a, len);
970 return NULL;
973 static const char *author_date_from_env(const struct strvec *env)
975 int i;
976 const char *date;
978 for (i = 0; i < env->nr; i++)
979 if (skip_prefix(env->v[i],
980 "GIT_AUTHOR_DATE=", &date))
981 return date;
983 * If GIT_AUTHOR_DATE is missing we should have already errored out when
984 * reading the script
986 BUG("GIT_AUTHOR_DATE missing from author script");
989 static const char staged_changes_advice[] =
990 N_("you have staged changes in your working tree\n"
991 "If these changes are meant to be squashed into the previous commit, run:\n"
992 "\n"
993 " git commit --amend %s\n"
994 "\n"
995 "If they are meant to go into a new commit, run:\n"
996 "\n"
997 " git commit %s\n"
998 "\n"
999 "In both cases, once you're done, continue with:\n"
1000 "\n"
1001 " git rebase --continue\n");
1003 #define ALLOW_EMPTY (1<<0)
1004 #define EDIT_MSG (1<<1)
1005 #define AMEND_MSG (1<<2)
1006 #define CLEANUP_MSG (1<<3)
1007 #define VERIFY_MSG (1<<4)
1008 #define CREATE_ROOT_COMMIT (1<<5)
1009 #define VERBATIM_MSG (1<<6)
1011 static int run_command_silent_on_success(struct child_process *cmd)
1013 struct strbuf buf = STRBUF_INIT;
1014 int rc;
1016 cmd->stdout_to_stderr = 1;
1017 rc = pipe_command(cmd,
1018 NULL, 0,
1019 NULL, 0,
1020 &buf, 0);
1022 if (rc)
1023 fputs(buf.buf, stderr);
1024 strbuf_release(&buf);
1025 return rc;
1029 * If we are cherry-pick, and if the merge did not result in
1030 * hand-editing, we will hit this commit and inherit the original
1031 * author date and name.
1033 * If we are revert, or if our cherry-pick results in a hand merge,
1034 * we had better say that the current user is responsible for that.
1036 * An exception is when run_git_commit() is called during an
1037 * interactive rebase: in that case, we will want to retain the
1038 * author metadata.
1040 static int run_git_commit(const char *defmsg,
1041 struct replay_opts *opts,
1042 unsigned int flags)
1044 struct child_process cmd = CHILD_PROCESS_INIT;
1046 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1047 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1049 cmd.git_cmd = 1;
1051 if (is_rebase_i(opts) &&
1052 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1053 !(!defmsg && (flags & AMEND_MSG))) &&
1054 read_env_script(&cmd.env)) {
1055 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1057 return error(_(staged_changes_advice),
1058 gpg_opt, gpg_opt);
1061 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1063 if (opts->committer_date_is_author_date)
1064 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1065 opts->ignore_date ?
1066 "" :
1067 author_date_from_env(&cmd.env));
1068 if (opts->ignore_date)
1069 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1071 strvec_push(&cmd.args, "commit");
1073 if (!(flags & VERIFY_MSG))
1074 strvec_push(&cmd.args, "-n");
1075 if ((flags & AMEND_MSG))
1076 strvec_push(&cmd.args, "--amend");
1077 if (opts->gpg_sign)
1078 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1079 else
1080 strvec_push(&cmd.args, "--no-gpg-sign");
1081 if (defmsg)
1082 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1083 else if (!(flags & EDIT_MSG))
1084 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1085 if ((flags & CLEANUP_MSG))
1086 strvec_push(&cmd.args, "--cleanup=strip");
1087 if ((flags & VERBATIM_MSG))
1088 strvec_push(&cmd.args, "--cleanup=verbatim");
1089 if ((flags & EDIT_MSG))
1090 strvec_push(&cmd.args, "-e");
1091 else if (!(flags & CLEANUP_MSG) &&
1092 !opts->signoff && !opts->record_origin &&
1093 !opts->explicit_cleanup)
1094 strvec_push(&cmd.args, "--cleanup=verbatim");
1096 if ((flags & ALLOW_EMPTY))
1097 strvec_push(&cmd.args, "--allow-empty");
1099 if (!(flags & EDIT_MSG))
1100 strvec_push(&cmd.args, "--allow-empty-message");
1102 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1103 return run_command_silent_on_success(&cmd);
1104 else
1105 return run_command(&cmd);
1108 static int rest_is_empty(const struct strbuf *sb, int start)
1110 int i, eol;
1111 const char *nl;
1113 /* Check if the rest is just whitespace and Signed-off-by's. */
1114 for (i = start; i < sb->len; i++) {
1115 nl = memchr(sb->buf + i, '\n', sb->len - i);
1116 if (nl)
1117 eol = nl - sb->buf;
1118 else
1119 eol = sb->len;
1121 if (strlen(sign_off_header) <= eol - i &&
1122 starts_with(sb->buf + i, sign_off_header)) {
1123 i = eol;
1124 continue;
1126 while (i < eol)
1127 if (!isspace(sb->buf[i++]))
1128 return 0;
1131 return 1;
1134 void cleanup_message(struct strbuf *msgbuf,
1135 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1137 if (verbose || /* Truncate the message just before the diff, if any. */
1138 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1139 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1140 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1141 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1145 * Find out if the message in the strbuf contains only whitespace and
1146 * Signed-off-by lines.
1148 int message_is_empty(const struct strbuf *sb,
1149 enum commit_msg_cleanup_mode cleanup_mode)
1151 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1152 return 0;
1153 return rest_is_empty(sb, 0);
1157 * See if the user edited the message in the editor or left what
1158 * was in the template intact
1160 int template_untouched(const struct strbuf *sb, const char *template_file,
1161 enum commit_msg_cleanup_mode cleanup_mode)
1163 struct strbuf tmpl = STRBUF_INIT;
1164 const char *start;
1166 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1167 return 0;
1169 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1170 return 0;
1172 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1173 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1174 start = sb->buf;
1175 strbuf_release(&tmpl);
1176 return rest_is_empty(sb, start - sb->buf);
1179 int update_head_with_reflog(const struct commit *old_head,
1180 const struct object_id *new_head,
1181 const char *action, const struct strbuf *msg,
1182 struct strbuf *err)
1184 struct ref_transaction *transaction;
1185 struct strbuf sb = STRBUF_INIT;
1186 const char *nl;
1187 int ret = 0;
1189 if (action) {
1190 strbuf_addstr(&sb, action);
1191 strbuf_addstr(&sb, ": ");
1194 nl = strchr(msg->buf, '\n');
1195 if (nl) {
1196 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1197 } else {
1198 strbuf_addbuf(&sb, msg);
1199 strbuf_addch(&sb, '\n');
1202 transaction = ref_transaction_begin(err);
1203 if (!transaction ||
1204 ref_transaction_update(transaction, "HEAD", new_head,
1205 old_head ? &old_head->object.oid : null_oid(),
1206 0, sb.buf, err) ||
1207 ref_transaction_commit(transaction, err)) {
1208 ret = -1;
1210 ref_transaction_free(transaction);
1211 strbuf_release(&sb);
1213 return ret;
1216 static int run_rewrite_hook(const struct object_id *oldoid,
1217 const struct object_id *newoid)
1219 struct child_process proc = CHILD_PROCESS_INIT;
1220 int code;
1221 struct strbuf sb = STRBUF_INIT;
1222 const char *hook_path = find_hook("post-rewrite");
1224 if (!hook_path)
1225 return 0;
1227 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1228 proc.in = -1;
1229 proc.stdout_to_stderr = 1;
1230 proc.trace2_hook_name = "post-rewrite";
1232 code = start_command(&proc);
1233 if (code)
1234 return code;
1235 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1236 sigchain_push(SIGPIPE, SIG_IGN);
1237 write_in_full(proc.in, sb.buf, sb.len);
1238 close(proc.in);
1239 strbuf_release(&sb);
1240 sigchain_pop(SIGPIPE);
1241 return finish_command(&proc);
1244 void commit_post_rewrite(struct repository *r,
1245 const struct commit *old_head,
1246 const struct object_id *new_head)
1248 struct notes_rewrite_cfg *cfg;
1250 cfg = init_copy_notes_for_rewrite("amend");
1251 if (cfg) {
1252 /* we are amending, so old_head is not NULL */
1253 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1254 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1256 run_rewrite_hook(&old_head->object.oid, new_head);
1259 static int run_prepare_commit_msg_hook(struct repository *r,
1260 struct strbuf *msg,
1261 const char *commit)
1263 int ret = 0;
1264 const char *name, *arg1 = NULL, *arg2 = NULL;
1266 name = git_path_commit_editmsg();
1267 if (write_message(msg->buf, msg->len, name, 0))
1268 return -1;
1270 if (commit) {
1271 arg1 = "commit";
1272 arg2 = commit;
1273 } else {
1274 arg1 = "message";
1276 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1277 arg1, arg2, NULL))
1278 ret = error(_("'prepare-commit-msg' hook failed"));
1280 return ret;
1283 static const char implicit_ident_advice_noconfig[] =
1284 N_("Your name and email address were configured automatically based\n"
1285 "on your username and hostname. Please check that they are accurate.\n"
1286 "You can suppress this message by setting them explicitly. Run the\n"
1287 "following command and follow the instructions in your editor to edit\n"
1288 "your configuration file:\n"
1289 "\n"
1290 " git config --global --edit\n"
1291 "\n"
1292 "After doing this, you may fix the identity used for this commit with:\n"
1293 "\n"
1294 " git commit --amend --reset-author\n");
1296 static const char implicit_ident_advice_config[] =
1297 N_("Your name and email address were configured automatically based\n"
1298 "on your username and hostname. Please check that they are accurate.\n"
1299 "You can suppress this message by setting them explicitly:\n"
1300 "\n"
1301 " git config --global user.name \"Your Name\"\n"
1302 " git config --global user.email you@example.com\n"
1303 "\n"
1304 "After doing this, you may fix the identity used for this commit with:\n"
1305 "\n"
1306 " git commit --amend --reset-author\n");
1308 static const char *implicit_ident_advice(void)
1310 char *user_config = interpolate_path("~/.gitconfig", 0);
1311 char *xdg_config = xdg_config_home("config");
1312 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1314 free(user_config);
1315 free(xdg_config);
1317 if (config_exists)
1318 return _(implicit_ident_advice_config);
1319 else
1320 return _(implicit_ident_advice_noconfig);
1324 void print_commit_summary(struct repository *r,
1325 const char *prefix,
1326 const struct object_id *oid,
1327 unsigned int flags)
1329 struct rev_info rev;
1330 struct commit *commit;
1331 struct strbuf format = STRBUF_INIT;
1332 const char *head;
1333 struct pretty_print_context pctx = {0};
1334 struct strbuf author_ident = STRBUF_INIT;
1335 struct strbuf committer_ident = STRBUF_INIT;
1336 struct ref_store *refs;
1338 commit = lookup_commit(r, oid);
1339 if (!commit)
1340 die(_("couldn't look up newly created commit"));
1341 if (repo_parse_commit(r, commit))
1342 die(_("could not parse newly created commit"));
1344 strbuf_addstr(&format, "format:%h] %s");
1346 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1347 &pctx);
1348 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1349 &pctx);
1350 if (strbuf_cmp(&author_ident, &committer_ident)) {
1351 strbuf_addstr(&format, "\n Author: ");
1352 strbuf_addbuf_percentquote(&format, &author_ident);
1354 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1355 struct strbuf date = STRBUF_INIT;
1357 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1358 strbuf_addstr(&format, "\n Date: ");
1359 strbuf_addbuf_percentquote(&format, &date);
1360 strbuf_release(&date);
1362 if (!committer_ident_sufficiently_given()) {
1363 strbuf_addstr(&format, "\n Committer: ");
1364 strbuf_addbuf_percentquote(&format, &committer_ident);
1365 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1366 strbuf_addch(&format, '\n');
1367 strbuf_addstr(&format, implicit_ident_advice());
1370 strbuf_release(&author_ident);
1371 strbuf_release(&committer_ident);
1373 repo_init_revisions(r, &rev, prefix);
1374 setup_revisions(0, NULL, &rev, NULL);
1376 rev.diff = 1;
1377 rev.diffopt.output_format =
1378 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1380 rev.verbose_header = 1;
1381 rev.show_root_diff = 1;
1382 get_commit_format(format.buf, &rev);
1383 rev.always_show_header = 0;
1384 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1385 diff_setup_done(&rev.diffopt);
1387 refs = get_main_ref_store(r);
1388 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1389 if (!head)
1390 die(_("unable to resolve HEAD after creating commit"));
1391 if (!strcmp(head, "HEAD"))
1392 head = _("detached HEAD");
1393 else
1394 skip_prefix(head, "refs/heads/", &head);
1395 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1396 _(" (root-commit)") : "");
1398 if (!log_tree_commit(&rev, commit)) {
1399 rev.always_show_header = 1;
1400 rev.use_terminator = 1;
1401 log_tree_commit(&rev, commit);
1404 release_revisions(&rev);
1405 strbuf_release(&format);
1408 static int parse_head(struct repository *r, struct commit **head)
1410 struct commit *current_head;
1411 struct object_id oid;
1413 if (repo_get_oid(r, "HEAD", &oid)) {
1414 current_head = NULL;
1415 } else {
1416 current_head = lookup_commit_reference(r, &oid);
1417 if (!current_head)
1418 return error(_("could not parse HEAD"));
1419 if (!oideq(&oid, &current_head->object.oid)) {
1420 warning(_("HEAD %s is not a commit!"),
1421 oid_to_hex(&oid));
1423 if (repo_parse_commit(r, current_head))
1424 return error(_("could not parse HEAD commit"));
1426 *head = current_head;
1428 return 0;
1432 * Try to commit without forking 'git commit'. In some cases we need
1433 * to run 'git commit' to display an error message
1435 * Returns:
1436 * -1 - error unable to commit
1437 * 0 - success
1438 * 1 - run 'git commit'
1440 static int try_to_commit(struct repository *r,
1441 struct strbuf *msg, const char *author,
1442 struct replay_opts *opts, unsigned int flags,
1443 struct object_id *oid)
1445 struct object_id tree;
1446 struct commit *current_head = NULL;
1447 struct commit_list *parents = NULL;
1448 struct commit_extra_header *extra = NULL;
1449 struct strbuf err = STRBUF_INIT;
1450 struct strbuf commit_msg = STRBUF_INIT;
1451 char *amend_author = NULL;
1452 const char *committer = NULL;
1453 const char *hook_commit = NULL;
1454 enum commit_msg_cleanup_mode cleanup;
1455 int res = 0;
1457 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1458 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1460 if (parse_head(r, &current_head))
1461 return -1;
1463 if (flags & AMEND_MSG) {
1464 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1465 const char *out_enc = get_commit_output_encoding();
1466 const char *message = repo_logmsg_reencode(r, current_head,
1467 NULL, out_enc);
1469 if (!msg) {
1470 const char *orig_message = NULL;
1472 find_commit_subject(message, &orig_message);
1473 msg = &commit_msg;
1474 strbuf_addstr(msg, orig_message);
1475 hook_commit = "HEAD";
1477 author = amend_author = get_author(message);
1478 repo_unuse_commit_buffer(r, current_head,
1479 message);
1480 if (!author) {
1481 res = error(_("unable to parse commit author"));
1482 goto out;
1484 parents = copy_commit_list(current_head->parents);
1485 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1486 } else if (current_head &&
1487 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1488 commit_list_insert(current_head, &parents);
1491 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1492 res = error(_("git write-tree failed to write a tree"));
1493 goto out;
1496 if (!(flags & ALLOW_EMPTY)) {
1497 struct commit *first_parent = current_head;
1499 if (flags & AMEND_MSG) {
1500 if (current_head->parents) {
1501 first_parent = current_head->parents->item;
1502 if (repo_parse_commit(r, first_parent)) {
1503 res = error(_("could not parse HEAD commit"));
1504 goto out;
1506 } else {
1507 first_parent = NULL;
1510 if (oideq(first_parent
1511 ? get_commit_tree_oid(first_parent)
1512 : the_hash_algo->empty_tree,
1513 &tree)) {
1514 res = 1; /* run 'git commit' to display error message */
1515 goto out;
1519 if (hook_exists("prepare-commit-msg")) {
1520 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1521 if (res)
1522 goto out;
1523 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1524 2048) < 0) {
1525 res = error_errno(_("unable to read commit message "
1526 "from '%s'"),
1527 git_path_commit_editmsg());
1528 goto out;
1530 msg = &commit_msg;
1533 if (flags & CLEANUP_MSG)
1534 cleanup = COMMIT_MSG_CLEANUP_ALL;
1535 else if (flags & VERBATIM_MSG)
1536 cleanup = COMMIT_MSG_CLEANUP_NONE;
1537 else if ((opts->signoff || opts->record_origin) &&
1538 !opts->explicit_cleanup)
1539 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1540 else
1541 cleanup = opts->default_msg_cleanup;
1543 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1544 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1545 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1546 res = 1; /* run 'git commit' to display error message */
1547 goto out;
1550 if (opts->committer_date_is_author_date) {
1551 struct ident_split id;
1552 struct strbuf date = STRBUF_INIT;
1554 if (!opts->ignore_date) {
1555 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1556 res = error(_("invalid author identity '%s'"),
1557 author);
1558 goto out;
1560 if (!id.date_begin) {
1561 res = error(_(
1562 "corrupt author: missing date information"));
1563 goto out;
1565 strbuf_addf(&date, "@%.*s %.*s",
1566 (int)(id.date_end - id.date_begin),
1567 id.date_begin,
1568 (int)(id.tz_end - id.tz_begin),
1569 id.tz_begin);
1570 } else {
1571 reset_ident_date();
1573 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1574 getenv("GIT_COMMITTER_EMAIL"),
1575 WANT_COMMITTER_IDENT,
1576 opts->ignore_date ? NULL : date.buf,
1577 IDENT_STRICT);
1578 strbuf_release(&date);
1579 } else {
1580 reset_ident_date();
1583 if (opts->ignore_date) {
1584 struct ident_split id;
1585 char *name, *email;
1587 if (split_ident_line(&id, author, strlen(author)) < 0) {
1588 error(_("invalid author identity '%s'"), author);
1589 goto out;
1591 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1592 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1593 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1594 IDENT_STRICT);
1595 free(name);
1596 free(email);
1599 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1600 author, committer, opts->gpg_sign, extra)) {
1601 res = error(_("failed to write commit object"));
1602 goto out;
1605 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1606 msg, &err)) {
1607 res = error("%s", err.buf);
1608 goto out;
1611 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1612 if (flags & AMEND_MSG)
1613 commit_post_rewrite(r, current_head, oid);
1615 out:
1616 free_commit_extra_headers(extra);
1617 strbuf_release(&err);
1618 strbuf_release(&commit_msg);
1619 free(amend_author);
1621 return res;
1624 static int write_rebase_head(struct object_id *oid)
1626 if (update_ref("rebase", "REBASE_HEAD", oid,
1627 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1628 return error(_("could not update %s"), "REBASE_HEAD");
1630 return 0;
1633 static int do_commit(struct repository *r,
1634 const char *msg_file, const char *author,
1635 struct replay_opts *opts, unsigned int flags,
1636 struct object_id *oid)
1638 int res = 1;
1640 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1641 struct object_id oid;
1642 struct strbuf sb = STRBUF_INIT;
1644 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1645 return error_errno(_("unable to read commit message "
1646 "from '%s'"),
1647 msg_file);
1649 res = try_to_commit(r, msg_file ? &sb : NULL,
1650 author, opts, flags, &oid);
1651 strbuf_release(&sb);
1652 if (!res) {
1653 refs_delete_ref(get_main_ref_store(r), "",
1654 "CHERRY_PICK_HEAD", NULL, 0);
1655 unlink(git_path_merge_msg(r));
1656 if (!is_rebase_i(opts))
1657 print_commit_summary(r, NULL, &oid,
1658 SUMMARY_SHOW_AUTHOR_DATE);
1659 return res;
1662 if (res == 1) {
1663 if (is_rebase_i(opts) && oid)
1664 if (write_rebase_head(oid))
1665 return -1;
1666 return run_git_commit(msg_file, opts, flags);
1669 return res;
1672 static int is_original_commit_empty(struct commit *commit)
1674 const struct object_id *ptree_oid;
1676 if (repo_parse_commit(the_repository, commit))
1677 return error(_("could not parse commit %s"),
1678 oid_to_hex(&commit->object.oid));
1679 if (commit->parents) {
1680 struct commit *parent = commit->parents->item;
1681 if (repo_parse_commit(the_repository, parent))
1682 return error(_("could not parse parent commit %s"),
1683 oid_to_hex(&parent->object.oid));
1684 ptree_oid = get_commit_tree_oid(parent);
1685 } else {
1686 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1689 return oideq(ptree_oid, get_commit_tree_oid(commit));
1693 * Should empty commits be allowed? Return status:
1694 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1695 * 0: Halt on empty commit
1696 * 1: Allow empty commit
1697 * 2: Drop empty commit
1699 static int allow_empty(struct repository *r,
1700 struct replay_opts *opts,
1701 struct commit *commit)
1703 int index_unchanged, originally_empty;
1706 * Four cases:
1708 * (1) we do not allow empty at all and error out.
1710 * (2) we allow ones that were initially empty, and
1711 * just drop the ones that become empty
1713 * (3) we allow ones that were initially empty, but
1714 * halt for the ones that become empty;
1716 * (4) we allow both.
1718 if (!opts->allow_empty)
1719 return 0; /* let "git commit" barf as necessary */
1721 index_unchanged = is_index_unchanged(r);
1722 if (index_unchanged < 0)
1723 return index_unchanged;
1724 if (!index_unchanged)
1725 return 0; /* we do not have to say --allow-empty */
1727 if (opts->keep_redundant_commits)
1728 return 1;
1730 originally_empty = is_original_commit_empty(commit);
1731 if (originally_empty < 0)
1732 return originally_empty;
1733 if (originally_empty)
1734 return 1;
1735 else if (opts->drop_redundant_commits)
1736 return 2;
1737 else
1738 return 0;
1741 static struct {
1742 char c;
1743 const char *str;
1744 } todo_command_info[] = {
1745 [TODO_PICK] = { 'p', "pick" },
1746 [TODO_REVERT] = { 0, "revert" },
1747 [TODO_EDIT] = { 'e', "edit" },
1748 [TODO_REWORD] = { 'r', "reword" },
1749 [TODO_FIXUP] = { 'f', "fixup" },
1750 [TODO_SQUASH] = { 's', "squash" },
1751 [TODO_EXEC] = { 'x', "exec" },
1752 [TODO_BREAK] = { 'b', "break" },
1753 [TODO_LABEL] = { 'l', "label" },
1754 [TODO_RESET] = { 't', "reset" },
1755 [TODO_MERGE] = { 'm', "merge" },
1756 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1757 [TODO_NOOP] = { 0, "noop" },
1758 [TODO_DROP] = { 'd', "drop" },
1759 [TODO_COMMENT] = { 0, NULL },
1762 static const char *command_to_string(const enum todo_command command)
1764 if (command < TODO_COMMENT)
1765 return todo_command_info[command].str;
1766 die(_("unknown command: %d"), command);
1769 static char command_to_char(const enum todo_command command)
1771 if (command < TODO_COMMENT)
1772 return todo_command_info[command].c;
1773 return comment_line_char;
1776 static int is_noop(const enum todo_command command)
1778 return TODO_NOOP <= command;
1781 static int is_fixup(enum todo_command command)
1783 return command == TODO_FIXUP || command == TODO_SQUASH;
1786 /* Does this command create a (non-merge) commit? */
1787 static int is_pick_or_similar(enum todo_command command)
1789 switch (command) {
1790 case TODO_PICK:
1791 case TODO_REVERT:
1792 case TODO_EDIT:
1793 case TODO_REWORD:
1794 case TODO_FIXUP:
1795 case TODO_SQUASH:
1796 return 1;
1797 default:
1798 return 0;
1802 enum todo_item_flags {
1803 TODO_EDIT_MERGE_MSG = (1 << 0),
1804 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1805 TODO_EDIT_FIXUP_MSG = (1 << 2),
1808 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1809 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1810 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1811 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1812 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1814 static int is_fixup_flag(enum todo_command command, unsigned flag)
1816 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1817 (flag & TODO_EDIT_FIXUP_MSG));
1821 * Wrapper around strbuf_add_commented_lines() which avoids double
1822 * commenting commit subjects.
1824 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1826 const char *s = str;
1827 while (len > 0 && s[0] == comment_line_char) {
1828 size_t count;
1829 const char *n = memchr(s, '\n', len);
1830 if (!n)
1831 count = len;
1832 else
1833 count = n - s + 1;
1834 strbuf_add(buf, s, count);
1835 s += count;
1836 len -= count;
1838 strbuf_add_commented_lines(buf, s, len);
1841 /* Does the current fixup chain contain a squash command? */
1842 static int seen_squash(struct replay_opts *opts)
1844 return starts_with(opts->current_fixups.buf, "squash") ||
1845 strstr(opts->current_fixups.buf, "\nsquash");
1848 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1850 strbuf_setlen(buf1, 2);
1851 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1852 strbuf_addch(buf1, '\n');
1853 strbuf_setlen(buf2, 2);
1854 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1855 strbuf_addch(buf2, '\n');
1859 * Comment out any un-commented commit messages, updating the message comments
1860 * to say they will be skipped but do not comment out the empty lines that
1861 * surround commit messages and their comments.
1863 static void update_squash_message_for_fixup(struct strbuf *msg)
1865 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1866 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1867 const char *s, *start;
1868 char *orig_msg;
1869 size_t orig_msg_len;
1870 int i = 1;
1872 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1873 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1874 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1875 while (s) {
1876 const char *next;
1877 size_t off;
1878 if (skip_prefix(s, buf1.buf, &next)) {
1880 * Copy the last message, preserving the blank line
1881 * preceding the current line
1883 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1884 copy_lines(msg, start, s - start - off);
1885 if (off)
1886 strbuf_addch(msg, '\n');
1888 * The next message needs to be commented out but the
1889 * message header is already commented out so just copy
1890 * it and the blank line that follows it.
1892 strbuf_addbuf(msg, &buf2);
1893 if (*next == '\n')
1894 strbuf_addch(msg, *next++);
1895 start = s = next;
1896 copy_lines = add_commented_lines;
1897 update_comment_bufs(&buf1, &buf2, ++i);
1898 } else if (skip_prefix(s, buf2.buf, &next)) {
1899 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1900 copy_lines(msg, start, s - start - off);
1901 start = s - off;
1902 s = next;
1903 copy_lines = strbuf_add;
1904 update_comment_bufs(&buf1, &buf2, ++i);
1905 } else {
1906 s = strchr(s, '\n');
1907 if (s)
1908 s++;
1911 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1912 free(orig_msg);
1913 strbuf_release(&buf1);
1914 strbuf_release(&buf2);
1917 static int append_squash_message(struct strbuf *buf, const char *body,
1918 enum todo_command command, struct replay_opts *opts,
1919 unsigned flag)
1921 const char *fixup_msg;
1922 size_t commented_len = 0, fixup_off;
1924 * amend is non-interactive and not normally used with fixup!
1925 * or squash! commits, so only comment out those subjects when
1926 * squashing commit messages.
1928 if (starts_with(body, "amend!") ||
1929 ((command == TODO_SQUASH || seen_squash(opts)) &&
1930 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1931 commented_len = commit_subject_length(body);
1933 strbuf_addf(buf, "\n%c ", comment_line_char);
1934 strbuf_addf(buf, _(nth_commit_msg_fmt),
1935 ++opts->current_fixup_count + 1);
1936 strbuf_addstr(buf, "\n\n");
1937 strbuf_add_commented_lines(buf, body, commented_len);
1938 /* buf->buf may be reallocated so store an offset into the buffer */
1939 fixup_off = buf->len;
1940 strbuf_addstr(buf, body + commented_len);
1942 /* fixup -C after squash behaves like squash */
1943 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1945 * We're replacing the commit message so we need to
1946 * append the Signed-off-by: trailer if the user
1947 * requested '--signoff'.
1949 if (opts->signoff)
1950 append_signoff(buf, 0, 0);
1952 if ((command == TODO_FIXUP) &&
1953 (flag & TODO_REPLACE_FIXUP_MSG) &&
1954 (file_exists(rebase_path_fixup_msg()) ||
1955 !file_exists(rebase_path_squash_msg()))) {
1956 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1957 if (write_message(fixup_msg, strlen(fixup_msg),
1958 rebase_path_fixup_msg(), 0) < 0)
1959 return error(_("cannot write '%s'"),
1960 rebase_path_fixup_msg());
1961 } else {
1962 unlink(rebase_path_fixup_msg());
1964 } else {
1965 unlink(rebase_path_fixup_msg());
1968 return 0;
1971 static int update_squash_messages(struct repository *r,
1972 enum todo_command command,
1973 struct commit *commit,
1974 struct replay_opts *opts,
1975 unsigned flag)
1977 struct strbuf buf = STRBUF_INIT;
1978 int res = 0;
1979 const char *message, *body;
1980 const char *encoding = get_commit_output_encoding();
1982 if (opts->current_fixup_count > 0) {
1983 struct strbuf header = STRBUF_INIT;
1984 char *eol;
1986 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1987 return error(_("could not read '%s'"),
1988 rebase_path_squash_msg());
1990 eol = buf.buf[0] != comment_line_char ?
1991 buf.buf : strchrnul(buf.buf, '\n');
1993 strbuf_addf(&header, "%c ", comment_line_char);
1994 strbuf_addf(&header, _(combined_commit_msg_fmt),
1995 opts->current_fixup_count + 2);
1996 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1997 strbuf_release(&header);
1998 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1999 update_squash_message_for_fixup(&buf);
2000 } else {
2001 struct object_id head;
2002 struct commit *head_commit;
2003 const char *head_message, *body;
2005 if (repo_get_oid(r, "HEAD", &head))
2006 return error(_("need a HEAD to fixup"));
2007 if (!(head_commit = lookup_commit_reference(r, &head)))
2008 return error(_("could not read HEAD"));
2009 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2010 encoding)))
2011 return error(_("could not read HEAD's commit message"));
2013 find_commit_subject(head_message, &body);
2014 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2015 rebase_path_fixup_msg(), 0) < 0) {
2016 repo_unuse_commit_buffer(r, head_commit, head_message);
2017 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2019 strbuf_addf(&buf, "%c ", comment_line_char);
2020 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2021 strbuf_addf(&buf, "\n%c ", comment_line_char);
2022 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2023 _(skip_first_commit_msg_str) :
2024 _(first_commit_msg_str));
2025 strbuf_addstr(&buf, "\n\n");
2026 if (is_fixup_flag(command, flag))
2027 strbuf_add_commented_lines(&buf, body, strlen(body));
2028 else
2029 strbuf_addstr(&buf, body);
2031 repo_unuse_commit_buffer(r, head_commit, head_message);
2034 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2035 return error(_("could not read commit message of %s"),
2036 oid_to_hex(&commit->object.oid));
2037 find_commit_subject(message, &body);
2039 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2040 res = append_squash_message(&buf, body, command, opts, flag);
2041 } else if (command == TODO_FIXUP) {
2042 strbuf_addf(&buf, "\n%c ", comment_line_char);
2043 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2044 ++opts->current_fixup_count + 1);
2045 strbuf_addstr(&buf, "\n\n");
2046 strbuf_add_commented_lines(&buf, body, strlen(body));
2047 } else
2048 return error(_("unknown command: %d"), command);
2049 repo_unuse_commit_buffer(r, commit, message);
2051 if (!res)
2052 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2054 strbuf_release(&buf);
2056 if (!res) {
2057 strbuf_addf(&opts->current_fixups, "%s%s %s",
2058 opts->current_fixups.len ? "\n" : "",
2059 command_to_string(command),
2060 oid_to_hex(&commit->object.oid));
2061 res = write_message(opts->current_fixups.buf,
2062 opts->current_fixups.len,
2063 rebase_path_current_fixups(), 0);
2066 return res;
2069 static void flush_rewritten_pending(void)
2071 struct strbuf buf = STRBUF_INIT;
2072 struct object_id newoid;
2073 FILE *out;
2075 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2076 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2077 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2078 char *bol = buf.buf, *eol;
2080 while (*bol) {
2081 eol = strchrnul(bol, '\n');
2082 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2083 bol, oid_to_hex(&newoid));
2084 if (!*eol)
2085 break;
2086 bol = eol + 1;
2088 fclose(out);
2089 unlink(rebase_path_rewritten_pending());
2091 strbuf_release(&buf);
2094 static void record_in_rewritten(struct object_id *oid,
2095 enum todo_command next_command)
2097 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2099 if (!out)
2100 return;
2102 fprintf(out, "%s\n", oid_to_hex(oid));
2103 fclose(out);
2105 if (!is_fixup(next_command))
2106 flush_rewritten_pending();
2109 static int should_edit(struct replay_opts *opts) {
2110 if (opts->edit < 0)
2112 * Note that we only handle the case of non-conflicted
2113 * commits; continue_single_pick() handles the conflicted
2114 * commits itself instead of calling this function.
2116 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2117 return opts->edit;
2120 static void refer_to_commit(struct replay_opts *opts,
2121 struct strbuf *msgbuf, struct commit *commit)
2123 if (opts->commit_use_reference) {
2124 struct pretty_print_context ctx = {
2125 .abbrev = DEFAULT_ABBREV,
2126 .date_mode.type = DATE_SHORT,
2128 repo_format_commit_message(the_repository, commit,
2129 "%h (%s, %ad)", msgbuf, &ctx);
2130 } else {
2131 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2135 static int do_pick_commit(struct repository *r,
2136 struct todo_item *item,
2137 struct replay_opts *opts,
2138 int final_fixup, int *check_todo)
2140 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2141 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2142 struct object_id head;
2143 struct commit *base, *next, *parent;
2144 const char *base_label, *next_label;
2145 char *author = NULL;
2146 struct commit_message msg = { NULL, NULL, NULL, NULL };
2147 struct strbuf msgbuf = STRBUF_INIT;
2148 int res, unborn = 0, reword = 0, allow, drop_commit;
2149 enum todo_command command = item->command;
2150 struct commit *commit = item->commit;
2152 if (opts->no_commit) {
2154 * We do not intend to commit immediately. We just want to
2155 * merge the differences in, so let's compute the tree
2156 * that represents the "current" state for the merge machinery
2157 * to work on.
2159 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2160 return error(_("your index file is unmerged."));
2161 } else {
2162 unborn = repo_get_oid(r, "HEAD", &head);
2163 /* Do we want to generate a root commit? */
2164 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2165 oideq(&head, &opts->squash_onto)) {
2166 if (is_fixup(command))
2167 return error(_("cannot fixup root commit"));
2168 flags |= CREATE_ROOT_COMMIT;
2169 unborn = 1;
2170 } else if (unborn)
2171 oidcpy(&head, the_hash_algo->empty_tree);
2172 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2173 NULL, 0))
2174 return error_dirty_index(r, opts);
2176 discard_index(r->index);
2178 if (!commit->parents)
2179 parent = NULL;
2180 else if (commit->parents->next) {
2181 /* Reverting or cherry-picking a merge commit */
2182 int cnt;
2183 struct commit_list *p;
2185 if (!opts->mainline)
2186 return error(_("commit %s is a merge but no -m option was given."),
2187 oid_to_hex(&commit->object.oid));
2189 for (cnt = 1, p = commit->parents;
2190 cnt != opts->mainline && p;
2191 cnt++)
2192 p = p->next;
2193 if (cnt != opts->mainline || !p)
2194 return error(_("commit %s does not have parent %d"),
2195 oid_to_hex(&commit->object.oid), opts->mainline);
2196 parent = p->item;
2197 } else if (1 < opts->mainline)
2199 * Non-first parent explicitly specified as mainline for
2200 * non-merge commit
2202 return error(_("commit %s does not have parent %d"),
2203 oid_to_hex(&commit->object.oid), opts->mainline);
2204 else
2205 parent = commit->parents->item;
2207 if (get_message(commit, &msg) != 0)
2208 return error(_("cannot get commit message for %s"),
2209 oid_to_hex(&commit->object.oid));
2211 if (opts->allow_ff && !is_fixup(command) &&
2212 ((parent && oideq(&parent->object.oid, &head)) ||
2213 (!parent && unborn))) {
2214 if (is_rebase_i(opts))
2215 write_author_script(msg.message);
2216 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2217 opts);
2218 if (res || command != TODO_REWORD)
2219 goto leave;
2220 reword = 1;
2221 msg_file = NULL;
2222 goto fast_forward_edit;
2224 if (parent && repo_parse_commit(r, parent) < 0)
2225 /* TRANSLATORS: The first %s will be a "todo" command like
2226 "revert" or "pick", the second %s a SHA1. */
2227 return error(_("%s: cannot parse parent commit %s"),
2228 command_to_string(command),
2229 oid_to_hex(&parent->object.oid));
2232 * "commit" is an existing commit. We would want to apply
2233 * the difference it introduces since its first parent "prev"
2234 * on top of the current HEAD if we are cherry-pick. Or the
2235 * reverse of it if we are revert.
2238 if (command == TODO_REVERT) {
2239 base = commit;
2240 base_label = msg.label;
2241 next = parent;
2242 next_label = msg.parent_label;
2243 if (opts->commit_use_reference) {
2244 strbuf_addstr(&msgbuf,
2245 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2246 } else {
2247 strbuf_addstr(&msgbuf, "Revert \"");
2248 strbuf_addstr(&msgbuf, msg.subject);
2249 strbuf_addstr(&msgbuf, "\"");
2251 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2252 refer_to_commit(opts, &msgbuf, commit);
2254 if (commit->parents && commit->parents->next) {
2255 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2256 refer_to_commit(opts, &msgbuf, parent);
2258 strbuf_addstr(&msgbuf, ".\n");
2259 } else {
2260 const char *p;
2262 base = parent;
2263 base_label = msg.parent_label;
2264 next = commit;
2265 next_label = msg.label;
2267 /* Append the commit log message to msgbuf. */
2268 if (find_commit_subject(msg.message, &p))
2269 strbuf_addstr(&msgbuf, p);
2271 if (opts->record_origin) {
2272 strbuf_complete_line(&msgbuf);
2273 if (!has_conforming_footer(&msgbuf, NULL, 0))
2274 strbuf_addch(&msgbuf, '\n');
2275 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2276 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2277 strbuf_addstr(&msgbuf, ")\n");
2279 if (!is_fixup(command))
2280 author = get_author(msg.message);
2283 if (command == TODO_REWORD)
2284 reword = 1;
2285 else if (is_fixup(command)) {
2286 if (update_squash_messages(r, command, commit,
2287 opts, item->flags)) {
2288 res = -1;
2289 goto leave;
2291 flags |= AMEND_MSG;
2292 if (!final_fixup)
2293 msg_file = rebase_path_squash_msg();
2294 else if (file_exists(rebase_path_fixup_msg())) {
2295 flags |= VERBATIM_MSG;
2296 msg_file = rebase_path_fixup_msg();
2297 } else {
2298 const char *dest = git_path_squash_msg(r);
2299 unlink(dest);
2300 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2301 res = error(_("could not rename '%s' to '%s'"),
2302 rebase_path_squash_msg(), dest);
2303 goto leave;
2305 unlink(git_path_merge_msg(r));
2306 msg_file = dest;
2307 flags |= EDIT_MSG;
2311 if (opts->signoff && !is_fixup(command))
2312 append_signoff(&msgbuf, 0, 0);
2314 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2315 res = -1;
2316 else if (!opts->strategy ||
2317 !strcmp(opts->strategy, "recursive") ||
2318 !strcmp(opts->strategy, "ort") ||
2319 command == TODO_REVERT) {
2320 res = do_recursive_merge(r, base, next, base_label, next_label,
2321 &head, &msgbuf, opts);
2322 if (res < 0)
2323 goto leave;
2325 res |= write_message(msgbuf.buf, msgbuf.len,
2326 git_path_merge_msg(r), 0);
2327 } else {
2328 struct commit_list *common = NULL;
2329 struct commit_list *remotes = NULL;
2331 res = write_message(msgbuf.buf, msgbuf.len,
2332 git_path_merge_msg(r), 0);
2334 commit_list_insert(base, &common);
2335 commit_list_insert(next, &remotes);
2336 res |= try_merge_command(r, opts->strategy,
2337 opts->xopts.nr, opts->xopts.v,
2338 common, oid_to_hex(&head), remotes);
2339 free_commit_list(common);
2340 free_commit_list(remotes);
2344 * If the merge was clean or if it failed due to conflict, we write
2345 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2346 * However, if the merge did not even start, then we don't want to
2347 * write it at all.
2349 if ((command == TODO_PICK || command == TODO_REWORD ||
2350 command == TODO_EDIT) && !opts->no_commit &&
2351 (res == 0 || res == 1) &&
2352 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2353 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2354 res = -1;
2355 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2356 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2357 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2358 res = -1;
2360 if (res) {
2361 error(command == TODO_REVERT
2362 ? _("could not revert %s... %s")
2363 : _("could not apply %s... %s"),
2364 short_commit_name(commit), msg.subject);
2365 print_advice(r, res == 1, opts);
2366 repo_rerere(r, opts->allow_rerere_auto);
2367 goto leave;
2370 drop_commit = 0;
2371 allow = allow_empty(r, opts, commit);
2372 if (allow < 0) {
2373 res = allow;
2374 goto leave;
2375 } else if (allow == 1) {
2376 flags |= ALLOW_EMPTY;
2377 } else if (allow == 2) {
2378 drop_commit = 1;
2379 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2380 NULL, 0);
2381 unlink(git_path_merge_msg(r));
2382 unlink(git_path_auto_merge(r));
2383 fprintf(stderr,
2384 _("dropping %s %s -- patch contents already upstream\n"),
2385 oid_to_hex(&commit->object.oid), msg.subject);
2386 } /* else allow == 0 and there's nothing special to do */
2387 if (!opts->no_commit && !drop_commit) {
2388 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2389 res = do_commit(r, msg_file, author, opts, flags,
2390 commit? &commit->object.oid : NULL);
2391 else
2392 res = error(_("unable to parse commit author"));
2393 *check_todo = !!(flags & EDIT_MSG);
2394 if (!res && reword) {
2395 fast_forward_edit:
2396 res = run_git_commit(NULL, opts, EDIT_MSG |
2397 VERIFY_MSG | AMEND_MSG |
2398 (flags & ALLOW_EMPTY));
2399 *check_todo = 1;
2404 if (!res && final_fixup) {
2405 unlink(rebase_path_fixup_msg());
2406 unlink(rebase_path_squash_msg());
2407 unlink(rebase_path_current_fixups());
2408 strbuf_reset(&opts->current_fixups);
2409 opts->current_fixup_count = 0;
2412 leave:
2413 free_message(commit, &msg);
2414 free(author);
2415 strbuf_release(&msgbuf);
2416 update_abort_safety_file();
2418 return res;
2421 static int prepare_revs(struct replay_opts *opts)
2424 * picking (but not reverting) ranges (but not individual revisions)
2425 * should be done in reverse
2427 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2428 opts->revs->reverse ^= 1;
2430 if (prepare_revision_walk(opts->revs))
2431 return error(_("revision walk setup failed"));
2433 return 0;
2436 static int read_and_refresh_cache(struct repository *r,
2437 struct replay_opts *opts)
2439 struct lock_file index_lock = LOCK_INIT;
2440 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2441 if (repo_read_index(r) < 0) {
2442 rollback_lock_file(&index_lock);
2443 return error(_("git %s: failed to read the index"),
2444 action_name(opts));
2446 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2448 if (index_fd >= 0) {
2449 if (write_locked_index(r->index, &index_lock,
2450 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2451 return error(_("git %s: failed to refresh the index"),
2452 action_name(opts));
2457 * If we are resolving merges in any way other than "ort", then
2458 * expand the sparse index.
2460 if (opts->strategy && strcmp(opts->strategy, "ort"))
2461 ensure_full_index(r->index);
2462 return 0;
2465 void todo_list_release(struct todo_list *todo_list)
2467 strbuf_release(&todo_list->buf);
2468 FREE_AND_NULL(todo_list->items);
2469 todo_list->nr = todo_list->alloc = 0;
2472 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2474 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2475 todo_list->total_nr++;
2476 return todo_list->items + todo_list->nr++;
2479 const char *todo_item_get_arg(struct todo_list *todo_list,
2480 struct todo_item *item)
2482 return todo_list->buf.buf + item->arg_offset;
2485 static int is_command(enum todo_command command, const char **bol)
2487 const char *str = todo_command_info[command].str;
2488 const char nick = todo_command_info[command].c;
2489 const char *p = *bol;
2491 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2492 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2493 (*bol = p);
2496 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2498 switch (command) {
2499 case TODO_LABEL:
2501 * '#' is not a valid label as the merge command uses it to
2502 * separate merge parents from the commit subject.
2504 if (!strcmp(arg, "#") ||
2505 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2506 return error(_("'%s' is not a valid label"), arg);
2507 break;
2509 case TODO_UPDATE_REF:
2510 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2511 return error(_("'%s' is not a valid refname"), arg);
2512 if (check_refname_format(arg, 0))
2513 return error(_("update-ref requires a fully qualified "
2514 "refname e.g. refs/heads/%s"), arg);
2515 break;
2517 default:
2518 BUG("unexpected todo_command");
2521 return 0;
2524 static int parse_insn_line(struct repository *r, struct todo_item *item,
2525 const char *buf, const char *bol, char *eol)
2527 struct object_id commit_oid;
2528 char *end_of_object_name;
2529 int i, saved, status, padding;
2531 item->flags = 0;
2533 /* left-trim */
2534 bol += strspn(bol, " \t");
2536 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2537 item->command = TODO_COMMENT;
2538 item->commit = NULL;
2539 item->arg_offset = bol - buf;
2540 item->arg_len = eol - bol;
2541 return 0;
2544 for (i = 0; i < TODO_COMMENT; i++)
2545 if (is_command(i, &bol)) {
2546 item->command = i;
2547 break;
2549 if (i >= TODO_COMMENT)
2550 return error(_("invalid command '%.*s'"),
2551 (int)strcspn(bol, " \t\r\n"), bol);
2553 /* Eat up extra spaces/ tabs before object name */
2554 padding = strspn(bol, " \t");
2555 bol += padding;
2557 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2558 if (bol != eol)
2559 return error(_("%s does not accept arguments: '%s'"),
2560 command_to_string(item->command), bol);
2561 item->commit = NULL;
2562 item->arg_offset = bol - buf;
2563 item->arg_len = eol - bol;
2564 return 0;
2567 if (!padding)
2568 return error(_("missing arguments for %s"),
2569 command_to_string(item->command));
2571 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2572 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2573 int ret = 0;
2575 item->commit = NULL;
2576 item->arg_offset = bol - buf;
2577 item->arg_len = (int)(eol - bol);
2578 if (item->command == TODO_LABEL ||
2579 item->command == TODO_UPDATE_REF) {
2580 saved = *eol;
2581 *eol = '\0';
2582 ret = check_label_or_ref_arg(item->command, bol);
2583 *eol = saved;
2585 return ret;
2588 if (item->command == TODO_FIXUP) {
2589 if (skip_prefix(bol, "-C", &bol)) {
2590 bol += strspn(bol, " \t");
2591 item->flags |= TODO_REPLACE_FIXUP_MSG;
2592 } else if (skip_prefix(bol, "-c", &bol)) {
2593 bol += strspn(bol, " \t");
2594 item->flags |= TODO_EDIT_FIXUP_MSG;
2598 if (item->command == TODO_MERGE) {
2599 if (skip_prefix(bol, "-C", &bol))
2600 bol += strspn(bol, " \t");
2601 else if (skip_prefix(bol, "-c", &bol)) {
2602 bol += strspn(bol, " \t");
2603 item->flags |= TODO_EDIT_MERGE_MSG;
2604 } else {
2605 item->flags |= TODO_EDIT_MERGE_MSG;
2606 item->commit = NULL;
2607 item->arg_offset = bol - buf;
2608 item->arg_len = (int)(eol - bol);
2609 return 0;
2613 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2614 saved = *end_of_object_name;
2615 *end_of_object_name = '\0';
2616 status = repo_get_oid(r, bol, &commit_oid);
2617 if (status < 0)
2618 error(_("could not parse '%s'"), bol); /* return later */
2619 *end_of_object_name = saved;
2621 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2622 item->arg_offset = bol - buf;
2623 item->arg_len = (int)(eol - bol);
2625 if (status < 0)
2626 return status;
2628 item->commit = lookup_commit_reference(r, &commit_oid);
2629 return item->commit ? 0 : -1;
2632 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2634 const char *todo_file, *bol;
2635 struct strbuf buf = STRBUF_INIT;
2636 int ret = 0;
2638 todo_file = git_path_todo_file();
2639 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2640 if (errno == ENOENT || errno == ENOTDIR)
2641 return -1;
2642 else
2643 return error_errno("unable to open '%s'", todo_file);
2645 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2646 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2647 *action = REPLAY_PICK;
2648 else if (is_command(TODO_REVERT, &bol) &&
2649 (*bol == ' ' || *bol == '\t'))
2650 *action = REPLAY_REVERT;
2651 else
2652 ret = -1;
2654 strbuf_release(&buf);
2656 return ret;
2659 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2660 struct todo_list *todo_list)
2662 struct todo_item *item;
2663 char *p = buf, *next_p;
2664 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2666 todo_list->current = todo_list->nr = 0;
2668 for (i = 1; *p; i++, p = next_p) {
2669 char *eol = strchrnul(p, '\n');
2671 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2673 if (p != eol && eol[-1] == '\r')
2674 eol--; /* strip Carriage Return */
2676 item = append_new_todo(todo_list);
2677 item->offset_in_buf = p - todo_list->buf.buf;
2678 if (parse_insn_line(r, item, buf, p, eol)) {
2679 res = error(_("invalid line %d: %.*s"),
2680 i, (int)(eol - p), p);
2681 item->command = TODO_COMMENT + 1;
2682 item->arg_offset = p - buf;
2683 item->arg_len = (int)(eol - p);
2684 item->commit = NULL;
2687 if (fixup_okay)
2688 ; /* do nothing */
2689 else if (is_fixup(item->command))
2690 return error(_("cannot '%s' without a previous commit"),
2691 command_to_string(item->command));
2692 else if (!is_noop(item->command))
2693 fixup_okay = 1;
2696 return res;
2699 static int count_commands(struct todo_list *todo_list)
2701 int count = 0, i;
2703 for (i = 0; i < todo_list->nr; i++)
2704 if (todo_list->items[i].command != TODO_COMMENT)
2705 count++;
2707 return count;
2710 static int get_item_line_offset(struct todo_list *todo_list, int index)
2712 return index < todo_list->nr ?
2713 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2716 static const char *get_item_line(struct todo_list *todo_list, int index)
2718 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2721 static int get_item_line_length(struct todo_list *todo_list, int index)
2723 return get_item_line_offset(todo_list, index + 1)
2724 - get_item_line_offset(todo_list, index);
2727 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2729 int fd;
2730 ssize_t len;
2732 fd = open(path, O_RDONLY);
2733 if (fd < 0)
2734 return error_errno(_("could not open '%s'"), path);
2735 len = strbuf_read(sb, fd, 0);
2736 close(fd);
2737 if (len < 0)
2738 return error(_("could not read '%s'."), path);
2739 return len;
2742 static int have_finished_the_last_pick(void)
2744 struct strbuf buf = STRBUF_INIT;
2745 const char *eol;
2746 const char *todo_path = git_path_todo_file();
2747 int ret = 0;
2749 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2750 if (errno == ENOENT) {
2751 return 0;
2752 } else {
2753 error_errno("unable to open '%s'", todo_path);
2754 return 0;
2757 /* If there is only one line then we are done */
2758 eol = strchr(buf.buf, '\n');
2759 if (!eol || !eol[1])
2760 ret = 1;
2762 strbuf_release(&buf);
2764 return ret;
2767 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2769 struct replay_opts opts = REPLAY_OPTS_INIT;
2770 int need_cleanup = 0;
2772 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2773 if (!refs_delete_ref(get_main_ref_store(r), "",
2774 "CHERRY_PICK_HEAD", NULL, 0) &&
2775 verbose)
2776 warning(_("cancelling a cherry picking in progress"));
2777 opts.action = REPLAY_PICK;
2778 need_cleanup = 1;
2781 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2782 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2783 NULL, 0) &&
2784 verbose)
2785 warning(_("cancelling a revert in progress"));
2786 opts.action = REPLAY_REVERT;
2787 need_cleanup = 1;
2790 unlink(git_path_auto_merge(r));
2792 if (!need_cleanup)
2793 return;
2795 if (!have_finished_the_last_pick())
2796 return;
2798 sequencer_remove_state(&opts);
2801 static void todo_list_write_total_nr(struct todo_list *todo_list)
2803 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2805 if (f) {
2806 fprintf(f, "%d\n", todo_list->total_nr);
2807 fclose(f);
2811 static int read_populate_todo(struct repository *r,
2812 struct todo_list *todo_list,
2813 struct replay_opts *opts)
2815 const char *todo_file = get_todo_path(opts);
2816 int res;
2818 strbuf_reset(&todo_list->buf);
2819 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2820 return -1;
2822 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2823 if (res) {
2824 if (is_rebase_i(opts))
2825 return error(_("please fix this using "
2826 "'git rebase --edit-todo'."));
2827 return error(_("unusable instruction sheet: '%s'"), todo_file);
2830 if (!todo_list->nr &&
2831 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2832 return error(_("no commits parsed."));
2834 if (!is_rebase_i(opts)) {
2835 enum todo_command valid =
2836 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2837 int i;
2839 for (i = 0; i < todo_list->nr; i++)
2840 if (valid == todo_list->items[i].command)
2841 continue;
2842 else if (valid == TODO_PICK)
2843 return error(_("cannot cherry-pick during a revert."));
2844 else
2845 return error(_("cannot revert during a cherry-pick."));
2848 if (is_rebase_i(opts)) {
2849 struct todo_list done = TODO_LIST_INIT;
2851 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2852 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2853 todo_list->done_nr = count_commands(&done);
2854 else
2855 todo_list->done_nr = 0;
2857 todo_list->total_nr = todo_list->done_nr
2858 + count_commands(todo_list);
2859 todo_list_release(&done);
2861 todo_list_write_total_nr(todo_list);
2864 return 0;
2867 static int git_config_string_dup(char **dest,
2868 const char *var, const char *value)
2870 if (!value)
2871 return config_error_nonbool(var);
2872 free(*dest);
2873 *dest = xstrdup(value);
2874 return 0;
2877 static int populate_opts_cb(const char *key, const char *value, void *data)
2879 struct replay_opts *opts = data;
2880 int error_flag = 1;
2882 if (!value)
2883 error_flag = 0;
2884 else if (!strcmp(key, "options.no-commit"))
2885 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2886 else if (!strcmp(key, "options.edit"))
2887 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2888 else if (!strcmp(key, "options.allow-empty"))
2889 opts->allow_empty =
2890 git_config_bool_or_int(key, value, &error_flag);
2891 else if (!strcmp(key, "options.allow-empty-message"))
2892 opts->allow_empty_message =
2893 git_config_bool_or_int(key, value, &error_flag);
2894 else if (!strcmp(key, "options.keep-redundant-commits"))
2895 opts->keep_redundant_commits =
2896 git_config_bool_or_int(key, value, &error_flag);
2897 else if (!strcmp(key, "options.signoff"))
2898 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2899 else if (!strcmp(key, "options.record-origin"))
2900 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2901 else if (!strcmp(key, "options.allow-ff"))
2902 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2903 else if (!strcmp(key, "options.mainline"))
2904 opts->mainline = git_config_int(key, value);
2905 else if (!strcmp(key, "options.strategy"))
2906 git_config_string_dup(&opts->strategy, key, value);
2907 else if (!strcmp(key, "options.gpg-sign"))
2908 git_config_string_dup(&opts->gpg_sign, key, value);
2909 else if (!strcmp(key, "options.strategy-option")) {
2910 strvec_push(&opts->xopts, value);
2911 } else if (!strcmp(key, "options.allow-rerere-auto"))
2912 opts->allow_rerere_auto =
2913 git_config_bool_or_int(key, value, &error_flag) ?
2914 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2915 else if (!strcmp(key, "options.default-msg-cleanup")) {
2916 opts->explicit_cleanup = 1;
2917 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2918 } else
2919 return error(_("invalid key: %s"), key);
2921 if (!error_flag)
2922 return error(_("invalid value for '%s': '%s'"), key, value);
2924 return 0;
2927 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2929 int i;
2930 int count;
2931 const char **argv;
2932 char *strategy_opts_string = raw_opts;
2934 if (*strategy_opts_string == ' ')
2935 strategy_opts_string++;
2937 count = split_cmdline(strategy_opts_string, &argv);
2938 if (count < 0)
2939 BUG("could not split '%s': %s", strategy_opts_string,
2940 split_cmdline_strerror(count));
2941 for (i = 0; i < count; i++) {
2942 const char *arg = argv[i];
2944 skip_prefix(arg, "--", &arg);
2945 strvec_push(&opts->xopts, arg);
2947 free(argv);
2950 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2952 strbuf_reset(buf);
2953 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2954 return;
2955 opts->strategy = strbuf_detach(buf, NULL);
2956 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2957 return;
2959 parse_strategy_opts(opts, buf->buf);
2962 static int read_populate_opts(struct replay_opts *opts)
2964 if (is_rebase_i(opts)) {
2965 struct strbuf buf = STRBUF_INIT;
2966 int ret = 0;
2968 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2969 READ_ONELINER_SKIP_IF_EMPTY)) {
2970 if (!starts_with(buf.buf, "-S"))
2971 strbuf_reset(&buf);
2972 else {
2973 free(opts->gpg_sign);
2974 opts->gpg_sign = xstrdup(buf.buf + 2);
2976 strbuf_reset(&buf);
2979 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2980 READ_ONELINER_SKIP_IF_EMPTY)) {
2981 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2982 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2983 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2984 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2985 strbuf_reset(&buf);
2988 if (file_exists(rebase_path_verbose()))
2989 opts->verbose = 1;
2991 if (file_exists(rebase_path_quiet()))
2992 opts->quiet = 1;
2994 if (file_exists(rebase_path_signoff())) {
2995 opts->allow_ff = 0;
2996 opts->signoff = 1;
2999 if (file_exists(rebase_path_cdate_is_adate())) {
3000 opts->allow_ff = 0;
3001 opts->committer_date_is_author_date = 1;
3004 if (file_exists(rebase_path_ignore_date())) {
3005 opts->allow_ff = 0;
3006 opts->ignore_date = 1;
3009 if (file_exists(rebase_path_reschedule_failed_exec()))
3010 opts->reschedule_failed_exec = 1;
3011 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3012 opts->reschedule_failed_exec = 0;
3014 if (file_exists(rebase_path_drop_redundant_commits()))
3015 opts->drop_redundant_commits = 1;
3017 if (file_exists(rebase_path_keep_redundant_commits()))
3018 opts->keep_redundant_commits = 1;
3020 read_strategy_opts(opts, &buf);
3021 strbuf_reset(&buf);
3023 if (read_oneliner(&opts->current_fixups,
3024 rebase_path_current_fixups(),
3025 READ_ONELINER_SKIP_IF_EMPTY)) {
3026 const char *p = opts->current_fixups.buf;
3027 opts->current_fixup_count = 1;
3028 while ((p = strchr(p, '\n'))) {
3029 opts->current_fixup_count++;
3030 p++;
3034 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3035 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3036 ret = error(_("unusable squash-onto"));
3037 goto done_rebase_i;
3039 opts->have_squash_onto = 1;
3042 done_rebase_i:
3043 strbuf_release(&buf);
3044 return ret;
3047 if (!file_exists(git_path_opts_file()))
3048 return 0;
3050 * The function git_parse_source(), called from git_config_from_file(),
3051 * may die() in case of a syntactically incorrect file. We do not care
3052 * about this case, though, because we wrote that file ourselves, so we
3053 * are pretty certain that it is syntactically correct.
3055 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3056 return error(_("malformed options sheet: '%s'"),
3057 git_path_opts_file());
3058 return 0;
3061 static void write_strategy_opts(struct replay_opts *opts)
3063 struct strbuf buf = STRBUF_INIT;
3066 * Quote strategy options so that they can be read correctly
3067 * by split_cmdline().
3069 quote_cmdline(&buf, opts->xopts.v);
3070 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3071 strbuf_release(&buf);
3074 int write_basic_state(struct replay_opts *opts, const char *head_name,
3075 struct commit *onto, const struct object_id *orig_head)
3077 if (head_name)
3078 write_file(rebase_path_head_name(), "%s\n", head_name);
3079 if (onto)
3080 write_file(rebase_path_onto(), "%s\n",
3081 oid_to_hex(&onto->object.oid));
3082 if (orig_head)
3083 write_file(rebase_path_orig_head(), "%s\n",
3084 oid_to_hex(orig_head));
3086 if (opts->quiet)
3087 write_file(rebase_path_quiet(), "%s", "");
3088 if (opts->verbose)
3089 write_file(rebase_path_verbose(), "%s", "");
3090 if (opts->strategy)
3091 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3092 if (opts->xopts.nr > 0)
3093 write_strategy_opts(opts);
3095 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3096 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3097 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3098 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3100 if (opts->gpg_sign)
3101 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3102 if (opts->signoff)
3103 write_file(rebase_path_signoff(), "--signoff\n");
3104 if (opts->drop_redundant_commits)
3105 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3106 if (opts->keep_redundant_commits)
3107 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3108 if (opts->committer_date_is_author_date)
3109 write_file(rebase_path_cdate_is_adate(), "%s", "");
3110 if (opts->ignore_date)
3111 write_file(rebase_path_ignore_date(), "%s", "");
3112 if (opts->reschedule_failed_exec)
3113 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3114 else
3115 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3117 return 0;
3120 static int walk_revs_populate_todo(struct todo_list *todo_list,
3121 struct replay_opts *opts)
3123 enum todo_command command = opts->action == REPLAY_PICK ?
3124 TODO_PICK : TODO_REVERT;
3125 const char *command_string = todo_command_info[command].str;
3126 const char *encoding;
3127 struct commit *commit;
3129 if (prepare_revs(opts))
3130 return -1;
3132 encoding = get_log_output_encoding();
3134 while ((commit = get_revision(opts->revs))) {
3135 struct todo_item *item = append_new_todo(todo_list);
3136 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3137 commit, NULL,
3138 encoding);
3139 const char *subject;
3140 int subject_len;
3142 item->command = command;
3143 item->commit = commit;
3144 item->arg_offset = 0;
3145 item->arg_len = 0;
3146 item->offset_in_buf = todo_list->buf.len;
3147 subject_len = find_commit_subject(commit_buffer, &subject);
3148 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3149 short_commit_name(commit), subject_len, subject);
3150 repo_unuse_commit_buffer(the_repository, commit,
3151 commit_buffer);
3154 if (!todo_list->nr)
3155 return error(_("empty commit set passed"));
3157 return 0;
3160 static int create_seq_dir(struct repository *r)
3162 enum replay_action action;
3163 const char *in_progress_error = NULL;
3164 const char *in_progress_advice = NULL;
3165 unsigned int advise_skip =
3166 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3167 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3169 if (!sequencer_get_last_command(r, &action)) {
3170 switch (action) {
3171 case REPLAY_REVERT:
3172 in_progress_error = _("revert is already in progress");
3173 in_progress_advice =
3174 _("try \"git revert (--continue | %s--abort | --quit)\"");
3175 break;
3176 case REPLAY_PICK:
3177 in_progress_error = _("cherry-pick is already in progress");
3178 in_progress_advice =
3179 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3180 break;
3181 default:
3182 BUG("unexpected action in create_seq_dir");
3185 if (in_progress_error) {
3186 error("%s", in_progress_error);
3187 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3188 advise(in_progress_advice,
3189 advise_skip ? "--skip | " : "");
3190 return -1;
3192 if (mkdir(git_path_seq_dir(), 0777) < 0)
3193 return error_errno(_("could not create sequencer directory '%s'"),
3194 git_path_seq_dir());
3196 return 0;
3199 static int save_head(const char *head)
3201 return write_message(head, strlen(head), git_path_head_file(), 1);
3204 static int rollback_is_safe(void)
3206 struct strbuf sb = STRBUF_INIT;
3207 struct object_id expected_head, actual_head;
3209 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3210 strbuf_trim(&sb);
3211 if (get_oid_hex(sb.buf, &expected_head)) {
3212 strbuf_release(&sb);
3213 die(_("could not parse %s"), git_path_abort_safety_file());
3215 strbuf_release(&sb);
3217 else if (errno == ENOENT)
3218 oidclr(&expected_head);
3219 else
3220 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3222 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3223 oidclr(&actual_head);
3225 return oideq(&actual_head, &expected_head);
3228 static int reset_merge(const struct object_id *oid)
3230 struct child_process cmd = CHILD_PROCESS_INIT;
3232 cmd.git_cmd = 1;
3233 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3235 if (!is_null_oid(oid))
3236 strvec_push(&cmd.args, oid_to_hex(oid));
3238 return run_command(&cmd);
3241 static int rollback_single_pick(struct repository *r)
3243 struct object_id head_oid;
3245 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3246 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3247 return error(_("no cherry-pick or revert in progress"));
3248 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3249 return error(_("cannot resolve HEAD"));
3250 if (is_null_oid(&head_oid))
3251 return error(_("cannot abort from a branch yet to be born"));
3252 return reset_merge(&head_oid);
3255 static int skip_single_pick(void)
3257 struct object_id head;
3259 if (read_ref_full("HEAD", 0, &head, NULL))
3260 return error(_("cannot resolve HEAD"));
3261 return reset_merge(&head);
3264 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3266 FILE *f;
3267 struct object_id oid;
3268 struct strbuf buf = STRBUF_INIT;
3269 const char *p;
3271 f = fopen(git_path_head_file(), "r");
3272 if (!f && errno == ENOENT) {
3274 * There is no multiple-cherry-pick in progress.
3275 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3276 * a single-cherry-pick in progress, abort that.
3278 return rollback_single_pick(r);
3280 if (!f)
3281 return error_errno(_("cannot open '%s'"), git_path_head_file());
3282 if (strbuf_getline_lf(&buf, f)) {
3283 error(_("cannot read '%s': %s"), git_path_head_file(),
3284 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3285 fclose(f);
3286 goto fail;
3288 fclose(f);
3289 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3290 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3291 git_path_head_file());
3292 goto fail;
3294 if (is_null_oid(&oid)) {
3295 error(_("cannot abort from a branch yet to be born"));
3296 goto fail;
3299 if (!rollback_is_safe()) {
3300 /* Do not error, just do not rollback */
3301 warning(_("You seem to have moved HEAD. "
3302 "Not rewinding, check your HEAD!"));
3303 } else
3304 if (reset_merge(&oid))
3305 goto fail;
3306 strbuf_release(&buf);
3307 return sequencer_remove_state(opts);
3308 fail:
3309 strbuf_release(&buf);
3310 return -1;
3313 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3315 enum replay_action action = -1;
3316 sequencer_get_last_command(r, &action);
3319 * Check whether the subcommand requested to skip the commit is actually
3320 * in progress and that it's safe to skip the commit.
3322 * opts->action tells us which subcommand requested to skip the commit.
3323 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3324 * action is in progress and we can skip the commit.
3326 * Otherwise we check that the last instruction was related to the
3327 * particular subcommand we're trying to execute and barf if that's not
3328 * the case.
3330 * Finally we check that the rollback is "safe", i.e., has the HEAD
3331 * moved? In this case, it doesn't make sense to "reset the merge" and
3332 * "skip the commit" as the user already handled this by committing. But
3333 * we'd not want to barf here, instead give advice on how to proceed. We
3334 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3335 * it gets removed when the user commits, so if it still exists we're
3336 * sure the user can't have committed before.
3338 switch (opts->action) {
3339 case REPLAY_REVERT:
3340 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3341 if (action != REPLAY_REVERT)
3342 return error(_("no revert in progress"));
3343 if (!rollback_is_safe())
3344 goto give_advice;
3346 break;
3347 case REPLAY_PICK:
3348 if (!refs_ref_exists(get_main_ref_store(r),
3349 "CHERRY_PICK_HEAD")) {
3350 if (action != REPLAY_PICK)
3351 return error(_("no cherry-pick in progress"));
3352 if (!rollback_is_safe())
3353 goto give_advice;
3355 break;
3356 default:
3357 BUG("unexpected action in sequencer_skip");
3360 if (skip_single_pick())
3361 return error(_("failed to skip the commit"));
3362 if (!is_directory(git_path_seq_dir()))
3363 return 0;
3365 return sequencer_continue(r, opts);
3367 give_advice:
3368 error(_("there is nothing to skip"));
3370 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3371 advise(_("have you committed already?\n"
3372 "try \"git %s --continue\""),
3373 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3375 return -1;
3378 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3380 struct lock_file todo_lock = LOCK_INIT;
3381 const char *todo_path = get_todo_path(opts);
3382 int next = todo_list->current, offset, fd;
3385 * rebase -i writes "git-rebase-todo" without the currently executing
3386 * command, appending it to "done" instead.
3388 if (is_rebase_i(opts))
3389 next++;
3391 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3392 if (fd < 0)
3393 return error_errno(_("could not lock '%s'"), todo_path);
3394 offset = get_item_line_offset(todo_list, next);
3395 if (write_in_full(fd, todo_list->buf.buf + offset,
3396 todo_list->buf.len - offset) < 0)
3397 return error_errno(_("could not write to '%s'"), todo_path);
3398 if (commit_lock_file(&todo_lock) < 0)
3399 return error(_("failed to finalize '%s'"), todo_path);
3401 if (is_rebase_i(opts) && next > 0) {
3402 const char *done = rebase_path_done();
3403 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3404 int ret = 0;
3406 if (fd < 0)
3407 return 0;
3408 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3409 get_item_line_length(todo_list, next - 1))
3410 < 0)
3411 ret = error_errno(_("could not write to '%s'"), done);
3412 if (close(fd) < 0)
3413 ret = error_errno(_("failed to finalize '%s'"), done);
3414 return ret;
3416 return 0;
3419 static int save_opts(struct replay_opts *opts)
3421 const char *opts_file = git_path_opts_file();
3422 int res = 0;
3424 if (opts->no_commit)
3425 res |= git_config_set_in_file_gently(opts_file,
3426 "options.no-commit", "true");
3427 if (opts->edit >= 0)
3428 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3429 opts->edit ? "true" : "false");
3430 if (opts->allow_empty)
3431 res |= git_config_set_in_file_gently(opts_file,
3432 "options.allow-empty", "true");
3433 if (opts->allow_empty_message)
3434 res |= git_config_set_in_file_gently(opts_file,
3435 "options.allow-empty-message", "true");
3436 if (opts->keep_redundant_commits)
3437 res |= git_config_set_in_file_gently(opts_file,
3438 "options.keep-redundant-commits", "true");
3439 if (opts->signoff)
3440 res |= git_config_set_in_file_gently(opts_file,
3441 "options.signoff", "true");
3442 if (opts->record_origin)
3443 res |= git_config_set_in_file_gently(opts_file,
3444 "options.record-origin", "true");
3445 if (opts->allow_ff)
3446 res |= git_config_set_in_file_gently(opts_file,
3447 "options.allow-ff", "true");
3448 if (opts->mainline) {
3449 struct strbuf buf = STRBUF_INIT;
3450 strbuf_addf(&buf, "%d", opts->mainline);
3451 res |= git_config_set_in_file_gently(opts_file,
3452 "options.mainline", buf.buf);
3453 strbuf_release(&buf);
3455 if (opts->strategy)
3456 res |= git_config_set_in_file_gently(opts_file,
3457 "options.strategy", opts->strategy);
3458 if (opts->gpg_sign)
3459 res |= git_config_set_in_file_gently(opts_file,
3460 "options.gpg-sign", opts->gpg_sign);
3461 for (size_t i = 0; i < opts->xopts.nr; i++)
3462 res |= git_config_set_multivar_in_file_gently(opts_file,
3463 "options.strategy-option",
3464 opts->xopts.v[i], "^$", 0);
3465 if (opts->allow_rerere_auto)
3466 res |= git_config_set_in_file_gently(opts_file,
3467 "options.allow-rerere-auto",
3468 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3469 "true" : "false");
3471 if (opts->explicit_cleanup)
3472 res |= git_config_set_in_file_gently(opts_file,
3473 "options.default-msg-cleanup",
3474 describe_cleanup_mode(opts->default_msg_cleanup));
3475 return res;
3478 static int make_patch(struct repository *r,
3479 struct commit *commit,
3480 struct replay_opts *opts)
3482 struct strbuf buf = STRBUF_INIT;
3483 struct rev_info log_tree_opt;
3484 const char *subject;
3485 char hex[GIT_MAX_HEXSZ + 1];
3486 int res = 0;
3488 oid_to_hex_r(hex, &commit->object.oid);
3489 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3490 return -1;
3491 res |= write_rebase_head(&commit->object.oid);
3493 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3494 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3495 repo_init_revisions(r, &log_tree_opt, NULL);
3496 log_tree_opt.abbrev = 0;
3497 log_tree_opt.diff = 1;
3498 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3499 log_tree_opt.disable_stdin = 1;
3500 log_tree_opt.no_commit_id = 1;
3501 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3502 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3503 if (!log_tree_opt.diffopt.file)
3504 res |= error_errno(_("could not open '%s'"), buf.buf);
3505 else {
3506 res |= log_tree_commit(&log_tree_opt, commit);
3507 fclose(log_tree_opt.diffopt.file);
3509 strbuf_reset(&buf);
3511 strbuf_addf(&buf, "%s/message", get_dir(opts));
3512 if (!file_exists(buf.buf)) {
3513 const char *encoding = get_commit_output_encoding();
3514 const char *commit_buffer = repo_logmsg_reencode(r,
3515 commit, NULL,
3516 encoding);
3517 find_commit_subject(commit_buffer, &subject);
3518 res |= write_message(subject, strlen(subject), buf.buf, 1);
3519 repo_unuse_commit_buffer(r, commit,
3520 commit_buffer);
3522 strbuf_release(&buf);
3523 release_revisions(&log_tree_opt);
3525 return res;
3528 static int intend_to_amend(void)
3530 struct object_id head;
3531 char *p;
3533 if (repo_get_oid(the_repository, "HEAD", &head))
3534 return error(_("cannot read HEAD"));
3536 p = oid_to_hex(&head);
3537 return write_message(p, strlen(p), rebase_path_amend(), 1);
3540 static int error_with_patch(struct repository *r,
3541 struct commit *commit,
3542 const char *subject, int subject_len,
3543 struct replay_opts *opts,
3544 int exit_code, int to_amend)
3546 if (commit) {
3547 if (make_patch(r, commit, opts))
3548 return -1;
3549 } else if (copy_file(rebase_path_message(),
3550 git_path_merge_msg(r), 0666))
3551 return error(_("unable to copy '%s' to '%s'"),
3552 git_path_merge_msg(r), rebase_path_message());
3554 if (to_amend) {
3555 if (intend_to_amend())
3556 return -1;
3558 fprintf(stderr,
3559 _("You can amend the commit now, with\n"
3560 "\n"
3561 " git commit --amend %s\n"
3562 "\n"
3563 "Once you are satisfied with your changes, run\n"
3564 "\n"
3565 " git rebase --continue\n"),
3566 gpg_sign_opt_quoted(opts));
3567 } else if (exit_code) {
3568 if (commit)
3569 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3570 short_commit_name(commit), subject_len, subject);
3571 else
3573 * We don't have the hash of the parent so
3574 * just print the line from the todo file.
3576 fprintf_ln(stderr, _("Could not merge %.*s"),
3577 subject_len, subject);
3580 return exit_code;
3583 static int error_failed_squash(struct repository *r,
3584 struct commit *commit,
3585 struct replay_opts *opts,
3586 int subject_len,
3587 const char *subject)
3589 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3590 return error(_("could not copy '%s' to '%s'"),
3591 rebase_path_squash_msg(), rebase_path_message());
3592 unlink(git_path_merge_msg(r));
3593 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3594 return error(_("could not copy '%s' to '%s'"),
3595 rebase_path_message(),
3596 git_path_merge_msg(r));
3597 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3600 static int do_exec(struct repository *r, const char *command_line)
3602 struct child_process cmd = CHILD_PROCESS_INIT;
3603 int dirty, status;
3605 fprintf(stderr, _("Executing: %s\n"), command_line);
3606 cmd.use_shell = 1;
3607 strvec_push(&cmd.args, command_line);
3608 status = run_command(&cmd);
3610 /* force re-reading of the cache */
3611 discard_index(r->index);
3612 if (repo_read_index(r) < 0)
3613 return error(_("could not read index"));
3615 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3617 if (status) {
3618 warning(_("execution failed: %s\n%s"
3619 "You can fix the problem, and then run\n"
3620 "\n"
3621 " git rebase --continue\n"
3622 "\n"),
3623 command_line,
3624 dirty ? N_("and made changes to the index and/or the "
3625 "working tree\n") : "");
3626 if (status == 127)
3627 /* command not found */
3628 status = 1;
3629 } else if (dirty) {
3630 warning(_("execution succeeded: %s\nbut "
3631 "left changes to the index and/or the working tree\n"
3632 "Commit or stash your changes, and then run\n"
3633 "\n"
3634 " git rebase --continue\n"
3635 "\n"), command_line);
3636 status = 1;
3639 return status;
3642 __attribute__((format (printf, 2, 3)))
3643 static int safe_append(const char *filename, const char *fmt, ...)
3645 va_list ap;
3646 struct lock_file lock = LOCK_INIT;
3647 int fd = hold_lock_file_for_update(&lock, filename,
3648 LOCK_REPORT_ON_ERROR);
3649 struct strbuf buf = STRBUF_INIT;
3651 if (fd < 0)
3652 return -1;
3654 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3655 error_errno(_("could not read '%s'"), filename);
3656 rollback_lock_file(&lock);
3657 return -1;
3659 strbuf_complete(&buf, '\n');
3660 va_start(ap, fmt);
3661 strbuf_vaddf(&buf, fmt, ap);
3662 va_end(ap);
3664 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3665 error_errno(_("could not write to '%s'"), filename);
3666 strbuf_release(&buf);
3667 rollback_lock_file(&lock);
3668 return -1;
3670 if (commit_lock_file(&lock) < 0) {
3671 strbuf_release(&buf);
3672 return error(_("failed to finalize '%s'"), filename);
3675 strbuf_release(&buf);
3676 return 0;
3679 static int do_label(struct repository *r, const char *name, int len)
3681 struct ref_store *refs = get_main_ref_store(r);
3682 struct ref_transaction *transaction;
3683 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3684 struct strbuf msg = STRBUF_INIT;
3685 int ret = 0;
3686 struct object_id head_oid;
3688 if (len == 1 && *name == '#')
3689 return error(_("illegal label name: '%.*s'"), len, name);
3691 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3692 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3694 transaction = ref_store_transaction_begin(refs, &err);
3695 if (!transaction) {
3696 error("%s", err.buf);
3697 ret = -1;
3698 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3699 error(_("could not read HEAD"));
3700 ret = -1;
3701 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3702 NULL, 0, msg.buf, &err) < 0 ||
3703 ref_transaction_commit(transaction, &err)) {
3704 error("%s", err.buf);
3705 ret = -1;
3707 ref_transaction_free(transaction);
3708 strbuf_release(&err);
3709 strbuf_release(&msg);
3711 if (!ret)
3712 ret = safe_append(rebase_path_refs_to_delete(),
3713 "%s\n", ref_name.buf);
3714 strbuf_release(&ref_name);
3716 return ret;
3719 static const char *sequencer_reflog_action(struct replay_opts *opts)
3721 if (!opts->reflog_action) {
3722 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3723 opts->reflog_action =
3724 xstrdup(opts->reflog_action ? opts->reflog_action
3725 : action_name(opts));
3728 return opts->reflog_action;
3731 __attribute__((format (printf, 3, 4)))
3732 static const char *reflog_message(struct replay_opts *opts,
3733 const char *sub_action, const char *fmt, ...)
3735 va_list ap;
3736 static struct strbuf buf = STRBUF_INIT;
3738 va_start(ap, fmt);
3739 strbuf_reset(&buf);
3740 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3741 if (sub_action)
3742 strbuf_addf(&buf, " (%s)", sub_action);
3743 if (fmt) {
3744 strbuf_addstr(&buf, ": ");
3745 strbuf_vaddf(&buf, fmt, ap);
3747 va_end(ap);
3749 return buf.buf;
3752 static struct commit *lookup_label(struct repository *r, const char *label,
3753 int len, struct strbuf *buf)
3755 struct commit *commit;
3756 struct object_id oid;
3758 strbuf_reset(buf);
3759 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3760 if (!read_ref(buf->buf, &oid)) {
3761 commit = lookup_commit_object(r, &oid);
3762 } else {
3763 /* fall back to non-rewritten ref or commit */
3764 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3765 commit = lookup_commit_reference_by_name(buf->buf);
3768 if (!commit)
3769 error(_("could not resolve '%s'"), buf->buf);
3771 return commit;
3774 static int do_reset(struct repository *r,
3775 const char *name, int len,
3776 struct replay_opts *opts)
3778 struct strbuf ref_name = STRBUF_INIT;
3779 struct object_id oid;
3780 struct lock_file lock = LOCK_INIT;
3781 struct tree_desc desc = { 0 };
3782 struct tree *tree;
3783 struct unpack_trees_options unpack_tree_opts = { 0 };
3784 int ret = 0;
3786 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3787 return -1;
3789 if (len == 10 && !strncmp("[new root]", name, len)) {
3790 if (!opts->have_squash_onto) {
3791 const char *hex;
3792 if (commit_tree("", 0, the_hash_algo->empty_tree,
3793 NULL, &opts->squash_onto,
3794 NULL, NULL))
3795 return error(_("writing fake root commit"));
3796 opts->have_squash_onto = 1;
3797 hex = oid_to_hex(&opts->squash_onto);
3798 if (write_message(hex, strlen(hex),
3799 rebase_path_squash_onto(), 0))
3800 return error(_("writing squash-onto"));
3802 oidcpy(&oid, &opts->squash_onto);
3803 } else {
3804 int i;
3805 struct commit *commit;
3807 /* Determine the length of the label */
3808 for (i = 0; i < len; i++)
3809 if (isspace(name[i]))
3810 break;
3811 len = i;
3813 commit = lookup_label(r, name, len, &ref_name);
3814 if (!commit) {
3815 ret = -1;
3816 goto cleanup;
3818 oid = commit->object.oid;
3821 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3822 unpack_tree_opts.head_idx = 1;
3823 unpack_tree_opts.src_index = r->index;
3824 unpack_tree_opts.dst_index = r->index;
3825 unpack_tree_opts.fn = oneway_merge;
3826 unpack_tree_opts.merge = 1;
3827 unpack_tree_opts.update = 1;
3828 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3829 unpack_tree_opts.skip_cache_tree_update = 1;
3830 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3832 if (repo_read_index_unmerged(r)) {
3833 ret = error_resolve_conflict(action_name(opts));
3834 goto cleanup;
3837 if (!fill_tree_descriptor(r, &desc, &oid)) {
3838 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3839 goto cleanup;
3842 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3843 ret = -1;
3844 goto cleanup;
3847 tree = parse_tree_indirect(&oid);
3848 prime_cache_tree(r, r->index, tree);
3850 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3851 ret = error(_("could not write index"));
3853 if (!ret)
3854 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3855 len, name), "HEAD", &oid,
3856 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3857 cleanup:
3858 free((void *)desc.buffer);
3859 if (ret < 0)
3860 rollback_lock_file(&lock);
3861 strbuf_release(&ref_name);
3862 clear_unpack_trees_porcelain(&unpack_tree_opts);
3863 return ret;
3866 static int do_merge(struct repository *r,
3867 struct commit *commit,
3868 const char *arg, int arg_len,
3869 int flags, int *check_todo, struct replay_opts *opts)
3871 int run_commit_flags = 0;
3872 struct strbuf ref_name = STRBUF_INIT;
3873 struct commit *head_commit, *merge_commit, *i;
3874 struct commit_list *bases, *j;
3875 struct commit_list *to_merge = NULL, **tail = &to_merge;
3876 const char *strategy = !opts->xopts.nr &&
3877 (!opts->strategy ||
3878 !strcmp(opts->strategy, "recursive") ||
3879 !strcmp(opts->strategy, "ort")) ?
3880 NULL : opts->strategy;
3881 struct merge_options o;
3882 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3883 static struct lock_file lock;
3884 const char *p;
3886 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3887 ret = -1;
3888 goto leave_merge;
3891 head_commit = lookup_commit_reference_by_name("HEAD");
3892 if (!head_commit) {
3893 ret = error(_("cannot merge without a current revision"));
3894 goto leave_merge;
3898 * For octopus merges, the arg starts with the list of revisions to be
3899 * merged. The list is optionally followed by '#' and the oneline.
3901 merge_arg_len = oneline_offset = arg_len;
3902 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3903 if (!*p)
3904 break;
3905 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3906 p += 1 + strspn(p + 1, " \t\n");
3907 oneline_offset = p - arg;
3908 break;
3910 k = strcspn(p, " \t\n");
3911 if (!k)
3912 continue;
3913 merge_commit = lookup_label(r, p, k, &ref_name);
3914 if (!merge_commit) {
3915 ret = error(_("unable to parse '%.*s'"), k, p);
3916 goto leave_merge;
3918 tail = &commit_list_insert(merge_commit, tail)->next;
3919 p += k;
3920 merge_arg_len = p - arg;
3923 if (!to_merge) {
3924 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3925 goto leave_merge;
3928 if (opts->have_squash_onto &&
3929 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3931 * When the user tells us to "merge" something into a
3932 * "[new root]", let's simply fast-forward to the merge head.
3934 rollback_lock_file(&lock);
3935 if (to_merge->next)
3936 ret = error(_("octopus merge cannot be executed on "
3937 "top of a [new root]"));
3938 else
3939 ret = fast_forward_to(r, &to_merge->item->object.oid,
3940 &head_commit->object.oid, 0,
3941 opts);
3942 goto leave_merge;
3946 * If HEAD is not identical to the first parent of the original merge
3947 * commit, we cannot fast-forward.
3949 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3950 oideq(&commit->parents->item->object.oid,
3951 &head_commit->object.oid);
3954 * If any merge head is different from the original one, we cannot
3955 * fast-forward.
3957 if (can_fast_forward) {
3958 struct commit_list *p = commit->parents->next;
3960 for (j = to_merge; j && p; j = j->next, p = p->next)
3961 if (!oideq(&j->item->object.oid,
3962 &p->item->object.oid)) {
3963 can_fast_forward = 0;
3964 break;
3967 * If the number of merge heads differs from the original merge
3968 * commit, we cannot fast-forward.
3970 if (j || p)
3971 can_fast_forward = 0;
3974 if (can_fast_forward) {
3975 rollback_lock_file(&lock);
3976 ret = fast_forward_to(r, &commit->object.oid,
3977 &head_commit->object.oid, 0, opts);
3978 if (flags & TODO_EDIT_MERGE_MSG)
3979 goto fast_forward_edit;
3981 goto leave_merge;
3984 if (commit) {
3985 const char *encoding = get_commit_output_encoding();
3986 const char *message = repo_logmsg_reencode(r, commit, NULL,
3987 encoding);
3988 const char *body;
3989 int len;
3991 if (!message) {
3992 ret = error(_("could not get commit message of '%s'"),
3993 oid_to_hex(&commit->object.oid));
3994 goto leave_merge;
3996 write_author_script(message);
3997 find_commit_subject(message, &body);
3998 len = strlen(body);
3999 ret = write_message(body, len, git_path_merge_msg(r), 0);
4000 repo_unuse_commit_buffer(r, commit, message);
4001 if (ret) {
4002 error_errno(_("could not write '%s'"),
4003 git_path_merge_msg(r));
4004 goto leave_merge;
4006 } else {
4007 struct strbuf buf = STRBUF_INIT;
4008 int len;
4010 strbuf_addf(&buf, "author %s", git_author_info(0));
4011 write_author_script(buf.buf);
4012 strbuf_reset(&buf);
4014 if (oneline_offset < arg_len) {
4015 p = arg + oneline_offset;
4016 len = arg_len - oneline_offset;
4017 } else {
4018 strbuf_addf(&buf, "Merge %s '%.*s'",
4019 to_merge->next ? "branches" : "branch",
4020 merge_arg_len, arg);
4021 p = buf.buf;
4022 len = buf.len;
4025 ret = write_message(p, len, git_path_merge_msg(r), 0);
4026 strbuf_release(&buf);
4027 if (ret) {
4028 error_errno(_("could not write '%s'"),
4029 git_path_merge_msg(r));
4030 goto leave_merge;
4034 if (strategy || to_merge->next) {
4035 /* Octopus merge */
4036 struct child_process cmd = CHILD_PROCESS_INIT;
4038 if (read_env_script(&cmd.env)) {
4039 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4041 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4042 goto leave_merge;
4045 if (opts->committer_date_is_author_date)
4046 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4047 opts->ignore_date ?
4048 "" :
4049 author_date_from_env(&cmd.env));
4050 if (opts->ignore_date)
4051 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4053 cmd.git_cmd = 1;
4054 strvec_push(&cmd.args, "merge");
4055 strvec_push(&cmd.args, "-s");
4056 if (!strategy)
4057 strvec_push(&cmd.args, "octopus");
4058 else {
4059 strvec_push(&cmd.args, strategy);
4060 for (k = 0; k < opts->xopts.nr; k++)
4061 strvec_pushf(&cmd.args,
4062 "-X%s", opts->xopts.v[k]);
4064 if (!(flags & TODO_EDIT_MERGE_MSG))
4065 strvec_push(&cmd.args, "--no-edit");
4066 else
4067 strvec_push(&cmd.args, "--edit");
4068 strvec_push(&cmd.args, "--no-ff");
4069 strvec_push(&cmd.args, "--no-log");
4070 strvec_push(&cmd.args, "--no-stat");
4071 strvec_push(&cmd.args, "-F");
4072 strvec_push(&cmd.args, git_path_merge_msg(r));
4073 if (opts->gpg_sign)
4074 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4075 else
4076 strvec_push(&cmd.args, "--no-gpg-sign");
4078 /* Add the tips to be merged */
4079 for (j = to_merge; j; j = j->next)
4080 strvec_push(&cmd.args,
4081 oid_to_hex(&j->item->object.oid));
4083 strbuf_release(&ref_name);
4084 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4085 NULL, 0);
4086 rollback_lock_file(&lock);
4088 ret = run_command(&cmd);
4090 /* force re-reading of the cache */
4091 if (!ret) {
4092 discard_index(r->index);
4093 if (repo_read_index(r) < 0)
4094 ret = error(_("could not read index"));
4096 goto leave_merge;
4099 merge_commit = to_merge->item;
4100 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4101 if (bases && oideq(&merge_commit->object.oid,
4102 &bases->item->object.oid)) {
4103 ret = 0;
4104 /* skip merging an ancestor of HEAD */
4105 goto leave_merge;
4108 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4109 git_path_merge_head(r), 0);
4110 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4112 bases = reverse_commit_list(bases);
4114 repo_read_index(r);
4115 init_merge_options(&o, r);
4116 o.branch1 = "HEAD";
4117 o.branch2 = ref_name.buf;
4118 o.buffer_output = 2;
4120 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4122 * TODO: Should use merge_incore_recursive() and
4123 * merge_switch_to_result(), skipping the call to
4124 * merge_switch_to_result() when we don't actually need to
4125 * update the index and working copy immediately.
4127 ret = merge_ort_recursive(&o,
4128 head_commit, merge_commit, bases,
4129 &i);
4130 } else {
4131 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4132 &i);
4134 if (ret <= 0)
4135 fputs(o.obuf.buf, stdout);
4136 strbuf_release(&o.obuf);
4137 if (ret < 0) {
4138 error(_("could not even attempt to merge '%.*s'"),
4139 merge_arg_len, arg);
4140 goto leave_merge;
4143 * The return value of merge_recursive() is 1 on clean, and 0 on
4144 * unclean merge.
4146 * Let's reverse that, so that do_merge() returns 0 upon success and
4147 * 1 upon failed merge (keeping the return value -1 for the cases where
4148 * we will want to reschedule the `merge` command).
4150 ret = !ret;
4152 if (r->index->cache_changed &&
4153 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4154 ret = error(_("merge: Unable to write new index file"));
4155 goto leave_merge;
4158 rollback_lock_file(&lock);
4159 if (ret)
4160 repo_rerere(r, opts->allow_rerere_auto);
4161 else
4163 * In case of problems, we now want to return a positive
4164 * value (a negative one would indicate that the `merge`
4165 * command needs to be rescheduled).
4167 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4168 run_commit_flags);
4170 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4171 fast_forward_edit:
4172 *check_todo = 1;
4173 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4174 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4178 leave_merge:
4179 strbuf_release(&ref_name);
4180 rollback_lock_file(&lock);
4181 free_commit_list(to_merge);
4182 return ret;
4185 static int write_update_refs_state(struct string_list *refs_to_oids)
4187 int result = 0;
4188 struct lock_file lock = LOCK_INIT;
4189 FILE *fp = NULL;
4190 struct string_list_item *item;
4191 char *path;
4193 path = rebase_path_update_refs(the_repository->gitdir);
4195 if (!refs_to_oids->nr) {
4196 if (unlink(path) && errno != ENOENT)
4197 result = error_errno(_("could not unlink: %s"), path);
4198 goto cleanup;
4201 if (safe_create_leading_directories(path)) {
4202 result = error(_("unable to create leading directories of %s"),
4203 path);
4204 goto cleanup;
4207 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4208 result = error(_("another 'rebase' process appears to be running; "
4209 "'%s.lock' already exists"),
4210 path);
4211 goto cleanup;
4214 fp = fdopen_lock_file(&lock, "w");
4215 if (!fp) {
4216 result = error_errno(_("could not open '%s' for writing"), path);
4217 rollback_lock_file(&lock);
4218 goto cleanup;
4221 for_each_string_list_item(item, refs_to_oids) {
4222 struct update_ref_record *rec = item->util;
4223 fprintf(fp, "%s\n%s\n%s\n", item->string,
4224 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4227 result = commit_lock_file(&lock);
4229 cleanup:
4230 free(path);
4231 return result;
4235 * Parse the update-refs file for the current rebase, then remove the
4236 * refs that do not appear in the todo_list (and have not had updated
4237 * values stored) and add refs that are in the todo_list but not
4238 * represented in the update-refs file.
4240 * If there are changes to the update-refs list, then write the new state
4241 * to disk.
4243 void todo_list_filter_update_refs(struct repository *r,
4244 struct todo_list *todo_list)
4246 int i;
4247 int updated = 0;
4248 struct string_list update_refs = STRING_LIST_INIT_DUP;
4250 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4253 * For each item in the update_refs list, if it has no updated
4254 * value and does not appear in the todo_list, then remove it
4255 * from the update_refs list.
4257 for (i = 0; i < update_refs.nr; i++) {
4258 int j;
4259 int found = 0;
4260 const char *ref = update_refs.items[i].string;
4261 size_t reflen = strlen(ref);
4262 struct update_ref_record *rec = update_refs.items[i].util;
4264 /* OID already stored as updated. */
4265 if (!is_null_oid(&rec->after))
4266 continue;
4268 for (j = 0; !found && j < todo_list->total_nr; j++) {
4269 struct todo_item *item = &todo_list->items[j];
4270 const char *arg = todo_list->buf.buf + item->arg_offset;
4272 if (item->command != TODO_UPDATE_REF)
4273 continue;
4275 if (item->arg_len != reflen ||
4276 strncmp(arg, ref, reflen))
4277 continue;
4279 found = 1;
4282 if (!found) {
4283 free(update_refs.items[i].string);
4284 free(update_refs.items[i].util);
4286 update_refs.nr--;
4287 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4289 updated = 1;
4290 i--;
4295 * For each todo_item, check if its ref is in the update_refs list.
4296 * If not, then add it as an un-updated ref.
4298 for (i = 0; i < todo_list->total_nr; i++) {
4299 struct todo_item *item = &todo_list->items[i];
4300 const char *arg = todo_list->buf.buf + item->arg_offset;
4301 int j, found = 0;
4303 if (item->command != TODO_UPDATE_REF)
4304 continue;
4306 for (j = 0; !found && j < update_refs.nr; j++) {
4307 const char *ref = update_refs.items[j].string;
4309 found = strlen(ref) == item->arg_len &&
4310 !strncmp(ref, arg, item->arg_len);
4313 if (!found) {
4314 struct string_list_item *inserted;
4315 struct strbuf argref = STRBUF_INIT;
4317 strbuf_add(&argref, arg, item->arg_len);
4318 inserted = string_list_insert(&update_refs, argref.buf);
4319 inserted->util = init_update_ref_record(argref.buf);
4320 strbuf_release(&argref);
4321 updated = 1;
4325 if (updated)
4326 write_update_refs_state(&update_refs);
4327 string_list_clear(&update_refs, 1);
4330 static int do_update_ref(struct repository *r, const char *refname)
4332 struct string_list_item *item;
4333 struct string_list list = STRING_LIST_INIT_DUP;
4335 if (sequencer_get_update_refs_state(r->gitdir, &list))
4336 return -1;
4338 for_each_string_list_item(item, &list) {
4339 if (!strcmp(item->string, refname)) {
4340 struct update_ref_record *rec = item->util;
4341 if (read_ref("HEAD", &rec->after))
4342 return -1;
4343 break;
4347 write_update_refs_state(&list);
4348 string_list_clear(&list, 1);
4349 return 0;
4352 static int do_update_refs(struct repository *r, int quiet)
4354 int res = 0;
4355 struct string_list_item *item;
4356 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4357 struct ref_store *refs = get_main_ref_store(r);
4358 struct strbuf update_msg = STRBUF_INIT;
4359 struct strbuf error_msg = STRBUF_INIT;
4361 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4362 return res;
4364 for_each_string_list_item(item, &refs_to_oids) {
4365 struct update_ref_record *rec = item->util;
4366 int loop_res;
4368 loop_res = refs_update_ref(refs, "rewritten during rebase",
4369 item->string,
4370 &rec->after, &rec->before,
4371 0, UPDATE_REFS_MSG_ON_ERR);
4372 res |= loop_res;
4374 if (quiet)
4375 continue;
4377 if (loop_res)
4378 strbuf_addf(&error_msg, "\t%s\n", item->string);
4379 else
4380 strbuf_addf(&update_msg, "\t%s\n", item->string);
4383 if (!quiet &&
4384 (update_msg.len || error_msg.len)) {
4385 fprintf(stderr,
4386 _("Updated the following refs with %s:\n%s"),
4387 "--update-refs",
4388 update_msg.buf);
4390 if (res)
4391 fprintf(stderr,
4392 _("Failed to update the following refs with %s:\n%s"),
4393 "--update-refs",
4394 error_msg.buf);
4397 string_list_clear(&refs_to_oids, 1);
4398 strbuf_release(&update_msg);
4399 strbuf_release(&error_msg);
4400 return res;
4403 static int is_final_fixup(struct todo_list *todo_list)
4405 int i = todo_list->current;
4407 if (!is_fixup(todo_list->items[i].command))
4408 return 0;
4410 while (++i < todo_list->nr)
4411 if (is_fixup(todo_list->items[i].command))
4412 return 0;
4413 else if (!is_noop(todo_list->items[i].command))
4414 break;
4415 return 1;
4418 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4420 int i;
4422 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4423 if (!is_noop(todo_list->items[i].command))
4424 return todo_list->items[i].command;
4426 return -1;
4429 void create_autostash(struct repository *r, const char *path)
4431 struct strbuf buf = STRBUF_INIT;
4432 struct lock_file lock_file = LOCK_INIT;
4433 int fd;
4435 fd = repo_hold_locked_index(r, &lock_file, 0);
4436 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4437 if (0 <= fd)
4438 repo_update_index_if_able(r, &lock_file);
4439 rollback_lock_file(&lock_file);
4441 if (has_unstaged_changes(r, 1) ||
4442 has_uncommitted_changes(r, 1)) {
4443 struct child_process stash = CHILD_PROCESS_INIT;
4444 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4445 struct object_id oid;
4447 strvec_pushl(&stash.args,
4448 "stash", "create", "autostash", NULL);
4449 stash.git_cmd = 1;
4450 stash.no_stdin = 1;
4451 strbuf_reset(&buf);
4452 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4453 die(_("Cannot autostash"));
4454 strbuf_trim_trailing_newline(&buf);
4455 if (repo_get_oid(r, buf.buf, &oid))
4456 die(_("Unexpected stash response: '%s'"),
4457 buf.buf);
4458 strbuf_reset(&buf);
4459 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4461 if (safe_create_leading_directories_const(path))
4462 die(_("Could not create directory for '%s'"),
4463 path);
4464 write_file(path, "%s", oid_to_hex(&oid));
4465 printf(_("Created autostash: %s\n"), buf.buf);
4466 if (reset_head(r, &ropts) < 0)
4467 die(_("could not reset --hard"));
4468 discard_index(r->index);
4469 if (repo_read_index(r) < 0)
4470 die(_("could not read index"));
4472 strbuf_release(&buf);
4475 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4477 struct child_process child = CHILD_PROCESS_INIT;
4478 int ret = 0;
4480 if (attempt_apply) {
4481 child.git_cmd = 1;
4482 child.no_stdout = 1;
4483 child.no_stderr = 1;
4484 strvec_push(&child.args, "stash");
4485 strvec_push(&child.args, "apply");
4486 strvec_push(&child.args, stash_oid);
4487 ret = run_command(&child);
4490 if (attempt_apply && !ret)
4491 fprintf(stderr, _("Applied autostash.\n"));
4492 else {
4493 struct child_process store = CHILD_PROCESS_INIT;
4495 store.git_cmd = 1;
4496 strvec_push(&store.args, "stash");
4497 strvec_push(&store.args, "store");
4498 strvec_push(&store.args, "-m");
4499 strvec_push(&store.args, "autostash");
4500 strvec_push(&store.args, "-q");
4501 strvec_push(&store.args, stash_oid);
4502 if (run_command(&store))
4503 ret = error(_("cannot store %s"), stash_oid);
4504 else
4505 fprintf(stderr,
4506 _("%s\n"
4507 "Your changes are safe in the stash.\n"
4508 "You can run \"git stash pop\" or"
4509 " \"git stash drop\" at any time.\n"),
4510 attempt_apply ?
4511 _("Applying autostash resulted in conflicts.") :
4512 _("Autostash exists; creating a new stash entry."));
4515 return ret;
4518 static int apply_save_autostash(const char *path, int attempt_apply)
4520 struct strbuf stash_oid = STRBUF_INIT;
4521 int ret = 0;
4523 if (!read_oneliner(&stash_oid, path,
4524 READ_ONELINER_SKIP_IF_EMPTY)) {
4525 strbuf_release(&stash_oid);
4526 return 0;
4528 strbuf_trim(&stash_oid);
4530 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4532 unlink(path);
4533 strbuf_release(&stash_oid);
4534 return ret;
4537 int save_autostash(const char *path)
4539 return apply_save_autostash(path, 0);
4542 int apply_autostash(const char *path)
4544 return apply_save_autostash(path, 1);
4547 int apply_autostash_oid(const char *stash_oid)
4549 return apply_save_autostash_oid(stash_oid, 1);
4552 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4553 const char *onto_name, const struct object_id *onto,
4554 const struct object_id *orig_head)
4556 struct reset_head_opts ropts = {
4557 .oid = onto,
4558 .orig_head = orig_head,
4559 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4560 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4561 .head_msg = reflog_message(opts, "start", "checkout %s",
4562 onto_name),
4563 .default_reflog_action = sequencer_reflog_action(opts)
4565 if (reset_head(r, &ropts)) {
4566 apply_autostash(rebase_path_autostash());
4567 sequencer_remove_state(opts);
4568 return error(_("could not detach HEAD"));
4571 return 0;
4574 static int stopped_at_head(struct repository *r)
4576 struct object_id head;
4577 struct commit *commit;
4578 struct commit_message message;
4580 if (repo_get_oid(r, "HEAD", &head) ||
4581 !(commit = lookup_commit(r, &head)) ||
4582 repo_parse_commit(r, commit) || get_message(commit, &message))
4583 fprintf(stderr, _("Stopped at HEAD\n"));
4584 else {
4585 fprintf(stderr, _("Stopped at %s\n"), message.label);
4586 free_message(commit, &message);
4588 return 0;
4592 static int reread_todo_if_changed(struct repository *r,
4593 struct todo_list *todo_list,
4594 struct replay_opts *opts)
4596 int offset;
4597 struct strbuf buf = STRBUF_INIT;
4599 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4600 return -1;
4601 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4602 if (buf.len != todo_list->buf.len - offset ||
4603 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4604 /* Reread the todo file if it has changed. */
4605 todo_list_release(todo_list);
4606 if (read_populate_todo(r, todo_list, opts))
4607 return -1; /* message was printed */
4608 /* `current` will be incremented on return */
4609 todo_list->current = -1;
4611 strbuf_release(&buf);
4613 return 0;
4616 static const char rescheduled_advice[] =
4617 N_("Could not execute the todo command\n"
4618 "\n"
4619 " %.*s"
4620 "\n"
4621 "It has been rescheduled; To edit the command before continuing, please\n"
4622 "edit the todo list first:\n"
4623 "\n"
4624 " git rebase --edit-todo\n"
4625 " git rebase --continue\n");
4627 static int pick_commits(struct repository *r,
4628 struct todo_list *todo_list,
4629 struct replay_opts *opts)
4631 int res = 0, reschedule = 0;
4633 opts->reflog_message = sequencer_reflog_action(opts);
4634 if (opts->allow_ff)
4635 assert(!(opts->signoff || opts->no_commit ||
4636 opts->record_origin || should_edit(opts) ||
4637 opts->committer_date_is_author_date ||
4638 opts->ignore_date));
4639 if (read_and_refresh_cache(r, opts))
4640 return -1;
4642 while (todo_list->current < todo_list->nr) {
4643 struct todo_item *item = todo_list->items + todo_list->current;
4644 const char *arg = todo_item_get_arg(todo_list, item);
4645 int check_todo = 0;
4647 if (save_todo(todo_list, opts))
4648 return -1;
4649 if (is_rebase_i(opts)) {
4650 if (item->command != TODO_COMMENT) {
4651 FILE *f = fopen(rebase_path_msgnum(), "w");
4653 todo_list->done_nr++;
4655 if (f) {
4656 fprintf(f, "%d\n", todo_list->done_nr);
4657 fclose(f);
4659 if (!opts->quiet)
4660 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4661 todo_list->done_nr,
4662 todo_list->total_nr,
4663 opts->verbose ? "\n" : "\r");
4665 unlink(rebase_path_message());
4666 unlink(rebase_path_author_script());
4667 unlink(rebase_path_stopped_sha());
4668 unlink(rebase_path_amend());
4669 unlink(git_path_merge_head(r));
4670 unlink(git_path_auto_merge(r));
4671 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4673 if (item->command == TODO_BREAK) {
4674 if (!opts->verbose)
4675 term_clear_line();
4676 return stopped_at_head(r);
4679 if (item->command <= TODO_SQUASH) {
4680 if (is_rebase_i(opts))
4681 opts->reflog_message = reflog_message(opts,
4682 command_to_string(item->command), NULL);
4684 res = do_pick_commit(r, item, opts,
4685 is_final_fixup(todo_list),
4686 &check_todo);
4687 if (is_rebase_i(opts) && res < 0) {
4688 /* Reschedule */
4689 advise(_(rescheduled_advice),
4690 get_item_line_length(todo_list,
4691 todo_list->current),
4692 get_item_line(todo_list,
4693 todo_list->current));
4694 todo_list->current--;
4695 if (save_todo(todo_list, opts))
4696 return -1;
4698 if (item->command == TODO_EDIT) {
4699 struct commit *commit = item->commit;
4700 if (!res) {
4701 if (!opts->verbose)
4702 term_clear_line();
4703 fprintf(stderr,
4704 _("Stopped at %s... %.*s\n"),
4705 short_commit_name(commit),
4706 item->arg_len, arg);
4708 return error_with_patch(r, commit,
4709 arg, item->arg_len, opts, res, !res);
4711 if (is_rebase_i(opts) && !res)
4712 record_in_rewritten(&item->commit->object.oid,
4713 peek_command(todo_list, 1));
4714 if (res && is_fixup(item->command)) {
4715 if (res == 1)
4716 intend_to_amend();
4717 return error_failed_squash(r, item->commit, opts,
4718 item->arg_len, arg);
4719 } else if (res && is_rebase_i(opts) && item->commit) {
4720 int to_amend = 0;
4721 struct object_id oid;
4724 * If we are rewording and have either
4725 * fast-forwarded already, or are about to
4726 * create a new root commit, we want to amend,
4727 * otherwise we do not.
4729 if (item->command == TODO_REWORD &&
4730 !repo_get_oid(r, "HEAD", &oid) &&
4731 (oideq(&item->commit->object.oid, &oid) ||
4732 (opts->have_squash_onto &&
4733 oideq(&opts->squash_onto, &oid))))
4734 to_amend = 1;
4736 return res | error_with_patch(r, item->commit,
4737 arg, item->arg_len, opts,
4738 res, to_amend);
4740 } else if (item->command == TODO_EXEC) {
4741 char *end_of_arg = (char *)(arg + item->arg_len);
4742 int saved = *end_of_arg;
4744 if (!opts->verbose)
4745 term_clear_line();
4746 *end_of_arg = '\0';
4747 res = do_exec(r, arg);
4748 *end_of_arg = saved;
4750 if (res) {
4751 if (opts->reschedule_failed_exec)
4752 reschedule = 1;
4754 check_todo = 1;
4755 } else if (item->command == TODO_LABEL) {
4756 if ((res = do_label(r, arg, item->arg_len)))
4757 reschedule = 1;
4758 } else if (item->command == TODO_RESET) {
4759 if ((res = do_reset(r, arg, item->arg_len, opts)))
4760 reschedule = 1;
4761 } else if (item->command == TODO_MERGE) {
4762 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4763 item->flags, &check_todo, opts)) < 0)
4764 reschedule = 1;
4765 else if (item->commit)
4766 record_in_rewritten(&item->commit->object.oid,
4767 peek_command(todo_list, 1));
4768 if (res > 0)
4769 /* failed with merge conflicts */
4770 return error_with_patch(r, item->commit,
4771 arg, item->arg_len,
4772 opts, res, 0);
4773 } else if (item->command == TODO_UPDATE_REF) {
4774 struct strbuf ref = STRBUF_INIT;
4775 strbuf_add(&ref, arg, item->arg_len);
4776 if ((res = do_update_ref(r, ref.buf)))
4777 reschedule = 1;
4778 strbuf_release(&ref);
4779 } else if (!is_noop(item->command))
4780 return error(_("unknown command %d"), item->command);
4782 if (reschedule) {
4783 advise(_(rescheduled_advice),
4784 get_item_line_length(todo_list,
4785 todo_list->current),
4786 get_item_line(todo_list, todo_list->current));
4787 todo_list->current--;
4788 if (save_todo(todo_list, opts))
4789 return -1;
4790 if (item->commit)
4791 return error_with_patch(r,
4792 item->commit,
4793 arg, item->arg_len,
4794 opts, res, 0);
4795 } else if (is_rebase_i(opts) && check_todo && !res &&
4796 reread_todo_if_changed(r, todo_list, opts)) {
4797 return -1;
4800 todo_list->current++;
4801 if (res)
4802 return res;
4805 if (is_rebase_i(opts)) {
4806 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4807 struct stat st;
4809 /* Stopped in the middle, as planned? */
4810 if (todo_list->current < todo_list->nr)
4811 return 0;
4813 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4814 starts_with(head_ref.buf, "refs/")) {
4815 const char *msg;
4816 struct object_id head, orig;
4817 int res;
4819 if (repo_get_oid(r, "HEAD", &head)) {
4820 res = error(_("cannot read HEAD"));
4821 cleanup_head_ref:
4822 strbuf_release(&head_ref);
4823 strbuf_release(&buf);
4824 return res;
4826 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4827 get_oid_hex(buf.buf, &orig)) {
4828 res = error(_("could not read orig-head"));
4829 goto cleanup_head_ref;
4831 strbuf_reset(&buf);
4832 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4833 res = error(_("could not read 'onto'"));
4834 goto cleanup_head_ref;
4836 msg = reflog_message(opts, "finish", "%s onto %s",
4837 head_ref.buf, buf.buf);
4838 if (update_ref(msg, head_ref.buf, &head, &orig,
4839 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4840 res = error(_("could not update %s"),
4841 head_ref.buf);
4842 goto cleanup_head_ref;
4844 msg = reflog_message(opts, "finish", "returning to %s",
4845 head_ref.buf);
4846 if (create_symref("HEAD", head_ref.buf, msg)) {
4847 res = error(_("could not update HEAD to %s"),
4848 head_ref.buf);
4849 goto cleanup_head_ref;
4851 strbuf_reset(&buf);
4854 if (opts->verbose) {
4855 struct rev_info log_tree_opt;
4856 struct object_id orig, head;
4858 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4859 repo_init_revisions(r, &log_tree_opt, NULL);
4860 log_tree_opt.diff = 1;
4861 log_tree_opt.diffopt.output_format =
4862 DIFF_FORMAT_DIFFSTAT;
4863 log_tree_opt.disable_stdin = 1;
4865 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4866 !repo_get_oid(r, buf.buf, &orig) &&
4867 !repo_get_oid(r, "HEAD", &head)) {
4868 diff_tree_oid(&orig, &head, "",
4869 &log_tree_opt.diffopt);
4870 log_tree_diff_flush(&log_tree_opt);
4872 release_revisions(&log_tree_opt);
4874 flush_rewritten_pending();
4875 if (!stat(rebase_path_rewritten_list(), &st) &&
4876 st.st_size > 0) {
4877 struct child_process child = CHILD_PROCESS_INIT;
4878 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4880 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4881 child.git_cmd = 1;
4882 strvec_push(&child.args, "notes");
4883 strvec_push(&child.args, "copy");
4884 strvec_push(&child.args, "--for-rewrite=rebase");
4885 /* we don't care if this copying failed */
4886 run_command(&child);
4888 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4889 strvec_push(&hook_opt.args, "rebase");
4890 run_hooks_opt("post-rewrite", &hook_opt);
4892 apply_autostash(rebase_path_autostash());
4894 if (!opts->quiet) {
4895 if (!opts->verbose)
4896 term_clear_line();
4897 fprintf(stderr,
4898 _("Successfully rebased and updated %s.\n"),
4899 head_ref.buf);
4902 strbuf_release(&buf);
4903 strbuf_release(&head_ref);
4905 if (do_update_refs(r, opts->quiet))
4906 return -1;
4910 * Sequence of picks finished successfully; cleanup by
4911 * removing the .git/sequencer directory
4913 return sequencer_remove_state(opts);
4916 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4918 struct child_process cmd = CHILD_PROCESS_INIT;
4920 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4921 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4922 return error(_("no cherry-pick or revert in progress"));
4924 cmd.git_cmd = 1;
4925 strvec_push(&cmd.args, "commit");
4928 * continue_single_pick() handles the case of recovering from a
4929 * conflict. should_edit() doesn't handle that case; for a conflict,
4930 * we want to edit if the user asked for it, or if they didn't specify
4931 * and stdin is a tty.
4933 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4935 * Include --cleanup=strip as well because we don't want the
4936 * "# Conflicts:" messages.
4938 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4940 return run_command(&cmd);
4943 static int commit_staged_changes(struct repository *r,
4944 struct replay_opts *opts,
4945 struct todo_list *todo_list)
4947 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4948 unsigned int final_fixup = 0, is_clean;
4950 if (has_unstaged_changes(r, 1))
4951 return error(_("cannot rebase: You have unstaged changes."));
4953 is_clean = !has_uncommitted_changes(r, 0);
4955 if (file_exists(rebase_path_amend())) {
4956 struct strbuf rev = STRBUF_INIT;
4957 struct object_id head, to_amend;
4959 if (repo_get_oid(r, "HEAD", &head))
4960 return error(_("cannot amend non-existing commit"));
4961 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4962 return error(_("invalid file: '%s'"), rebase_path_amend());
4963 if (get_oid_hex(rev.buf, &to_amend))
4964 return error(_("invalid contents: '%s'"),
4965 rebase_path_amend());
4966 if (!is_clean && !oideq(&head, &to_amend))
4967 return error(_("\nYou have uncommitted changes in your "
4968 "working tree. Please, commit them\n"
4969 "first and then run 'git rebase "
4970 "--continue' again."));
4972 * When skipping a failed fixup/squash, we need to edit the
4973 * commit message, the current fixup list and count, and if it
4974 * was the last fixup/squash in the chain, we need to clean up
4975 * the commit message and if there was a squash, let the user
4976 * edit it.
4978 if (!is_clean || !opts->current_fixup_count)
4979 ; /* this is not the final fixup */
4980 else if (!oideq(&head, &to_amend) ||
4981 !file_exists(rebase_path_stopped_sha())) {
4982 /* was a final fixup or squash done manually? */
4983 if (!is_fixup(peek_command(todo_list, 0))) {
4984 unlink(rebase_path_fixup_msg());
4985 unlink(rebase_path_squash_msg());
4986 unlink(rebase_path_current_fixups());
4987 strbuf_reset(&opts->current_fixups);
4988 opts->current_fixup_count = 0;
4990 } else {
4991 /* we are in a fixup/squash chain */
4992 const char *p = opts->current_fixups.buf;
4993 int len = opts->current_fixups.len;
4995 opts->current_fixup_count--;
4996 if (!len)
4997 BUG("Incorrect current_fixups:\n%s", p);
4998 while (len && p[len - 1] != '\n')
4999 len--;
5000 strbuf_setlen(&opts->current_fixups, len);
5001 if (write_message(p, len, rebase_path_current_fixups(),
5002 0) < 0)
5003 return error(_("could not write file: '%s'"),
5004 rebase_path_current_fixups());
5007 * If a fixup/squash in a fixup/squash chain failed, the
5008 * commit message is already correct, no need to commit
5009 * it again.
5011 * Only if it is the final command in the fixup/squash
5012 * chain, and only if the chain is longer than a single
5013 * fixup/squash command (which was just skipped), do we
5014 * actually need to re-commit with a cleaned up commit
5015 * message.
5017 if (opts->current_fixup_count > 0 &&
5018 !is_fixup(peek_command(todo_list, 0))) {
5019 final_fixup = 1;
5021 * If there was not a single "squash" in the
5022 * chain, we only need to clean up the commit
5023 * message, no need to bother the user with
5024 * opening the commit message in the editor.
5026 if (!starts_with(p, "squash ") &&
5027 !strstr(p, "\nsquash "))
5028 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5029 } else if (is_fixup(peek_command(todo_list, 0))) {
5031 * We need to update the squash message to skip
5032 * the latest commit message.
5034 struct commit *commit;
5035 const char *path = rebase_path_squash_msg();
5036 const char *encoding = get_commit_output_encoding();
5038 if (parse_head(r, &commit) ||
5039 !(p = repo_logmsg_reencode(r, commit, NULL, encoding)) ||
5040 write_message(p, strlen(p), path, 0)) {
5041 repo_unuse_commit_buffer(r, commit, p);
5042 return error(_("could not write file: "
5043 "'%s'"), path);
5045 repo_unuse_commit_buffer(r,
5046 commit, p);
5050 strbuf_release(&rev);
5051 flags |= AMEND_MSG;
5054 if (is_clean) {
5055 if (refs_ref_exists(get_main_ref_store(r),
5056 "CHERRY_PICK_HEAD") &&
5057 refs_delete_ref(get_main_ref_store(r), "",
5058 "CHERRY_PICK_HEAD", NULL, 0))
5059 return error(_("could not remove CHERRY_PICK_HEAD"));
5060 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5061 return error_errno(_("could not remove '%s'"),
5062 git_path_merge_msg(r));
5063 if (!final_fixup)
5064 return 0;
5067 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5068 opts, flags))
5069 return error(_("could not commit staged changes."));
5070 unlink(rebase_path_amend());
5071 unlink(git_path_merge_head(r));
5072 unlink(git_path_auto_merge(r));
5073 if (final_fixup) {
5074 unlink(rebase_path_fixup_msg());
5075 unlink(rebase_path_squash_msg());
5077 if (opts->current_fixup_count > 0) {
5079 * Whether final fixup or not, we just cleaned up the commit
5080 * message...
5082 unlink(rebase_path_current_fixups());
5083 strbuf_reset(&opts->current_fixups);
5084 opts->current_fixup_count = 0;
5086 return 0;
5089 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5091 struct todo_list todo_list = TODO_LIST_INIT;
5092 int res;
5094 if (read_and_refresh_cache(r, opts))
5095 return -1;
5097 if (read_populate_opts(opts))
5098 return -1;
5099 if (is_rebase_i(opts)) {
5100 if ((res = read_populate_todo(r, &todo_list, opts)))
5101 goto release_todo_list;
5103 if (file_exists(rebase_path_dropped())) {
5104 if ((res = todo_list_check_against_backup(r, &todo_list)))
5105 goto release_todo_list;
5107 unlink(rebase_path_dropped());
5110 opts->reflog_message = reflog_message(opts, "continue", NULL);
5111 if (commit_staged_changes(r, opts, &todo_list)) {
5112 res = -1;
5113 goto release_todo_list;
5115 } else if (!file_exists(get_todo_path(opts)))
5116 return continue_single_pick(r, opts);
5117 else if ((res = read_populate_todo(r, &todo_list, opts)))
5118 goto release_todo_list;
5120 if (!is_rebase_i(opts)) {
5121 /* Verify that the conflict has been resolved */
5122 if (refs_ref_exists(get_main_ref_store(r),
5123 "CHERRY_PICK_HEAD") ||
5124 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5125 res = continue_single_pick(r, opts);
5126 if (res)
5127 goto release_todo_list;
5129 if (index_differs_from(r, "HEAD", NULL, 0)) {
5130 res = error_dirty_index(r, opts);
5131 goto release_todo_list;
5133 todo_list.current++;
5134 } else if (file_exists(rebase_path_stopped_sha())) {
5135 struct strbuf buf = STRBUF_INIT;
5136 struct object_id oid;
5138 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5139 READ_ONELINER_SKIP_IF_EMPTY) &&
5140 !get_oid_hex(buf.buf, &oid))
5141 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5142 strbuf_release(&buf);
5145 res = pick_commits(r, &todo_list, opts);
5146 release_todo_list:
5147 todo_list_release(&todo_list);
5148 return res;
5151 static int single_pick(struct repository *r,
5152 struct commit *cmit,
5153 struct replay_opts *opts)
5155 int check_todo;
5156 struct todo_item item;
5158 item.command = opts->action == REPLAY_PICK ?
5159 TODO_PICK : TODO_REVERT;
5160 item.commit = cmit;
5162 opts->reflog_message = sequencer_reflog_action(opts);
5163 return do_pick_commit(r, &item, opts, 0, &check_todo);
5166 int sequencer_pick_revisions(struct repository *r,
5167 struct replay_opts *opts)
5169 struct todo_list todo_list = TODO_LIST_INIT;
5170 struct object_id oid;
5171 int i, res;
5173 assert(opts->revs);
5174 if (read_and_refresh_cache(r, opts))
5175 return -1;
5177 for (i = 0; i < opts->revs->pending.nr; i++) {
5178 struct object_id oid;
5179 const char *name = opts->revs->pending.objects[i].name;
5181 /* This happens when using --stdin. */
5182 if (!strlen(name))
5183 continue;
5185 if (!repo_get_oid(r, name, &oid)) {
5186 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5187 enum object_type type = oid_object_info(r,
5188 &oid,
5189 NULL);
5190 return error(_("%s: can't cherry-pick a %s"),
5191 name, type_name(type));
5193 } else
5194 return error(_("%s: bad revision"), name);
5198 * If we were called as "git cherry-pick <commit>", just
5199 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5200 * REVERT_HEAD, and don't touch the sequencer state.
5201 * This means it is possible to cherry-pick in the middle
5202 * of a cherry-pick sequence.
5204 if (opts->revs->cmdline.nr == 1 &&
5205 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5206 opts->revs->no_walk &&
5207 !opts->revs->cmdline.rev->flags) {
5208 struct commit *cmit;
5209 if (prepare_revision_walk(opts->revs))
5210 return error(_("revision walk setup failed"));
5211 cmit = get_revision(opts->revs);
5212 if (!cmit)
5213 return error(_("empty commit set passed"));
5214 if (get_revision(opts->revs))
5215 BUG("unexpected extra commit from walk");
5216 return single_pick(r, cmit, opts);
5220 * Start a new cherry-pick/ revert sequence; but
5221 * first, make sure that an existing one isn't in
5222 * progress
5225 if (walk_revs_populate_todo(&todo_list, opts) ||
5226 create_seq_dir(r) < 0)
5227 return -1;
5228 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5229 return error(_("can't revert as initial commit"));
5230 if (save_head(oid_to_hex(&oid)))
5231 return -1;
5232 if (save_opts(opts))
5233 return -1;
5234 update_abort_safety_file();
5235 res = pick_commits(r, &todo_list, opts);
5236 todo_list_release(&todo_list);
5237 return res;
5240 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5242 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5243 struct strbuf sob = STRBUF_INIT;
5244 int has_footer;
5246 strbuf_addstr(&sob, sign_off_header);
5247 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5248 strbuf_addch(&sob, '\n');
5250 if (!ignore_footer)
5251 strbuf_complete_line(msgbuf);
5254 * If the whole message buffer is equal to the sob, pretend that we
5255 * found a conforming footer with a matching sob
5257 if (msgbuf->len - ignore_footer == sob.len &&
5258 !strncmp(msgbuf->buf, sob.buf, sob.len))
5259 has_footer = 3;
5260 else
5261 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5263 if (!has_footer) {
5264 const char *append_newlines = NULL;
5265 size_t len = msgbuf->len - ignore_footer;
5267 if (!len) {
5269 * The buffer is completely empty. Leave foom for
5270 * the title and body to be filled in by the user.
5272 append_newlines = "\n\n";
5273 } else if (len == 1) {
5275 * Buffer contains a single newline. Add another
5276 * so that we leave room for the title and body.
5278 append_newlines = "\n";
5279 } else if (msgbuf->buf[len - 2] != '\n') {
5281 * Buffer ends with a single newline. Add another
5282 * so that there is an empty line between the message
5283 * body and the sob.
5285 append_newlines = "\n";
5286 } /* else, the buffer already ends with two newlines. */
5288 if (append_newlines)
5289 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5290 append_newlines, strlen(append_newlines));
5293 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5294 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5295 sob.buf, sob.len);
5297 strbuf_release(&sob);
5300 struct labels_entry {
5301 struct hashmap_entry entry;
5302 char label[FLEX_ARRAY];
5305 static int labels_cmp(const void *fndata UNUSED,
5306 const struct hashmap_entry *eptr,
5307 const struct hashmap_entry *entry_or_key, const void *key)
5309 const struct labels_entry *a, *b;
5311 a = container_of(eptr, const struct labels_entry, entry);
5312 b = container_of(entry_or_key, const struct labels_entry, entry);
5314 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5317 struct string_entry {
5318 struct oidmap_entry entry;
5319 char string[FLEX_ARRAY];
5322 struct label_state {
5323 struct oidmap commit2label;
5324 struct hashmap labels;
5325 struct strbuf buf;
5328 static const char *label_oid(struct object_id *oid, const char *label,
5329 struct label_state *state)
5331 struct labels_entry *labels_entry;
5332 struct string_entry *string_entry;
5333 struct object_id dummy;
5334 int i;
5336 string_entry = oidmap_get(&state->commit2label, oid);
5337 if (string_entry)
5338 return string_entry->string;
5341 * For "uninteresting" commits, i.e. commits that are not to be
5342 * rebased, and which can therefore not be labeled, we use a unique
5343 * abbreviation of the commit name. This is slightly more complicated
5344 * than calling repo_find_unique_abbrev() because we also need to make
5345 * sure that the abbreviation does not conflict with any other
5346 * label.
5348 * We disallow "interesting" commits to be labeled by a string that
5349 * is a valid full-length hash, to ensure that we always can find an
5350 * abbreviation for any uninteresting commit's names that does not
5351 * clash with any other label.
5353 strbuf_reset(&state->buf);
5354 if (!label) {
5355 char *p;
5357 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5358 label = p = state->buf.buf;
5360 repo_find_unique_abbrev_r(the_repository, p, oid,
5361 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 (repo_parse_commit(r, 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 repo_find_unique_abbrev_r(r, shortonto, &oid,
6095 DEFAULT_ABBREV);
6097 if (buf->len == 0) {
6098 struct todo_item *item = append_new_todo(todo_list);
6099 item->command = TODO_NOOP;
6100 item->commit = NULL;
6101 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6104 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6105 return -1;
6107 if (autosquash && todo_list_rearrange_squash(todo_list))
6108 return -1;
6110 if (commands->nr)
6111 todo_list_add_exec_commands(todo_list, commands);
6113 if (count_commands(todo_list) == 0) {
6114 apply_autostash(rebase_path_autostash());
6115 sequencer_remove_state(opts);
6117 return error(_("nothing to do"));
6120 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6121 shortonto, flags);
6122 if (res == -1)
6123 return -1;
6124 else if (res == -2) {
6125 apply_autostash(rebase_path_autostash());
6126 sequencer_remove_state(opts);
6128 return -1;
6129 } else if (res == -3) {
6130 apply_autostash(rebase_path_autostash());
6131 sequencer_remove_state(opts);
6132 todo_list_release(&new_todo);
6134 return error(_("nothing to do"));
6135 } else if (res == -4) {
6136 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6137 todo_list_release(&new_todo);
6139 return -1;
6142 /* Expand the commit IDs */
6143 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6144 strbuf_swap(&new_todo.buf, &buf2);
6145 strbuf_release(&buf2);
6146 new_todo.total_nr -= new_todo.nr;
6147 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6148 BUG("invalid todo list after expanding IDs:\n%s",
6149 new_todo.buf.buf);
6151 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6152 todo_list_release(&new_todo);
6153 return error(_("could not skip unnecessary pick commands"));
6156 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6157 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6158 todo_list_release(&new_todo);
6159 return error_errno(_("could not write '%s'"), todo_file);
6162 res = -1;
6164 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6165 goto cleanup;
6167 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6168 goto cleanup;
6170 todo_list_write_total_nr(&new_todo);
6171 res = pick_commits(r, &new_todo, opts);
6173 cleanup:
6174 todo_list_release(&new_todo);
6176 return res;
6179 struct subject2item_entry {
6180 struct hashmap_entry entry;
6181 int i;
6182 char subject[FLEX_ARRAY];
6185 static int subject2item_cmp(const void *fndata UNUSED,
6186 const struct hashmap_entry *eptr,
6187 const struct hashmap_entry *entry_or_key,
6188 const void *key)
6190 const struct subject2item_entry *a, *b;
6192 a = container_of(eptr, const struct subject2item_entry, entry);
6193 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6195 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6198 define_commit_slab(commit_todo_item, struct todo_item *);
6200 static int skip_fixupish(const char *subject, const char **p) {
6201 return skip_prefix(subject, "fixup! ", p) ||
6202 skip_prefix(subject, "amend! ", p) ||
6203 skip_prefix(subject, "squash! ", p);
6207 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6208 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6209 * after the former, and change "pick" to "fixup"/"squash".
6211 * Note that if the config has specified a custom instruction format, each log
6212 * message will have to be retrieved from the commit (as the oneline in the
6213 * script cannot be trusted) in order to normalize the autosquash arrangement.
6215 int todo_list_rearrange_squash(struct todo_list *todo_list)
6217 struct hashmap subject2item;
6218 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6219 char **subjects;
6220 struct commit_todo_item commit_todo;
6221 struct todo_item *items = NULL;
6223 init_commit_todo_item(&commit_todo);
6225 * The hashmap maps onelines to the respective todo list index.
6227 * If any items need to be rearranged, the next[i] value will indicate
6228 * which item was moved directly after the i'th.
6230 * In that case, last[i] will indicate the index of the latest item to
6231 * be moved to appear after the i'th.
6233 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6234 ALLOC_ARRAY(next, todo_list->nr);
6235 ALLOC_ARRAY(tail, todo_list->nr);
6236 ALLOC_ARRAY(subjects, todo_list->nr);
6237 for (i = 0; i < todo_list->nr; i++) {
6238 struct strbuf buf = STRBUF_INIT;
6239 struct todo_item *item = todo_list->items + i;
6240 const char *commit_buffer, *subject, *p;
6241 size_t subject_len;
6242 int i2 = -1;
6243 struct subject2item_entry *entry;
6245 next[i] = tail[i] = -1;
6246 if (!item->commit || item->command == TODO_DROP) {
6247 subjects[i] = NULL;
6248 continue;
6251 if (is_fixup(item->command)) {
6252 clear_commit_todo_item(&commit_todo);
6253 return error(_("the script was already rearranged."));
6256 repo_parse_commit(the_repository, item->commit);
6257 commit_buffer = repo_logmsg_reencode(the_repository,
6258 item->commit, NULL,
6259 "UTF-8");
6260 find_commit_subject(commit_buffer, &subject);
6261 format_subject(&buf, subject, " ");
6262 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6263 repo_unuse_commit_buffer(the_repository, item->commit,
6264 commit_buffer);
6265 if (skip_fixupish(subject, &p)) {
6266 struct commit *commit2;
6268 for (;;) {
6269 while (isspace(*p))
6270 p++;
6271 if (!skip_fixupish(p, &p))
6272 break;
6275 entry = hashmap_get_entry_from_hash(&subject2item,
6276 strhash(p), p,
6277 struct subject2item_entry,
6278 entry);
6279 if (entry)
6280 /* found by title */
6281 i2 = entry->i;
6282 else if (!strchr(p, ' ') &&
6283 (commit2 =
6284 lookup_commit_reference_by_name(p)) &&
6285 *commit_todo_item_at(&commit_todo, commit2))
6286 /* found by commit name */
6287 i2 = *commit_todo_item_at(&commit_todo, commit2)
6288 - todo_list->items;
6289 else {
6290 /* copy can be a prefix of the commit subject */
6291 for (i2 = 0; i2 < i; i2++)
6292 if (subjects[i2] &&
6293 starts_with(subjects[i2], p))
6294 break;
6295 if (i2 == i)
6296 i2 = -1;
6299 if (i2 >= 0) {
6300 rearranged = 1;
6301 if (starts_with(subject, "fixup!")) {
6302 todo_list->items[i].command = TODO_FIXUP;
6303 } else if (starts_with(subject, "amend!")) {
6304 todo_list->items[i].command = TODO_FIXUP;
6305 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6306 } else {
6307 todo_list->items[i].command = TODO_SQUASH;
6309 if (tail[i2] < 0) {
6310 next[i] = next[i2];
6311 next[i2] = i;
6312 } else {
6313 next[i] = next[tail[i2]];
6314 next[tail[i2]] = i;
6316 tail[i2] = i;
6317 } else if (!hashmap_get_from_hash(&subject2item,
6318 strhash(subject), subject)) {
6319 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6320 entry->i = i;
6321 hashmap_entry_init(&entry->entry,
6322 strhash(entry->subject));
6323 hashmap_put(&subject2item, &entry->entry);
6326 *commit_todo_item_at(&commit_todo, item->commit) = item;
6329 if (rearranged) {
6330 for (i = 0; i < todo_list->nr; i++) {
6331 enum todo_command command = todo_list->items[i].command;
6332 int cur = i;
6335 * Initially, all commands are 'pick's. If it is a
6336 * fixup or a squash now, we have rearranged it.
6338 if (is_fixup(command))
6339 continue;
6341 while (cur >= 0) {
6342 ALLOC_GROW(items, nr + 1, alloc);
6343 items[nr++] = todo_list->items[cur];
6344 cur = next[cur];
6348 FREE_AND_NULL(todo_list->items);
6349 todo_list->items = items;
6350 todo_list->nr = nr;
6351 todo_list->alloc = alloc;
6354 free(next);
6355 free(tail);
6356 for (i = 0; i < todo_list->nr; i++)
6357 free(subjects[i]);
6358 free(subjects);
6359 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6361 clear_commit_todo_item(&commit_todo);
6363 return 0;
6366 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6368 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6369 struct object_id cherry_pick_head, rebase_head;
6371 if (file_exists(git_path_seq_dir()))
6372 *whence = FROM_CHERRY_PICK_MULTI;
6373 if (file_exists(rebase_path()) &&
6374 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6375 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6376 oideq(&rebase_head, &cherry_pick_head))
6377 *whence = FROM_REBASE_PICK;
6378 else
6379 *whence = FROM_CHERRY_PICK_SINGLE;
6381 return 1;
6384 return 0;
6387 int sequencer_get_update_refs_state(const char *wt_dir,
6388 struct string_list *refs)
6390 int result = 0;
6391 FILE *fp = NULL;
6392 struct strbuf ref = STRBUF_INIT;
6393 struct strbuf hash = STRBUF_INIT;
6394 struct update_ref_record *rec = NULL;
6396 char *path = rebase_path_update_refs(wt_dir);
6398 fp = fopen(path, "r");
6399 if (!fp)
6400 goto cleanup;
6402 while (strbuf_getline(&ref, fp) != EOF) {
6403 struct string_list_item *item;
6405 CALLOC_ARRAY(rec, 1);
6407 if (strbuf_getline(&hash, fp) == EOF ||
6408 get_oid_hex(hash.buf, &rec->before)) {
6409 warning(_("update-refs file at '%s' is invalid"),
6410 path);
6411 result = -1;
6412 goto cleanup;
6415 if (strbuf_getline(&hash, fp) == EOF ||
6416 get_oid_hex(hash.buf, &rec->after)) {
6417 warning(_("update-refs file at '%s' is invalid"),
6418 path);
6419 result = -1;
6420 goto cleanup;
6423 item = string_list_insert(refs, ref.buf);
6424 item->util = rec;
6425 rec = NULL;
6428 cleanup:
6429 if (fp)
6430 fclose(fp);
6431 free(path);
6432 free(rec);
6433 strbuf_release(&ref);
6434 strbuf_release(&hash);
6435 return result;