t7701: make annotated tag unreachable
[git/debian.git] / sequencer.c
blobc88d1d95538fbb12b5887e34dd8b790aecd706ab
1 #include "cache.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "alloc.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store.h"
14 #include "object.h"
15 #include "pager.h"
16 #include "commit.h"
17 #include "sequencer.h"
18 #include "tag.h"
19 #include "run-command.h"
20 #include "hook.h"
21 #include "exec-cmd.h"
22 #include "utf8.h"
23 #include "cache-tree.h"
24 #include "diff.h"
25 #include "revision.h"
26 #include "rerere.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
29 #include "refs.h"
30 #include "strvec.h"
31 #include "quote.h"
32 #include "trailer.h"
33 #include "log-tree.h"
34 #include "wt-status.h"
35 #include "hashmap.h"
36 #include "notes-utils.h"
37 #include "sigchain.h"
38 #include "unpack-trees.h"
39 #include "worktree.h"
40 #include "oidmap.h"
41 #include "oidset.h"
42 #include "commit-slab.h"
43 #include "alias.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
46 #include "reset.h"
47 #include "branch.h"
48 #include "wrapper.h"
50 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 static const char sign_off_header[] = "Signed-off-by: ";
53 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
55 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
57 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
59 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
60 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
61 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
62 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
64 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
66 * The file containing rebase commands, comments, and empty lines.
67 * This file is created by "git rebase -i" then edited by the user. As
68 * the lines are processed, they are removed from the front of this
69 * file and written to the tail of 'done'.
71 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
72 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
74 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
77 * The rebase command lines that have already been processed. A line
78 * is moved here when it is first handled, before any associated user
79 * actions.
81 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
83 * The file to keep track of how many commands were already processed (e.g.
84 * for the prompt).
86 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
88 * The file to keep track of how many commands are to be processed in total
89 * (e.g. for the prompt).
91 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
93 * The commit message that is planned to be used for any changes that
94 * need to be committed following a user interaction.
96 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
98 * The file into which is accumulated the suggested commit message for
99 * squash/fixup commands. When the first of a series of squash/fixups
100 * is seen, the file is created and the commit message from the
101 * previous commit and from the first squash/fixup commit are written
102 * to it. The commit message for each subsequent squash/fixup commit
103 * is appended to the file as it is processed.
105 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
107 * If the current series of squash/fixups has not yet included a squash
108 * command, then this file exists and holds the commit message of the
109 * original "pick" commit. (If the series ends without a "squash"
110 * command, then this can be used as the commit message of the combined
111 * commit without opening the editor.)
113 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
115 * This file contains the list fixup/squash commands that have been
116 * accumulated into message-fixup or message-squash so far.
118 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
120 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
121 * GIT_AUTHOR_DATE that will be used for the commit that is currently
122 * being rebased.
124 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
126 * When an "edit" rebase command is being processed, the SHA1 of the
127 * commit to be edited is recorded in this file. When "git rebase
128 * --continue" is executed, if there are any staged changes then they
129 * will be amended to the HEAD commit, but only provided the HEAD
130 * commit is still the commit to be edited. When any other rebase
131 * command is processed, this file is deleted.
133 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
135 * When we stop at a given patch via the "edit" command, this file contains
136 * the commit object name of the corresponding patch.
138 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
140 * For the post-rewrite hook, we make a list of rewritten commits and
141 * their new sha1s. The rewritten-pending list keeps the sha1s of
142 * commits that have been processed, but not committed yet,
143 * e.g. because they are waiting for a 'squash' command.
145 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
146 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
147 "rebase-merge/rewritten-pending")
150 * The path of the file containing the OID of the "squash onto" commit, i.e.
151 * the dummy commit used for `reset [new root]`.
153 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
156 * The path of the file listing refs that need to be deleted after the rebase
157 * finishes. This is used by the `label` command to record the need for cleanup.
159 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
162 * The update-refs file stores a list of refs that will be updated at the end
163 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
164 * update the OIDs for the refs in this file, but the refs are not updated
165 * until the end of the rebase sequence.
167 * rebase_path_update_refs() returns the path to this file for a given
168 * worktree directory. For the current worktree, pass the_repository->gitdir.
170 static char *rebase_path_update_refs(const char *wt_git_dir)
172 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
176 * The following files are written by git-rebase just after parsing the
177 * command-line.
179 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
180 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
181 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
182 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
183 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
184 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
185 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
186 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
187 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
188 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
189 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
190 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
191 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
192 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
193 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
194 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
195 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
198 * A 'struct update_refs_record' represents a value in the update-refs
199 * list. We use a string_list to map refs to these (before, after) pairs.
201 struct update_ref_record {
202 struct object_id before;
203 struct object_id after;
206 static struct update_ref_record *init_update_ref_record(const char *ref)
208 struct update_ref_record *rec;
210 CALLOC_ARRAY(rec, 1);
212 oidcpy(&rec->before, null_oid());
213 oidcpy(&rec->after, null_oid());
215 /* This may fail, but that's fine, we will keep the null OID. */
216 read_ref(ref, &rec->before);
218 return rec;
221 static int git_sequencer_config(const char *k, const char *v, void *cb)
223 struct replay_opts *opts = cb;
224 int status;
226 if (!strcmp(k, "commit.cleanup")) {
227 const char *s;
229 status = git_config_string(&s, k, v);
230 if (status)
231 return status;
233 if (!strcmp(s, "verbatim")) {
234 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
235 opts->explicit_cleanup = 1;
236 } else if (!strcmp(s, "whitespace")) {
237 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
238 opts->explicit_cleanup = 1;
239 } else if (!strcmp(s, "strip")) {
240 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
241 opts->explicit_cleanup = 1;
242 } else if (!strcmp(s, "scissors")) {
243 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
244 opts->explicit_cleanup = 1;
245 } else {
246 warning(_("invalid commit message cleanup mode '%s'"),
250 free((char *)s);
251 return status;
254 if (!strcmp(k, "commit.gpgsign")) {
255 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
256 return 0;
259 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
260 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
261 if (ret == 0) {
263 * pull.twohead is allowed to be multi-valued; we only
264 * care about the first value.
266 char *tmp = strchr(opts->default_strategy, ' ');
267 if (tmp)
268 *tmp = '\0';
270 return ret;
273 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
274 opts->commit_use_reference = git_config_bool(k, v);
276 return git_diff_basic_config(k, v, NULL);
279 void sequencer_init_config(struct replay_opts *opts)
281 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
282 git_config(git_sequencer_config, opts);
285 static inline int is_rebase_i(const struct replay_opts *opts)
287 return opts->action == REPLAY_INTERACTIVE_REBASE;
290 static const char *get_dir(const struct replay_opts *opts)
292 if (is_rebase_i(opts))
293 return rebase_path();
294 return git_path_seq_dir();
297 static const char *get_todo_path(const struct replay_opts *opts)
299 if (is_rebase_i(opts))
300 return rebase_path_todo();
301 return git_path_todo_file();
305 * Returns 0 for non-conforming footer
306 * Returns 1 for conforming footer
307 * Returns 2 when sob exists within conforming footer
308 * Returns 3 when sob exists within conforming footer as last entry
310 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
311 size_t ignore_footer)
313 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
314 struct trailer_info info;
315 size_t i;
316 int found_sob = 0, found_sob_last = 0;
317 char saved_char;
319 opts.no_divider = 1;
321 if (ignore_footer) {
322 saved_char = sb->buf[sb->len - ignore_footer];
323 sb->buf[sb->len - ignore_footer] = '\0';
326 trailer_info_get(&info, sb->buf, &opts);
328 if (ignore_footer)
329 sb->buf[sb->len - ignore_footer] = saved_char;
331 if (info.trailer_start == info.trailer_end)
332 return 0;
334 for (i = 0; i < info.trailer_nr; i++)
335 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
336 found_sob = 1;
337 if (i == info.trailer_nr - 1)
338 found_sob_last = 1;
341 trailer_info_release(&info);
343 if (found_sob_last)
344 return 3;
345 if (found_sob)
346 return 2;
347 return 1;
350 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
352 static struct strbuf buf = STRBUF_INIT;
354 strbuf_reset(&buf);
355 if (opts->gpg_sign)
356 sq_quotef(&buf, "-S%s", opts->gpg_sign);
357 return buf.buf;
360 void replay_opts_release(struct replay_opts *opts)
362 free(opts->gpg_sign);
363 free(opts->reflog_action);
364 free(opts->default_strategy);
365 free(opts->strategy);
366 strvec_clear (&opts->xopts);
367 strbuf_release(&opts->current_fixups);
368 if (opts->revs)
369 release_revisions(opts->revs);
370 free(opts->revs);
373 int sequencer_remove_state(struct replay_opts *opts)
375 struct strbuf buf = STRBUF_INIT;
376 int ret = 0;
378 if (is_rebase_i(opts) &&
379 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
380 char *p = buf.buf;
381 while (*p) {
382 char *eol = strchr(p, '\n');
383 if (eol)
384 *eol = '\0';
385 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
386 warning(_("could not delete '%s'"), p);
387 ret = -1;
389 if (!eol)
390 break;
391 p = eol + 1;
395 strbuf_reset(&buf);
396 strbuf_addstr(&buf, get_dir(opts));
397 if (remove_dir_recursively(&buf, 0))
398 ret = error(_("could not remove '%s'"), buf.buf);
399 strbuf_release(&buf);
401 return ret;
404 static const char *action_name(const struct replay_opts *opts)
406 switch (opts->action) {
407 case REPLAY_REVERT:
408 return N_("revert");
409 case REPLAY_PICK:
410 return N_("cherry-pick");
411 case REPLAY_INTERACTIVE_REBASE:
412 return N_("rebase");
414 die(_("unknown action: %d"), opts->action);
417 struct commit_message {
418 char *parent_label;
419 char *label;
420 char *subject;
421 const char *message;
424 static const char *short_commit_name(struct commit *commit)
426 return repo_find_unique_abbrev(the_repository, &commit->object.oid,
427 DEFAULT_ABBREV);
430 static int get_message(struct commit *commit, struct commit_message *out)
432 const char *abbrev, *subject;
433 int subject_len;
435 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
436 get_commit_output_encoding());
437 abbrev = short_commit_name(commit);
439 subject_len = find_commit_subject(out->message, &subject);
441 out->subject = xmemdupz(subject, subject_len);
442 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
443 out->parent_label = xstrfmt("parent of %s", out->label);
445 return 0;
448 static void free_message(struct commit *commit, struct commit_message *msg)
450 free(msg->parent_label);
451 free(msg->label);
452 free(msg->subject);
453 repo_unuse_commit_buffer(the_repository, commit, msg->message);
456 static void print_advice(struct repository *r, int show_hint,
457 struct replay_opts *opts)
459 char *msg = getenv("GIT_CHERRY_PICK_HELP");
461 if (msg) {
462 advise("%s\n", msg);
464 * A conflict has occurred but the porcelain
465 * (typically rebase --interactive) wants to take care
466 * of the commit itself so remove CHERRY_PICK_HEAD
468 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
469 NULL, 0);
470 return;
473 if (show_hint) {
474 if (opts->no_commit)
475 advise(_("after resolving the conflicts, mark the corrected paths\n"
476 "with 'git add <paths>' or 'git rm <paths>'"));
477 else if (opts->action == REPLAY_PICK)
478 advise(_("After resolving the conflicts, mark them with\n"
479 "\"git add/rm <pathspec>\", then run\n"
480 "\"git cherry-pick --continue\".\n"
481 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
482 "To abort and get back to the state before \"git cherry-pick\",\n"
483 "run \"git cherry-pick --abort\"."));
484 else if (opts->action == REPLAY_REVERT)
485 advise(_("After resolving the conflicts, mark them with\n"
486 "\"git add/rm <pathspec>\", then run\n"
487 "\"git revert --continue\".\n"
488 "You can instead skip this commit with \"git revert --skip\".\n"
489 "To abort and get back to the state before \"git revert\",\n"
490 "run \"git revert --abort\"."));
491 else
492 BUG("unexpected pick action in print_advice()");
496 static int write_message(const void *buf, size_t len, const char *filename,
497 int append_eol)
499 struct lock_file msg_file = LOCK_INIT;
501 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
502 if (msg_fd < 0)
503 return error_errno(_("could not lock '%s'"), filename);
504 if (write_in_full(msg_fd, buf, len) < 0) {
505 error_errno(_("could not write to '%s'"), filename);
506 rollback_lock_file(&msg_file);
507 return -1;
509 if (append_eol && write(msg_fd, "\n", 1) < 0) {
510 error_errno(_("could not write eol to '%s'"), filename);
511 rollback_lock_file(&msg_file);
512 return -1;
514 if (commit_lock_file(&msg_file) < 0)
515 return error(_("failed to finalize '%s'"), filename);
517 return 0;
520 int read_oneliner(struct strbuf *buf,
521 const char *path, unsigned flags)
523 int orig_len = buf->len;
525 if (strbuf_read_file(buf, path, 0) < 0) {
526 if ((flags & READ_ONELINER_WARN_MISSING) ||
527 (errno != ENOENT && errno != ENOTDIR))
528 warning_errno(_("could not read '%s'"), path);
529 return 0;
532 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
533 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
534 --buf->len;
535 buf->buf[buf->len] = '\0';
538 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
539 return 0;
541 return 1;
544 static struct tree *empty_tree(struct repository *r)
546 return lookup_tree(r, the_hash_algo->empty_tree);
549 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
551 if (repo_read_index_unmerged(repo))
552 return error_resolve_conflict(action_name(opts));
554 error(_("your local changes would be overwritten by %s."),
555 _(action_name(opts)));
557 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
558 advise(_("commit your changes or stash them to proceed."));
559 return -1;
562 static void update_abort_safety_file(void)
564 struct object_id head;
566 /* Do nothing on a single-pick */
567 if (!file_exists(git_path_seq_dir()))
568 return;
570 if (!repo_get_oid(the_repository, "HEAD", &head))
571 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
572 else
573 write_file(git_path_abort_safety_file(), "%s", "");
576 static int fast_forward_to(struct repository *r,
577 const struct object_id *to,
578 const struct object_id *from,
579 int unborn,
580 struct replay_opts *opts)
582 struct ref_transaction *transaction;
583 struct strbuf sb = STRBUF_INIT;
584 struct strbuf err = STRBUF_INIT;
586 repo_read_index(r);
587 if (checkout_fast_forward(r, from, to, 1))
588 return -1; /* the callee should have complained already */
590 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
592 transaction = ref_transaction_begin(&err);
593 if (!transaction ||
594 ref_transaction_update(transaction, "HEAD",
595 to, unborn && !is_rebase_i(opts) ?
596 null_oid() : from,
597 0, sb.buf, &err) ||
598 ref_transaction_commit(transaction, &err)) {
599 ref_transaction_free(transaction);
600 error("%s", err.buf);
601 strbuf_release(&sb);
602 strbuf_release(&err);
603 return -1;
606 strbuf_release(&sb);
607 strbuf_release(&err);
608 ref_transaction_free(transaction);
609 update_abort_safety_file();
610 return 0;
613 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
614 int use_editor)
616 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
617 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
618 COMMIT_MSG_CLEANUP_SPACE;
619 else if (!strcmp(cleanup_arg, "verbatim"))
620 return COMMIT_MSG_CLEANUP_NONE;
621 else if (!strcmp(cleanup_arg, "whitespace"))
622 return COMMIT_MSG_CLEANUP_SPACE;
623 else if (!strcmp(cleanup_arg, "strip"))
624 return COMMIT_MSG_CLEANUP_ALL;
625 else if (!strcmp(cleanup_arg, "scissors"))
626 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
627 COMMIT_MSG_CLEANUP_SPACE;
628 else
629 die(_("Invalid cleanup mode %s"), cleanup_arg);
633 * NB using int rather than enum cleanup_mode to stop clang's
634 * -Wtautological-constant-out-of-range-compare complaining that the comparison
635 * is always true.
637 static const char *describe_cleanup_mode(int cleanup_mode)
639 static const char *modes[] = { "whitespace",
640 "verbatim",
641 "scissors",
642 "strip" };
644 if (cleanup_mode < ARRAY_SIZE(modes))
645 return modes[cleanup_mode];
647 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
650 void append_conflicts_hint(struct index_state *istate,
651 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
653 int i;
655 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
656 strbuf_addch(msgbuf, '\n');
657 wt_status_append_cut_line(msgbuf);
658 strbuf_addch(msgbuf, comment_line_char);
661 strbuf_addch(msgbuf, '\n');
662 strbuf_commented_addf(msgbuf, "Conflicts:\n");
663 for (i = 0; i < istate->cache_nr;) {
664 const struct cache_entry *ce = istate->cache[i++];
665 if (ce_stage(ce)) {
666 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
667 while (i < istate->cache_nr &&
668 !strcmp(ce->name, istate->cache[i]->name))
669 i++;
674 static int do_recursive_merge(struct repository *r,
675 struct commit *base, struct commit *next,
676 const char *base_label, const char *next_label,
677 struct object_id *head, struct strbuf *msgbuf,
678 struct replay_opts *opts)
680 struct merge_options o;
681 struct merge_result result;
682 struct tree *next_tree, *base_tree, *head_tree;
683 int clean, show_output;
684 int i;
685 struct lock_file index_lock = LOCK_INIT;
687 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
688 return -1;
690 repo_read_index(r);
692 init_merge_options(&o, r);
693 o.ancestor = base ? base_label : "(empty tree)";
694 o.branch1 = "HEAD";
695 o.branch2 = next ? next_label : "(empty tree)";
696 if (is_rebase_i(opts))
697 o.buffer_output = 2;
698 o.show_rename_progress = 1;
700 head_tree = parse_tree_indirect(head);
701 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
702 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
704 for (i = 0; i < opts->xopts.nr; i++)
705 parse_merge_opt(&o, opts->xopts.v[i]);
707 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
708 memset(&result, 0, sizeof(result));
709 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
710 &result);
711 show_output = !is_rebase_i(opts) || !result.clean;
713 * TODO: merge_switch_to_result will update index/working tree;
714 * we only really want to do that if !result.clean || this is
715 * the final patch to be picked. But determining this is the
716 * final patch would take some work, and "head_tree" would need
717 * to be replace with the tree the index matched before we
718 * started doing any picks.
720 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
721 clean = result.clean;
722 } else {
723 ensure_full_index(r->index);
724 clean = merge_trees(&o, head_tree, next_tree, base_tree);
725 if (is_rebase_i(opts) && clean <= 0)
726 fputs(o.obuf.buf, stdout);
727 strbuf_release(&o.obuf);
729 if (clean < 0) {
730 rollback_lock_file(&index_lock);
731 return clean;
734 if (write_locked_index(r->index, &index_lock,
735 COMMIT_LOCK | SKIP_IF_UNCHANGED))
737 * TRANSLATORS: %s will be "revert", "cherry-pick" or
738 * "rebase".
740 return error(_("%s: Unable to write new index file"),
741 _(action_name(opts)));
743 if (!clean)
744 append_conflicts_hint(r->index, msgbuf,
745 opts->default_msg_cleanup);
747 return !clean;
750 static struct object_id *get_cache_tree_oid(struct index_state *istate)
752 if (!cache_tree_fully_valid(istate->cache_tree))
753 if (cache_tree_update(istate, 0)) {
754 error(_("unable to update cache tree"));
755 return NULL;
758 return &istate->cache_tree->oid;
761 static int is_index_unchanged(struct repository *r)
763 struct object_id head_oid, *cache_tree_oid;
764 struct commit *head_commit;
765 struct index_state *istate = r->index;
767 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
768 return error(_("could not resolve HEAD commit"));
770 head_commit = lookup_commit(r, &head_oid);
773 * If head_commit is NULL, check_commit, called from
774 * lookup_commit, would have indicated that head_commit is not
775 * a commit object already. repo_parse_commit() will return failure
776 * without further complaints in such a case. Otherwise, if
777 * the commit is invalid, repo_parse_commit() will complain. So
778 * there is nothing for us to say here. Just return failure.
780 if (repo_parse_commit(r, head_commit))
781 return -1;
783 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
784 return -1;
786 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
789 static int write_author_script(const char *message)
791 struct strbuf buf = STRBUF_INIT;
792 const char *eol;
793 int res;
795 for (;;)
796 if (!*message || starts_with(message, "\n")) {
797 missing_author:
798 /* Missing 'author' line? */
799 unlink(rebase_path_author_script());
800 return 0;
801 } else if (skip_prefix(message, "author ", &message))
802 break;
803 else if ((eol = strchr(message, '\n')))
804 message = eol + 1;
805 else
806 goto missing_author;
808 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
809 while (*message && *message != '\n' && *message != '\r')
810 if (skip_prefix(message, " <", &message))
811 break;
812 else if (*message != '\'')
813 strbuf_addch(&buf, *(message++));
814 else
815 strbuf_addf(&buf, "'\\%c'", *(message++));
816 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
817 while (*message && *message != '\n' && *message != '\r')
818 if (skip_prefix(message, "> ", &message))
819 break;
820 else if (*message != '\'')
821 strbuf_addch(&buf, *(message++));
822 else
823 strbuf_addf(&buf, "'\\%c'", *(message++));
824 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
825 while (*message && *message != '\n' && *message != '\r')
826 if (*message != '\'')
827 strbuf_addch(&buf, *(message++));
828 else
829 strbuf_addf(&buf, "'\\%c'", *(message++));
830 strbuf_addch(&buf, '\'');
831 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
832 strbuf_release(&buf);
833 return res;
837 * Take a series of KEY='VALUE' lines where VALUE part is
838 * sq-quoted, and append <KEY, VALUE> at the end of the string list
840 static int parse_key_value_squoted(char *buf, struct string_list *list)
842 while (*buf) {
843 struct string_list_item *item;
844 char *np;
845 char *cp = strchr(buf, '=');
846 if (!cp) {
847 np = strchrnul(buf, '\n');
848 return error(_("no key present in '%.*s'"),
849 (int) (np - buf), buf);
851 np = strchrnul(cp, '\n');
852 *cp++ = '\0';
853 item = string_list_append(list, buf);
855 buf = np + (*np == '\n');
856 *np = '\0';
857 cp = sq_dequote(cp);
858 if (!cp)
859 return error(_("unable to dequote value of '%s'"),
860 item->string);
861 item->util = xstrdup(cp);
863 return 0;
867 * Reads and parses the state directory's "author-script" file, and sets name,
868 * email and date accordingly.
869 * Returns 0 on success, -1 if the file could not be parsed.
871 * The author script is of the format:
873 * GIT_AUTHOR_NAME='$author_name'
874 * GIT_AUTHOR_EMAIL='$author_email'
875 * GIT_AUTHOR_DATE='$author_date'
877 * where $author_name, $author_email and $author_date are quoted. We are strict
878 * with our parsing, as the file was meant to be eval'd in the now-removed
879 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
880 * from what this function expects, it is better to bail out than to do
881 * something that the user does not expect.
883 int read_author_script(const char *path, char **name, char **email, char **date,
884 int allow_missing)
886 struct strbuf buf = STRBUF_INIT;
887 struct string_list kv = STRING_LIST_INIT_DUP;
888 int retval = -1; /* assume failure */
889 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
891 if (strbuf_read_file(&buf, path, 256) <= 0) {
892 strbuf_release(&buf);
893 if (errno == ENOENT && allow_missing)
894 return 0;
895 else
896 return error_errno(_("could not open '%s' for reading"),
897 path);
900 if (parse_key_value_squoted(buf.buf, &kv))
901 goto finish;
903 for (i = 0; i < kv.nr; i++) {
904 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
905 if (name_i != -2)
906 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
907 else
908 name_i = i;
909 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
910 if (email_i != -2)
911 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
912 else
913 email_i = i;
914 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
915 if (date_i != -2)
916 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
917 else
918 date_i = i;
919 } else {
920 err = error(_("unknown variable '%s'"),
921 kv.items[i].string);
924 if (name_i == -2)
925 error(_("missing 'GIT_AUTHOR_NAME'"));
926 if (email_i == -2)
927 error(_("missing 'GIT_AUTHOR_EMAIL'"));
928 if (date_i == -2)
929 error(_("missing 'GIT_AUTHOR_DATE'"));
930 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
931 goto finish;
932 *name = kv.items[name_i].util;
933 *email = kv.items[email_i].util;
934 *date = kv.items[date_i].util;
935 retval = 0;
936 finish:
937 string_list_clear(&kv, !!retval);
938 strbuf_release(&buf);
939 return retval;
943 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
944 * file with shell quoting into struct strvec. Returns -1 on
945 * error, 0 otherwise.
947 static int read_env_script(struct strvec *env)
949 char *name, *email, *date;
951 if (read_author_script(rebase_path_author_script(),
952 &name, &email, &date, 0))
953 return -1;
955 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
956 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
957 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
958 free(name);
959 free(email);
960 free(date);
962 return 0;
965 static char *get_author(const char *message)
967 size_t len;
968 const char *a;
970 a = find_commit_header(message, "author", &len);
971 if (a)
972 return xmemdupz(a, len);
974 return NULL;
977 static const char *author_date_from_env(const struct strvec *env)
979 int i;
980 const char *date;
982 for (i = 0; i < env->nr; i++)
983 if (skip_prefix(env->v[i],
984 "GIT_AUTHOR_DATE=", &date))
985 return date;
987 * If GIT_AUTHOR_DATE is missing we should have already errored out when
988 * reading the script
990 BUG("GIT_AUTHOR_DATE missing from author script");
993 static const char staged_changes_advice[] =
994 N_("you have staged changes in your working tree\n"
995 "If these changes are meant to be squashed into the previous commit, run:\n"
996 "\n"
997 " git commit --amend %s\n"
998 "\n"
999 "If they are meant to go into a new commit, run:\n"
1000 "\n"
1001 " git commit %s\n"
1002 "\n"
1003 "In both cases, once you're done, continue with:\n"
1004 "\n"
1005 " git rebase --continue\n");
1007 #define ALLOW_EMPTY (1<<0)
1008 #define EDIT_MSG (1<<1)
1009 #define AMEND_MSG (1<<2)
1010 #define CLEANUP_MSG (1<<3)
1011 #define VERIFY_MSG (1<<4)
1012 #define CREATE_ROOT_COMMIT (1<<5)
1013 #define VERBATIM_MSG (1<<6)
1015 static int run_command_silent_on_success(struct child_process *cmd)
1017 struct strbuf buf = STRBUF_INIT;
1018 int rc;
1020 cmd->stdout_to_stderr = 1;
1021 rc = pipe_command(cmd,
1022 NULL, 0,
1023 NULL, 0,
1024 &buf, 0);
1026 if (rc)
1027 fputs(buf.buf, stderr);
1028 strbuf_release(&buf);
1029 return rc;
1033 * If we are cherry-pick, and if the merge did not result in
1034 * hand-editing, we will hit this commit and inherit the original
1035 * author date and name.
1037 * If we are revert, or if our cherry-pick results in a hand merge,
1038 * we had better say that the current user is responsible for that.
1040 * An exception is when run_git_commit() is called during an
1041 * interactive rebase: in that case, we will want to retain the
1042 * author metadata.
1044 static int run_git_commit(const char *defmsg,
1045 struct replay_opts *opts,
1046 unsigned int flags)
1048 struct child_process cmd = CHILD_PROCESS_INIT;
1050 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1051 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1053 cmd.git_cmd = 1;
1055 if (is_rebase_i(opts) &&
1056 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1057 !(!defmsg && (flags & AMEND_MSG))) &&
1058 read_env_script(&cmd.env)) {
1059 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1061 return error(_(staged_changes_advice),
1062 gpg_opt, gpg_opt);
1065 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1067 if (opts->committer_date_is_author_date)
1068 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1069 opts->ignore_date ?
1070 "" :
1071 author_date_from_env(&cmd.env));
1072 if (opts->ignore_date)
1073 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1075 strvec_push(&cmd.args, "commit");
1077 if (!(flags & VERIFY_MSG))
1078 strvec_push(&cmd.args, "-n");
1079 if ((flags & AMEND_MSG))
1080 strvec_push(&cmd.args, "--amend");
1081 if (opts->gpg_sign)
1082 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1083 else
1084 strvec_push(&cmd.args, "--no-gpg-sign");
1085 if (defmsg)
1086 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1087 else if (!(flags & EDIT_MSG))
1088 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1089 if ((flags & CLEANUP_MSG))
1090 strvec_push(&cmd.args, "--cleanup=strip");
1091 if ((flags & VERBATIM_MSG))
1092 strvec_push(&cmd.args, "--cleanup=verbatim");
1093 if ((flags & EDIT_MSG))
1094 strvec_push(&cmd.args, "-e");
1095 else if (!(flags & CLEANUP_MSG) &&
1096 !opts->signoff && !opts->record_origin &&
1097 !opts->explicit_cleanup)
1098 strvec_push(&cmd.args, "--cleanup=verbatim");
1100 if ((flags & ALLOW_EMPTY))
1101 strvec_push(&cmd.args, "--allow-empty");
1103 if (!(flags & EDIT_MSG))
1104 strvec_push(&cmd.args, "--allow-empty-message");
1106 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1107 return run_command_silent_on_success(&cmd);
1108 else
1109 return run_command(&cmd);
1112 static int rest_is_empty(const struct strbuf *sb, int start)
1114 int i, eol;
1115 const char *nl;
1117 /* Check if the rest is just whitespace and Signed-off-by's. */
1118 for (i = start; i < sb->len; i++) {
1119 nl = memchr(sb->buf + i, '\n', sb->len - i);
1120 if (nl)
1121 eol = nl - sb->buf;
1122 else
1123 eol = sb->len;
1125 if (strlen(sign_off_header) <= eol - i &&
1126 starts_with(sb->buf + i, sign_off_header)) {
1127 i = eol;
1128 continue;
1130 while (i < eol)
1131 if (!isspace(sb->buf[i++]))
1132 return 0;
1135 return 1;
1138 void cleanup_message(struct strbuf *msgbuf,
1139 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1141 if (verbose || /* Truncate the message just before the diff, if any. */
1142 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1143 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1144 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1145 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1149 * Find out if the message in the strbuf contains only whitespace and
1150 * Signed-off-by lines.
1152 int message_is_empty(const struct strbuf *sb,
1153 enum commit_msg_cleanup_mode cleanup_mode)
1155 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1156 return 0;
1157 return rest_is_empty(sb, 0);
1161 * See if the user edited the message in the editor or left what
1162 * was in the template intact
1164 int template_untouched(const struct strbuf *sb, const char *template_file,
1165 enum commit_msg_cleanup_mode cleanup_mode)
1167 struct strbuf tmpl = STRBUF_INIT;
1168 const char *start;
1170 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1171 return 0;
1173 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1174 return 0;
1176 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1177 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1178 start = sb->buf;
1179 strbuf_release(&tmpl);
1180 return rest_is_empty(sb, start - sb->buf);
1183 int update_head_with_reflog(const struct commit *old_head,
1184 const struct object_id *new_head,
1185 const char *action, const struct strbuf *msg,
1186 struct strbuf *err)
1188 struct ref_transaction *transaction;
1189 struct strbuf sb = STRBUF_INIT;
1190 const char *nl;
1191 int ret = 0;
1193 if (action) {
1194 strbuf_addstr(&sb, action);
1195 strbuf_addstr(&sb, ": ");
1198 nl = strchr(msg->buf, '\n');
1199 if (nl) {
1200 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1201 } else {
1202 strbuf_addbuf(&sb, msg);
1203 strbuf_addch(&sb, '\n');
1206 transaction = ref_transaction_begin(err);
1207 if (!transaction ||
1208 ref_transaction_update(transaction, "HEAD", new_head,
1209 old_head ? &old_head->object.oid : null_oid(),
1210 0, sb.buf, err) ||
1211 ref_transaction_commit(transaction, err)) {
1212 ret = -1;
1214 ref_transaction_free(transaction);
1215 strbuf_release(&sb);
1217 return ret;
1220 static int run_rewrite_hook(const struct object_id *oldoid,
1221 const struct object_id *newoid)
1223 struct child_process proc = CHILD_PROCESS_INIT;
1224 int code;
1225 struct strbuf sb = STRBUF_INIT;
1226 const char *hook_path = find_hook("post-rewrite");
1228 if (!hook_path)
1229 return 0;
1231 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1232 proc.in = -1;
1233 proc.stdout_to_stderr = 1;
1234 proc.trace2_hook_name = "post-rewrite";
1236 code = start_command(&proc);
1237 if (code)
1238 return code;
1239 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1240 sigchain_push(SIGPIPE, SIG_IGN);
1241 write_in_full(proc.in, sb.buf, sb.len);
1242 close(proc.in);
1243 strbuf_release(&sb);
1244 sigchain_pop(SIGPIPE);
1245 return finish_command(&proc);
1248 void commit_post_rewrite(struct repository *r,
1249 const struct commit *old_head,
1250 const struct object_id *new_head)
1252 struct notes_rewrite_cfg *cfg;
1254 cfg = init_copy_notes_for_rewrite("amend");
1255 if (cfg) {
1256 /* we are amending, so old_head is not NULL */
1257 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1258 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1260 run_rewrite_hook(&old_head->object.oid, new_head);
1263 static int run_prepare_commit_msg_hook(struct repository *r,
1264 struct strbuf *msg,
1265 const char *commit)
1267 int ret = 0;
1268 const char *name, *arg1 = NULL, *arg2 = NULL;
1270 name = git_path_commit_editmsg();
1271 if (write_message(msg->buf, msg->len, name, 0))
1272 return -1;
1274 if (commit) {
1275 arg1 = "commit";
1276 arg2 = commit;
1277 } else {
1278 arg1 = "message";
1280 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1281 arg1, arg2, NULL))
1282 ret = error(_("'prepare-commit-msg' hook failed"));
1284 return ret;
1287 static const char implicit_ident_advice_noconfig[] =
1288 N_("Your name and email address were configured automatically based\n"
1289 "on your username and hostname. Please check that they are accurate.\n"
1290 "You can suppress this message by setting them explicitly. Run the\n"
1291 "following command and follow the instructions in your editor to edit\n"
1292 "your configuration file:\n"
1293 "\n"
1294 " git config --global --edit\n"
1295 "\n"
1296 "After doing this, you may fix the identity used for this commit with:\n"
1297 "\n"
1298 " git commit --amend --reset-author\n");
1300 static const char implicit_ident_advice_config[] =
1301 N_("Your name and email address were configured automatically based\n"
1302 "on your username and hostname. Please check that they are accurate.\n"
1303 "You can suppress this message by setting them explicitly:\n"
1304 "\n"
1305 " git config --global user.name \"Your Name\"\n"
1306 " git config --global user.email you@example.com\n"
1307 "\n"
1308 "After doing this, you may fix the identity used for this commit with:\n"
1309 "\n"
1310 " git commit --amend --reset-author\n");
1312 static const char *implicit_ident_advice(void)
1314 char *user_config = interpolate_path("~/.gitconfig", 0);
1315 char *xdg_config = xdg_config_home("config");
1316 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1318 free(user_config);
1319 free(xdg_config);
1321 if (config_exists)
1322 return _(implicit_ident_advice_config);
1323 else
1324 return _(implicit_ident_advice_noconfig);
1328 void print_commit_summary(struct repository *r,
1329 const char *prefix,
1330 const struct object_id *oid,
1331 unsigned int flags)
1333 struct rev_info rev;
1334 struct commit *commit;
1335 struct strbuf format = STRBUF_INIT;
1336 const char *head;
1337 struct pretty_print_context pctx = {0};
1338 struct strbuf author_ident = STRBUF_INIT;
1339 struct strbuf committer_ident = STRBUF_INIT;
1340 struct ref_store *refs;
1342 commit = lookup_commit(r, oid);
1343 if (!commit)
1344 die(_("couldn't look up newly created commit"));
1345 if (repo_parse_commit(r, commit))
1346 die(_("could not parse newly created commit"));
1348 strbuf_addstr(&format, "format:%h] %s");
1350 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1351 &pctx);
1352 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1353 &pctx);
1354 if (strbuf_cmp(&author_ident, &committer_ident)) {
1355 strbuf_addstr(&format, "\n Author: ");
1356 strbuf_addbuf_percentquote(&format, &author_ident);
1358 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1359 struct strbuf date = STRBUF_INIT;
1361 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1362 strbuf_addstr(&format, "\n Date: ");
1363 strbuf_addbuf_percentquote(&format, &date);
1364 strbuf_release(&date);
1366 if (!committer_ident_sufficiently_given()) {
1367 strbuf_addstr(&format, "\n Committer: ");
1368 strbuf_addbuf_percentquote(&format, &committer_ident);
1369 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1370 strbuf_addch(&format, '\n');
1371 strbuf_addstr(&format, implicit_ident_advice());
1374 strbuf_release(&author_ident);
1375 strbuf_release(&committer_ident);
1377 repo_init_revisions(r, &rev, prefix);
1378 setup_revisions(0, NULL, &rev, NULL);
1380 rev.diff = 1;
1381 rev.diffopt.output_format =
1382 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1384 rev.verbose_header = 1;
1385 rev.show_root_diff = 1;
1386 get_commit_format(format.buf, &rev);
1387 rev.always_show_header = 0;
1388 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1389 diff_setup_done(&rev.diffopt);
1391 refs = get_main_ref_store(r);
1392 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1393 if (!head)
1394 die(_("unable to resolve HEAD after creating commit"));
1395 if (!strcmp(head, "HEAD"))
1396 head = _("detached HEAD");
1397 else
1398 skip_prefix(head, "refs/heads/", &head);
1399 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1400 _(" (root-commit)") : "");
1402 if (!log_tree_commit(&rev, commit)) {
1403 rev.always_show_header = 1;
1404 rev.use_terminator = 1;
1405 log_tree_commit(&rev, commit);
1408 release_revisions(&rev);
1409 strbuf_release(&format);
1412 static int parse_head(struct repository *r, struct commit **head)
1414 struct commit *current_head;
1415 struct object_id oid;
1417 if (repo_get_oid(r, "HEAD", &oid)) {
1418 current_head = NULL;
1419 } else {
1420 current_head = lookup_commit_reference(r, &oid);
1421 if (!current_head)
1422 return error(_("could not parse HEAD"));
1423 if (!oideq(&oid, &current_head->object.oid)) {
1424 warning(_("HEAD %s is not a commit!"),
1425 oid_to_hex(&oid));
1427 if (repo_parse_commit(r, current_head))
1428 return error(_("could not parse HEAD commit"));
1430 *head = current_head;
1432 return 0;
1436 * Try to commit without forking 'git commit'. In some cases we need
1437 * to run 'git commit' to display an error message
1439 * Returns:
1440 * -1 - error unable to commit
1441 * 0 - success
1442 * 1 - run 'git commit'
1444 static int try_to_commit(struct repository *r,
1445 struct strbuf *msg, const char *author,
1446 struct replay_opts *opts, unsigned int flags,
1447 struct object_id *oid)
1449 struct object_id tree;
1450 struct commit *current_head = NULL;
1451 struct commit_list *parents = NULL;
1452 struct commit_extra_header *extra = NULL;
1453 struct strbuf err = STRBUF_INIT;
1454 struct strbuf commit_msg = STRBUF_INIT;
1455 char *amend_author = NULL;
1456 const char *committer = NULL;
1457 const char *hook_commit = NULL;
1458 enum commit_msg_cleanup_mode cleanup;
1459 int res = 0;
1461 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1462 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1464 if (parse_head(r, &current_head))
1465 return -1;
1467 if (flags & AMEND_MSG) {
1468 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1469 const char *out_enc = get_commit_output_encoding();
1470 const char *message = repo_logmsg_reencode(r, current_head,
1471 NULL, out_enc);
1473 if (!msg) {
1474 const char *orig_message = NULL;
1476 find_commit_subject(message, &orig_message);
1477 msg = &commit_msg;
1478 strbuf_addstr(msg, orig_message);
1479 hook_commit = "HEAD";
1481 author = amend_author = get_author(message);
1482 repo_unuse_commit_buffer(r, current_head,
1483 message);
1484 if (!author) {
1485 res = error(_("unable to parse commit author"));
1486 goto out;
1488 parents = copy_commit_list(current_head->parents);
1489 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1490 } else if (current_head &&
1491 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1492 commit_list_insert(current_head, &parents);
1495 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1496 res = error(_("git write-tree failed to write a tree"));
1497 goto out;
1500 if (!(flags & ALLOW_EMPTY)) {
1501 struct commit *first_parent = current_head;
1503 if (flags & AMEND_MSG) {
1504 if (current_head->parents) {
1505 first_parent = current_head->parents->item;
1506 if (repo_parse_commit(r, first_parent)) {
1507 res = error(_("could not parse HEAD commit"));
1508 goto out;
1510 } else {
1511 first_parent = NULL;
1514 if (oideq(first_parent
1515 ? get_commit_tree_oid(first_parent)
1516 : the_hash_algo->empty_tree,
1517 &tree)) {
1518 res = 1; /* run 'git commit' to display error message */
1519 goto out;
1523 if (hook_exists("prepare-commit-msg")) {
1524 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1525 if (res)
1526 goto out;
1527 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1528 2048) < 0) {
1529 res = error_errno(_("unable to read commit message "
1530 "from '%s'"),
1531 git_path_commit_editmsg());
1532 goto out;
1534 msg = &commit_msg;
1537 if (flags & CLEANUP_MSG)
1538 cleanup = COMMIT_MSG_CLEANUP_ALL;
1539 else if (flags & VERBATIM_MSG)
1540 cleanup = COMMIT_MSG_CLEANUP_NONE;
1541 else if ((opts->signoff || opts->record_origin) &&
1542 !opts->explicit_cleanup)
1543 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1544 else
1545 cleanup = opts->default_msg_cleanup;
1547 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1548 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1549 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1550 res = 1; /* run 'git commit' to display error message */
1551 goto out;
1554 if (opts->committer_date_is_author_date) {
1555 struct ident_split id;
1556 struct strbuf date = STRBUF_INIT;
1558 if (!opts->ignore_date) {
1559 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1560 res = error(_("invalid author identity '%s'"),
1561 author);
1562 goto out;
1564 if (!id.date_begin) {
1565 res = error(_(
1566 "corrupt author: missing date information"));
1567 goto out;
1569 strbuf_addf(&date, "@%.*s %.*s",
1570 (int)(id.date_end - id.date_begin),
1571 id.date_begin,
1572 (int)(id.tz_end - id.tz_begin),
1573 id.tz_begin);
1574 } else {
1575 reset_ident_date();
1577 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1578 getenv("GIT_COMMITTER_EMAIL"),
1579 WANT_COMMITTER_IDENT,
1580 opts->ignore_date ? NULL : date.buf,
1581 IDENT_STRICT);
1582 strbuf_release(&date);
1583 } else {
1584 reset_ident_date();
1587 if (opts->ignore_date) {
1588 struct ident_split id;
1589 char *name, *email;
1591 if (split_ident_line(&id, author, strlen(author)) < 0) {
1592 error(_("invalid author identity '%s'"), author);
1593 goto out;
1595 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1596 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1597 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1598 IDENT_STRICT);
1599 free(name);
1600 free(email);
1603 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1604 author, committer, opts->gpg_sign, extra)) {
1605 res = error(_("failed to write commit object"));
1606 goto out;
1609 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1610 msg, &err)) {
1611 res = error("%s", err.buf);
1612 goto out;
1615 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1616 if (flags & AMEND_MSG)
1617 commit_post_rewrite(r, current_head, oid);
1619 out:
1620 free_commit_extra_headers(extra);
1621 strbuf_release(&err);
1622 strbuf_release(&commit_msg);
1623 free(amend_author);
1625 return res;
1628 static int write_rebase_head(struct object_id *oid)
1630 if (update_ref("rebase", "REBASE_HEAD", oid,
1631 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1632 return error(_("could not update %s"), "REBASE_HEAD");
1634 return 0;
1637 static int do_commit(struct repository *r,
1638 const char *msg_file, const char *author,
1639 struct replay_opts *opts, unsigned int flags,
1640 struct object_id *oid)
1642 int res = 1;
1644 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1645 struct object_id oid;
1646 struct strbuf sb = STRBUF_INIT;
1648 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1649 return error_errno(_("unable to read commit message "
1650 "from '%s'"),
1651 msg_file);
1653 res = try_to_commit(r, msg_file ? &sb : NULL,
1654 author, opts, flags, &oid);
1655 strbuf_release(&sb);
1656 if (!res) {
1657 refs_delete_ref(get_main_ref_store(r), "",
1658 "CHERRY_PICK_HEAD", NULL, 0);
1659 unlink(git_path_merge_msg(r));
1660 if (!is_rebase_i(opts))
1661 print_commit_summary(r, NULL, &oid,
1662 SUMMARY_SHOW_AUTHOR_DATE);
1663 return res;
1666 if (res == 1) {
1667 if (is_rebase_i(opts) && oid)
1668 if (write_rebase_head(oid))
1669 return -1;
1670 return run_git_commit(msg_file, opts, flags);
1673 return res;
1676 static int is_original_commit_empty(struct commit *commit)
1678 const struct object_id *ptree_oid;
1680 if (repo_parse_commit(the_repository, commit))
1681 return error(_("could not parse commit %s"),
1682 oid_to_hex(&commit->object.oid));
1683 if (commit->parents) {
1684 struct commit *parent = commit->parents->item;
1685 if (repo_parse_commit(the_repository, parent))
1686 return error(_("could not parse parent commit %s"),
1687 oid_to_hex(&parent->object.oid));
1688 ptree_oid = get_commit_tree_oid(parent);
1689 } else {
1690 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1693 return oideq(ptree_oid, get_commit_tree_oid(commit));
1697 * Should empty commits be allowed? Return status:
1698 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1699 * 0: Halt on empty commit
1700 * 1: Allow empty commit
1701 * 2: Drop empty commit
1703 static int allow_empty(struct repository *r,
1704 struct replay_opts *opts,
1705 struct commit *commit)
1707 int index_unchanged, originally_empty;
1710 * Four cases:
1712 * (1) we do not allow empty at all and error out.
1714 * (2) we allow ones that were initially empty, and
1715 * just drop the ones that become empty
1717 * (3) we allow ones that were initially empty, but
1718 * halt for the ones that become empty;
1720 * (4) we allow both.
1722 if (!opts->allow_empty)
1723 return 0; /* let "git commit" barf as necessary */
1725 index_unchanged = is_index_unchanged(r);
1726 if (index_unchanged < 0)
1727 return index_unchanged;
1728 if (!index_unchanged)
1729 return 0; /* we do not have to say --allow-empty */
1731 if (opts->keep_redundant_commits)
1732 return 1;
1734 originally_empty = is_original_commit_empty(commit);
1735 if (originally_empty < 0)
1736 return originally_empty;
1737 if (originally_empty)
1738 return 1;
1739 else if (opts->drop_redundant_commits)
1740 return 2;
1741 else
1742 return 0;
1745 static struct {
1746 char c;
1747 const char *str;
1748 } todo_command_info[] = {
1749 [TODO_PICK] = { 'p', "pick" },
1750 [TODO_REVERT] = { 0, "revert" },
1751 [TODO_EDIT] = { 'e', "edit" },
1752 [TODO_REWORD] = { 'r', "reword" },
1753 [TODO_FIXUP] = { 'f', "fixup" },
1754 [TODO_SQUASH] = { 's', "squash" },
1755 [TODO_EXEC] = { 'x', "exec" },
1756 [TODO_BREAK] = { 'b', "break" },
1757 [TODO_LABEL] = { 'l', "label" },
1758 [TODO_RESET] = { 't', "reset" },
1759 [TODO_MERGE] = { 'm', "merge" },
1760 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1761 [TODO_NOOP] = { 0, "noop" },
1762 [TODO_DROP] = { 'd', "drop" },
1763 [TODO_COMMENT] = { 0, NULL },
1766 static const char *command_to_string(const enum todo_command command)
1768 if (command < TODO_COMMENT)
1769 return todo_command_info[command].str;
1770 die(_("unknown command: %d"), command);
1773 static char command_to_char(const enum todo_command command)
1775 if (command < TODO_COMMENT)
1776 return todo_command_info[command].c;
1777 return comment_line_char;
1780 static int is_noop(const enum todo_command command)
1782 return TODO_NOOP <= command;
1785 static int is_fixup(enum todo_command command)
1787 return command == TODO_FIXUP || command == TODO_SQUASH;
1790 /* Does this command create a (non-merge) commit? */
1791 static int is_pick_or_similar(enum todo_command command)
1793 switch (command) {
1794 case TODO_PICK:
1795 case TODO_REVERT:
1796 case TODO_EDIT:
1797 case TODO_REWORD:
1798 case TODO_FIXUP:
1799 case TODO_SQUASH:
1800 return 1;
1801 default:
1802 return 0;
1806 enum todo_item_flags {
1807 TODO_EDIT_MERGE_MSG = (1 << 0),
1808 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1809 TODO_EDIT_FIXUP_MSG = (1 << 2),
1812 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1813 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1814 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1815 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1816 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1818 static int is_fixup_flag(enum todo_command command, unsigned flag)
1820 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1821 (flag & TODO_EDIT_FIXUP_MSG));
1825 * Wrapper around strbuf_add_commented_lines() which avoids double
1826 * commenting commit subjects.
1828 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1830 const char *s = str;
1831 while (len > 0 && s[0] == comment_line_char) {
1832 size_t count;
1833 const char *n = memchr(s, '\n', len);
1834 if (!n)
1835 count = len;
1836 else
1837 count = n - s + 1;
1838 strbuf_add(buf, s, count);
1839 s += count;
1840 len -= count;
1842 strbuf_add_commented_lines(buf, s, len);
1845 /* Does the current fixup chain contain a squash command? */
1846 static int seen_squash(struct replay_opts *opts)
1848 return starts_with(opts->current_fixups.buf, "squash") ||
1849 strstr(opts->current_fixups.buf, "\nsquash");
1852 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1854 strbuf_setlen(buf1, 2);
1855 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1856 strbuf_addch(buf1, '\n');
1857 strbuf_setlen(buf2, 2);
1858 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1859 strbuf_addch(buf2, '\n');
1863 * Comment out any un-commented commit messages, updating the message comments
1864 * to say they will be skipped but do not comment out the empty lines that
1865 * surround commit messages and their comments.
1867 static void update_squash_message_for_fixup(struct strbuf *msg)
1869 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1870 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1871 const char *s, *start;
1872 char *orig_msg;
1873 size_t orig_msg_len;
1874 int i = 1;
1876 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1877 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1878 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1879 while (s) {
1880 const char *next;
1881 size_t off;
1882 if (skip_prefix(s, buf1.buf, &next)) {
1884 * Copy the last message, preserving the blank line
1885 * preceding the current line
1887 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1888 copy_lines(msg, start, s - start - off);
1889 if (off)
1890 strbuf_addch(msg, '\n');
1892 * The next message needs to be commented out but the
1893 * message header is already commented out so just copy
1894 * it and the blank line that follows it.
1896 strbuf_addbuf(msg, &buf2);
1897 if (*next == '\n')
1898 strbuf_addch(msg, *next++);
1899 start = s = next;
1900 copy_lines = add_commented_lines;
1901 update_comment_bufs(&buf1, &buf2, ++i);
1902 } else if (skip_prefix(s, buf2.buf, &next)) {
1903 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1904 copy_lines(msg, start, s - start - off);
1905 start = s - off;
1906 s = next;
1907 copy_lines = strbuf_add;
1908 update_comment_bufs(&buf1, &buf2, ++i);
1909 } else {
1910 s = strchr(s, '\n');
1911 if (s)
1912 s++;
1915 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1916 free(orig_msg);
1917 strbuf_release(&buf1);
1918 strbuf_release(&buf2);
1921 static int append_squash_message(struct strbuf *buf, const char *body,
1922 enum todo_command command, struct replay_opts *opts,
1923 unsigned flag)
1925 const char *fixup_msg;
1926 size_t commented_len = 0, fixup_off;
1928 * amend is non-interactive and not normally used with fixup!
1929 * or squash! commits, so only comment out those subjects when
1930 * squashing commit messages.
1932 if (starts_with(body, "amend!") ||
1933 ((command == TODO_SQUASH || seen_squash(opts)) &&
1934 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1935 commented_len = commit_subject_length(body);
1937 strbuf_addf(buf, "\n%c ", comment_line_char);
1938 strbuf_addf(buf, _(nth_commit_msg_fmt),
1939 ++opts->current_fixup_count + 1);
1940 strbuf_addstr(buf, "\n\n");
1941 strbuf_add_commented_lines(buf, body, commented_len);
1942 /* buf->buf may be reallocated so store an offset into the buffer */
1943 fixup_off = buf->len;
1944 strbuf_addstr(buf, body + commented_len);
1946 /* fixup -C after squash behaves like squash */
1947 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1949 * We're replacing the commit message so we need to
1950 * append the Signed-off-by: trailer if the user
1951 * requested '--signoff'.
1953 if (opts->signoff)
1954 append_signoff(buf, 0, 0);
1956 if ((command == TODO_FIXUP) &&
1957 (flag & TODO_REPLACE_FIXUP_MSG) &&
1958 (file_exists(rebase_path_fixup_msg()) ||
1959 !file_exists(rebase_path_squash_msg()))) {
1960 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1961 if (write_message(fixup_msg, strlen(fixup_msg),
1962 rebase_path_fixup_msg(), 0) < 0)
1963 return error(_("cannot write '%s'"),
1964 rebase_path_fixup_msg());
1965 } else {
1966 unlink(rebase_path_fixup_msg());
1968 } else {
1969 unlink(rebase_path_fixup_msg());
1972 return 0;
1975 static int update_squash_messages(struct repository *r,
1976 enum todo_command command,
1977 struct commit *commit,
1978 struct replay_opts *opts,
1979 unsigned flag)
1981 struct strbuf buf = STRBUF_INIT;
1982 int res = 0;
1983 const char *message, *body;
1984 const char *encoding = get_commit_output_encoding();
1986 if (opts->current_fixup_count > 0) {
1987 struct strbuf header = STRBUF_INIT;
1988 char *eol;
1990 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1991 return error(_("could not read '%s'"),
1992 rebase_path_squash_msg());
1994 eol = buf.buf[0] != comment_line_char ?
1995 buf.buf : strchrnul(buf.buf, '\n');
1997 strbuf_addf(&header, "%c ", comment_line_char);
1998 strbuf_addf(&header, _(combined_commit_msg_fmt),
1999 opts->current_fixup_count + 2);
2000 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2001 strbuf_release(&header);
2002 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2003 update_squash_message_for_fixup(&buf);
2004 } else {
2005 struct object_id head;
2006 struct commit *head_commit;
2007 const char *head_message, *body;
2009 if (repo_get_oid(r, "HEAD", &head))
2010 return error(_("need a HEAD to fixup"));
2011 if (!(head_commit = lookup_commit_reference(r, &head)))
2012 return error(_("could not read HEAD"));
2013 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2014 encoding)))
2015 return error(_("could not read HEAD's commit message"));
2017 find_commit_subject(head_message, &body);
2018 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2019 rebase_path_fixup_msg(), 0) < 0) {
2020 repo_unuse_commit_buffer(r, head_commit, head_message);
2021 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2023 strbuf_addf(&buf, "%c ", comment_line_char);
2024 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2025 strbuf_addf(&buf, "\n%c ", comment_line_char);
2026 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2027 _(skip_first_commit_msg_str) :
2028 _(first_commit_msg_str));
2029 strbuf_addstr(&buf, "\n\n");
2030 if (is_fixup_flag(command, flag))
2031 strbuf_add_commented_lines(&buf, body, strlen(body));
2032 else
2033 strbuf_addstr(&buf, body);
2035 repo_unuse_commit_buffer(r, head_commit, head_message);
2038 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2039 return error(_("could not read commit message of %s"),
2040 oid_to_hex(&commit->object.oid));
2041 find_commit_subject(message, &body);
2043 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2044 res = append_squash_message(&buf, body, command, opts, flag);
2045 } else if (command == TODO_FIXUP) {
2046 strbuf_addf(&buf, "\n%c ", comment_line_char);
2047 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2048 ++opts->current_fixup_count + 1);
2049 strbuf_addstr(&buf, "\n\n");
2050 strbuf_add_commented_lines(&buf, body, strlen(body));
2051 } else
2052 return error(_("unknown command: %d"), command);
2053 repo_unuse_commit_buffer(r, commit, message);
2055 if (!res)
2056 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2058 strbuf_release(&buf);
2060 if (!res) {
2061 strbuf_addf(&opts->current_fixups, "%s%s %s",
2062 opts->current_fixups.len ? "\n" : "",
2063 command_to_string(command),
2064 oid_to_hex(&commit->object.oid));
2065 res = write_message(opts->current_fixups.buf,
2066 opts->current_fixups.len,
2067 rebase_path_current_fixups(), 0);
2070 return res;
2073 static void flush_rewritten_pending(void)
2075 struct strbuf buf = STRBUF_INIT;
2076 struct object_id newoid;
2077 FILE *out;
2079 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2080 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2081 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2082 char *bol = buf.buf, *eol;
2084 while (*bol) {
2085 eol = strchrnul(bol, '\n');
2086 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2087 bol, oid_to_hex(&newoid));
2088 if (!*eol)
2089 break;
2090 bol = eol + 1;
2092 fclose(out);
2093 unlink(rebase_path_rewritten_pending());
2095 strbuf_release(&buf);
2098 static void record_in_rewritten(struct object_id *oid,
2099 enum todo_command next_command)
2101 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2103 if (!out)
2104 return;
2106 fprintf(out, "%s\n", oid_to_hex(oid));
2107 fclose(out);
2109 if (!is_fixup(next_command))
2110 flush_rewritten_pending();
2113 static int should_edit(struct replay_opts *opts) {
2114 if (opts->edit < 0)
2116 * Note that we only handle the case of non-conflicted
2117 * commits; continue_single_pick() handles the conflicted
2118 * commits itself instead of calling this function.
2120 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2121 return opts->edit;
2124 static void refer_to_commit(struct replay_opts *opts,
2125 struct strbuf *msgbuf, struct commit *commit)
2127 if (opts->commit_use_reference) {
2128 struct pretty_print_context ctx = {
2129 .abbrev = DEFAULT_ABBREV,
2130 .date_mode.type = DATE_SHORT,
2132 repo_format_commit_message(the_repository, commit,
2133 "%h (%s, %ad)", msgbuf, &ctx);
2134 } else {
2135 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2139 static int do_pick_commit(struct repository *r,
2140 struct todo_item *item,
2141 struct replay_opts *opts,
2142 int final_fixup, int *check_todo)
2144 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2145 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2146 struct object_id head;
2147 struct commit *base, *next, *parent;
2148 const char *base_label, *next_label;
2149 char *author = NULL;
2150 struct commit_message msg = { NULL, NULL, NULL, NULL };
2151 struct strbuf msgbuf = STRBUF_INIT;
2152 int res, unborn = 0, reword = 0, allow, drop_commit;
2153 enum todo_command command = item->command;
2154 struct commit *commit = item->commit;
2156 if (opts->no_commit) {
2158 * We do not intend to commit immediately. We just want to
2159 * merge the differences in, so let's compute the tree
2160 * that represents the "current" state for the merge machinery
2161 * to work on.
2163 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2164 return error(_("your index file is unmerged."));
2165 } else {
2166 unborn = repo_get_oid(r, "HEAD", &head);
2167 /* Do we want to generate a root commit? */
2168 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2169 oideq(&head, &opts->squash_onto)) {
2170 if (is_fixup(command))
2171 return error(_("cannot fixup root commit"));
2172 flags |= CREATE_ROOT_COMMIT;
2173 unborn = 1;
2174 } else if (unborn)
2175 oidcpy(&head, the_hash_algo->empty_tree);
2176 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2177 NULL, 0))
2178 return error_dirty_index(r, opts);
2180 discard_index(r->index);
2182 if (!commit->parents)
2183 parent = NULL;
2184 else if (commit->parents->next) {
2185 /* Reverting or cherry-picking a merge commit */
2186 int cnt;
2187 struct commit_list *p;
2189 if (!opts->mainline)
2190 return error(_("commit %s is a merge but no -m option was given."),
2191 oid_to_hex(&commit->object.oid));
2193 for (cnt = 1, p = commit->parents;
2194 cnt != opts->mainline && p;
2195 cnt++)
2196 p = p->next;
2197 if (cnt != opts->mainline || !p)
2198 return error(_("commit %s does not have parent %d"),
2199 oid_to_hex(&commit->object.oid), opts->mainline);
2200 parent = p->item;
2201 } else if (1 < opts->mainline)
2203 * Non-first parent explicitly specified as mainline for
2204 * non-merge commit
2206 return error(_("commit %s does not have parent %d"),
2207 oid_to_hex(&commit->object.oid), opts->mainline);
2208 else
2209 parent = commit->parents->item;
2211 if (get_message(commit, &msg) != 0)
2212 return error(_("cannot get commit message for %s"),
2213 oid_to_hex(&commit->object.oid));
2215 if (opts->allow_ff && !is_fixup(command) &&
2216 ((parent && oideq(&parent->object.oid, &head)) ||
2217 (!parent && unborn))) {
2218 if (is_rebase_i(opts))
2219 write_author_script(msg.message);
2220 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2221 opts);
2222 if (res || command != TODO_REWORD)
2223 goto leave;
2224 reword = 1;
2225 msg_file = NULL;
2226 goto fast_forward_edit;
2228 if (parent && repo_parse_commit(r, parent) < 0)
2229 /* TRANSLATORS: The first %s will be a "todo" command like
2230 "revert" or "pick", the second %s a SHA1. */
2231 return error(_("%s: cannot parse parent commit %s"),
2232 command_to_string(command),
2233 oid_to_hex(&parent->object.oid));
2236 * "commit" is an existing commit. We would want to apply
2237 * the difference it introduces since its first parent "prev"
2238 * on top of the current HEAD if we are cherry-pick. Or the
2239 * reverse of it if we are revert.
2242 if (command == TODO_REVERT) {
2243 base = commit;
2244 base_label = msg.label;
2245 next = parent;
2246 next_label = msg.parent_label;
2247 if (opts->commit_use_reference) {
2248 strbuf_addstr(&msgbuf,
2249 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2250 } else {
2251 strbuf_addstr(&msgbuf, "Revert \"");
2252 strbuf_addstr(&msgbuf, msg.subject);
2253 strbuf_addstr(&msgbuf, "\"");
2255 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2256 refer_to_commit(opts, &msgbuf, commit);
2258 if (commit->parents && commit->parents->next) {
2259 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2260 refer_to_commit(opts, &msgbuf, parent);
2262 strbuf_addstr(&msgbuf, ".\n");
2263 } else {
2264 const char *p;
2266 base = parent;
2267 base_label = msg.parent_label;
2268 next = commit;
2269 next_label = msg.label;
2271 /* Append the commit log message to msgbuf. */
2272 if (find_commit_subject(msg.message, &p))
2273 strbuf_addstr(&msgbuf, p);
2275 if (opts->record_origin) {
2276 strbuf_complete_line(&msgbuf);
2277 if (!has_conforming_footer(&msgbuf, NULL, 0))
2278 strbuf_addch(&msgbuf, '\n');
2279 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2280 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2281 strbuf_addstr(&msgbuf, ")\n");
2283 if (!is_fixup(command))
2284 author = get_author(msg.message);
2287 if (command == TODO_REWORD)
2288 reword = 1;
2289 else if (is_fixup(command)) {
2290 if (update_squash_messages(r, command, commit,
2291 opts, item->flags)) {
2292 res = -1;
2293 goto leave;
2295 flags |= AMEND_MSG;
2296 if (!final_fixup)
2297 msg_file = rebase_path_squash_msg();
2298 else if (file_exists(rebase_path_fixup_msg())) {
2299 flags |= VERBATIM_MSG;
2300 msg_file = rebase_path_fixup_msg();
2301 } else {
2302 const char *dest = git_path_squash_msg(r);
2303 unlink(dest);
2304 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2305 res = error(_("could not rename '%s' to '%s'"),
2306 rebase_path_squash_msg(), dest);
2307 goto leave;
2309 unlink(git_path_merge_msg(r));
2310 msg_file = dest;
2311 flags |= EDIT_MSG;
2315 if (opts->signoff && !is_fixup(command))
2316 append_signoff(&msgbuf, 0, 0);
2318 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2319 res = -1;
2320 else if (!opts->strategy ||
2321 !strcmp(opts->strategy, "recursive") ||
2322 !strcmp(opts->strategy, "ort") ||
2323 command == TODO_REVERT) {
2324 res = do_recursive_merge(r, base, next, base_label, next_label,
2325 &head, &msgbuf, opts);
2326 if (res < 0)
2327 goto leave;
2329 res |= write_message(msgbuf.buf, msgbuf.len,
2330 git_path_merge_msg(r), 0);
2331 } else {
2332 struct commit_list *common = NULL;
2333 struct commit_list *remotes = NULL;
2335 res = write_message(msgbuf.buf, msgbuf.len,
2336 git_path_merge_msg(r), 0);
2338 commit_list_insert(base, &common);
2339 commit_list_insert(next, &remotes);
2340 res |= try_merge_command(r, opts->strategy,
2341 opts->xopts.nr, opts->xopts.v,
2342 common, oid_to_hex(&head), remotes);
2343 free_commit_list(common);
2344 free_commit_list(remotes);
2348 * If the merge was clean or if it failed due to conflict, we write
2349 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2350 * However, if the merge did not even start, then we don't want to
2351 * write it at all.
2353 if ((command == TODO_PICK || command == TODO_REWORD ||
2354 command == TODO_EDIT) && !opts->no_commit &&
2355 (res == 0 || res == 1) &&
2356 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2357 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2358 res = -1;
2359 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2360 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2361 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2362 res = -1;
2364 if (res) {
2365 error(command == TODO_REVERT
2366 ? _("could not revert %s... %s")
2367 : _("could not apply %s... %s"),
2368 short_commit_name(commit), msg.subject);
2369 print_advice(r, res == 1, opts);
2370 repo_rerere(r, opts->allow_rerere_auto);
2371 goto leave;
2374 drop_commit = 0;
2375 allow = allow_empty(r, opts, commit);
2376 if (allow < 0) {
2377 res = allow;
2378 goto leave;
2379 } else if (allow == 1) {
2380 flags |= ALLOW_EMPTY;
2381 } else if (allow == 2) {
2382 drop_commit = 1;
2383 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2384 NULL, 0);
2385 unlink(git_path_merge_msg(r));
2386 unlink(git_path_auto_merge(r));
2387 fprintf(stderr,
2388 _("dropping %s %s -- patch contents already upstream\n"),
2389 oid_to_hex(&commit->object.oid), msg.subject);
2390 } /* else allow == 0 and there's nothing special to do */
2391 if (!opts->no_commit && !drop_commit) {
2392 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2393 res = do_commit(r, msg_file, author, opts, flags,
2394 commit? &commit->object.oid : NULL);
2395 else
2396 res = error(_("unable to parse commit author"));
2397 *check_todo = !!(flags & EDIT_MSG);
2398 if (!res && reword) {
2399 fast_forward_edit:
2400 res = run_git_commit(NULL, opts, EDIT_MSG |
2401 VERIFY_MSG | AMEND_MSG |
2402 (flags & ALLOW_EMPTY));
2403 *check_todo = 1;
2408 if (!res && final_fixup) {
2409 unlink(rebase_path_fixup_msg());
2410 unlink(rebase_path_squash_msg());
2411 unlink(rebase_path_current_fixups());
2412 strbuf_reset(&opts->current_fixups);
2413 opts->current_fixup_count = 0;
2416 leave:
2417 free_message(commit, &msg);
2418 free(author);
2419 strbuf_release(&msgbuf);
2420 update_abort_safety_file();
2422 return res;
2425 static int prepare_revs(struct replay_opts *opts)
2428 * picking (but not reverting) ranges (but not individual revisions)
2429 * should be done in reverse
2431 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2432 opts->revs->reverse ^= 1;
2434 if (prepare_revision_walk(opts->revs))
2435 return error(_("revision walk setup failed"));
2437 return 0;
2440 static int read_and_refresh_cache(struct repository *r,
2441 struct replay_opts *opts)
2443 struct lock_file index_lock = LOCK_INIT;
2444 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2445 if (repo_read_index(r) < 0) {
2446 rollback_lock_file(&index_lock);
2447 return error(_("git %s: failed to read the index"),
2448 action_name(opts));
2450 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2452 if (index_fd >= 0) {
2453 if (write_locked_index(r->index, &index_lock,
2454 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2455 return error(_("git %s: failed to refresh the index"),
2456 action_name(opts));
2461 * If we are resolving merges in any way other than "ort", then
2462 * expand the sparse index.
2464 if (opts->strategy && strcmp(opts->strategy, "ort"))
2465 ensure_full_index(r->index);
2466 return 0;
2469 void todo_list_release(struct todo_list *todo_list)
2471 strbuf_release(&todo_list->buf);
2472 FREE_AND_NULL(todo_list->items);
2473 todo_list->nr = todo_list->alloc = 0;
2476 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2478 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2479 todo_list->total_nr++;
2480 return todo_list->items + todo_list->nr++;
2483 const char *todo_item_get_arg(struct todo_list *todo_list,
2484 struct todo_item *item)
2486 return todo_list->buf.buf + item->arg_offset;
2489 static int is_command(enum todo_command command, const char **bol)
2491 const char *str = todo_command_info[command].str;
2492 const char nick = todo_command_info[command].c;
2493 const char *p = *bol;
2495 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2496 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2497 (*bol = p);
2500 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2502 switch (command) {
2503 case TODO_LABEL:
2505 * '#' is not a valid label as the merge command uses it to
2506 * separate merge parents from the commit subject.
2508 if (!strcmp(arg, "#") ||
2509 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2510 return error(_("'%s' is not a valid label"), arg);
2511 break;
2513 case TODO_UPDATE_REF:
2514 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2515 return error(_("'%s' is not a valid refname"), arg);
2516 if (check_refname_format(arg, 0))
2517 return error(_("update-ref requires a fully qualified "
2518 "refname e.g. refs/heads/%s"), arg);
2519 break;
2521 default:
2522 BUG("unexpected todo_command");
2525 return 0;
2528 static int parse_insn_line(struct repository *r, struct todo_item *item,
2529 const char *buf, const char *bol, char *eol)
2531 struct object_id commit_oid;
2532 char *end_of_object_name;
2533 int i, saved, status, padding;
2535 item->flags = 0;
2537 /* left-trim */
2538 bol += strspn(bol, " \t");
2540 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2541 item->command = TODO_COMMENT;
2542 item->commit = NULL;
2543 item->arg_offset = bol - buf;
2544 item->arg_len = eol - bol;
2545 return 0;
2548 for (i = 0; i < TODO_COMMENT; i++)
2549 if (is_command(i, &bol)) {
2550 item->command = i;
2551 break;
2553 if (i >= TODO_COMMENT)
2554 return error(_("invalid command '%.*s'"),
2555 (int)strcspn(bol, " \t\r\n"), bol);
2557 /* Eat up extra spaces/ tabs before object name */
2558 padding = strspn(bol, " \t");
2559 bol += padding;
2561 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2562 if (bol != eol)
2563 return error(_("%s does not accept arguments: '%s'"),
2564 command_to_string(item->command), bol);
2565 item->commit = NULL;
2566 item->arg_offset = bol - buf;
2567 item->arg_len = eol - bol;
2568 return 0;
2571 if (!padding)
2572 return error(_("missing arguments for %s"),
2573 command_to_string(item->command));
2575 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2576 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2577 int ret = 0;
2579 item->commit = NULL;
2580 item->arg_offset = bol - buf;
2581 item->arg_len = (int)(eol - bol);
2582 if (item->command == TODO_LABEL ||
2583 item->command == TODO_UPDATE_REF) {
2584 saved = *eol;
2585 *eol = '\0';
2586 ret = check_label_or_ref_arg(item->command, bol);
2587 *eol = saved;
2589 return ret;
2592 if (item->command == TODO_FIXUP) {
2593 if (skip_prefix(bol, "-C", &bol)) {
2594 bol += strspn(bol, " \t");
2595 item->flags |= TODO_REPLACE_FIXUP_MSG;
2596 } else if (skip_prefix(bol, "-c", &bol)) {
2597 bol += strspn(bol, " \t");
2598 item->flags |= TODO_EDIT_FIXUP_MSG;
2602 if (item->command == TODO_MERGE) {
2603 if (skip_prefix(bol, "-C", &bol))
2604 bol += strspn(bol, " \t");
2605 else if (skip_prefix(bol, "-c", &bol)) {
2606 bol += strspn(bol, " \t");
2607 item->flags |= TODO_EDIT_MERGE_MSG;
2608 } else {
2609 item->flags |= TODO_EDIT_MERGE_MSG;
2610 item->commit = NULL;
2611 item->arg_offset = bol - buf;
2612 item->arg_len = (int)(eol - bol);
2613 return 0;
2617 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2618 saved = *end_of_object_name;
2619 *end_of_object_name = '\0';
2620 status = repo_get_oid(r, bol, &commit_oid);
2621 if (status < 0)
2622 error(_("could not parse '%s'"), bol); /* return later */
2623 *end_of_object_name = saved;
2625 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2626 item->arg_offset = bol - buf;
2627 item->arg_len = (int)(eol - bol);
2629 if (status < 0)
2630 return status;
2632 item->commit = lookup_commit_reference(r, &commit_oid);
2633 return item->commit ? 0 : -1;
2636 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2638 const char *todo_file, *bol;
2639 struct strbuf buf = STRBUF_INIT;
2640 int ret = 0;
2642 todo_file = git_path_todo_file();
2643 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2644 if (errno == ENOENT || errno == ENOTDIR)
2645 return -1;
2646 else
2647 return error_errno("unable to open '%s'", todo_file);
2649 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2650 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2651 *action = REPLAY_PICK;
2652 else if (is_command(TODO_REVERT, &bol) &&
2653 (*bol == ' ' || *bol == '\t'))
2654 *action = REPLAY_REVERT;
2655 else
2656 ret = -1;
2658 strbuf_release(&buf);
2660 return ret;
2663 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2664 struct todo_list *todo_list)
2666 struct todo_item *item;
2667 char *p = buf, *next_p;
2668 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2670 todo_list->current = todo_list->nr = 0;
2672 for (i = 1; *p; i++, p = next_p) {
2673 char *eol = strchrnul(p, '\n');
2675 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2677 if (p != eol && eol[-1] == '\r')
2678 eol--; /* strip Carriage Return */
2680 item = append_new_todo(todo_list);
2681 item->offset_in_buf = p - todo_list->buf.buf;
2682 if (parse_insn_line(r, item, buf, p, eol)) {
2683 res = error(_("invalid line %d: %.*s"),
2684 i, (int)(eol - p), p);
2685 item->command = TODO_COMMENT + 1;
2686 item->arg_offset = p - buf;
2687 item->arg_len = (int)(eol - p);
2688 item->commit = NULL;
2691 if (fixup_okay)
2692 ; /* do nothing */
2693 else if (is_fixup(item->command))
2694 return error(_("cannot '%s' without a previous commit"),
2695 command_to_string(item->command));
2696 else if (!is_noop(item->command))
2697 fixup_okay = 1;
2700 return res;
2703 static int count_commands(struct todo_list *todo_list)
2705 int count = 0, i;
2707 for (i = 0; i < todo_list->nr; i++)
2708 if (todo_list->items[i].command != TODO_COMMENT)
2709 count++;
2711 return count;
2714 static int get_item_line_offset(struct todo_list *todo_list, int index)
2716 return index < todo_list->nr ?
2717 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2720 static const char *get_item_line(struct todo_list *todo_list, int index)
2722 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2725 static int get_item_line_length(struct todo_list *todo_list, int index)
2727 return get_item_line_offset(todo_list, index + 1)
2728 - get_item_line_offset(todo_list, index);
2731 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2733 int fd;
2734 ssize_t len;
2736 fd = open(path, O_RDONLY);
2737 if (fd < 0)
2738 return error_errno(_("could not open '%s'"), path);
2739 len = strbuf_read(sb, fd, 0);
2740 close(fd);
2741 if (len < 0)
2742 return error(_("could not read '%s'."), path);
2743 return len;
2746 static int have_finished_the_last_pick(void)
2748 struct strbuf buf = STRBUF_INIT;
2749 const char *eol;
2750 const char *todo_path = git_path_todo_file();
2751 int ret = 0;
2753 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2754 if (errno == ENOENT) {
2755 return 0;
2756 } else {
2757 error_errno("unable to open '%s'", todo_path);
2758 return 0;
2761 /* If there is only one line then we are done */
2762 eol = strchr(buf.buf, '\n');
2763 if (!eol || !eol[1])
2764 ret = 1;
2766 strbuf_release(&buf);
2768 return ret;
2771 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2773 struct replay_opts opts = REPLAY_OPTS_INIT;
2774 int need_cleanup = 0;
2776 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2777 if (!refs_delete_ref(get_main_ref_store(r), "",
2778 "CHERRY_PICK_HEAD", NULL, 0) &&
2779 verbose)
2780 warning(_("cancelling a cherry picking in progress"));
2781 opts.action = REPLAY_PICK;
2782 need_cleanup = 1;
2785 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2786 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2787 NULL, 0) &&
2788 verbose)
2789 warning(_("cancelling a revert in progress"));
2790 opts.action = REPLAY_REVERT;
2791 need_cleanup = 1;
2794 unlink(git_path_auto_merge(r));
2796 if (!need_cleanup)
2797 return;
2799 if (!have_finished_the_last_pick())
2800 return;
2802 sequencer_remove_state(&opts);
2805 static void todo_list_write_total_nr(struct todo_list *todo_list)
2807 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2809 if (f) {
2810 fprintf(f, "%d\n", todo_list->total_nr);
2811 fclose(f);
2815 static int read_populate_todo(struct repository *r,
2816 struct todo_list *todo_list,
2817 struct replay_opts *opts)
2819 const char *todo_file = get_todo_path(opts);
2820 int res;
2822 strbuf_reset(&todo_list->buf);
2823 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2824 return -1;
2826 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2827 if (res) {
2828 if (is_rebase_i(opts))
2829 return error(_("please fix this using "
2830 "'git rebase --edit-todo'."));
2831 return error(_("unusable instruction sheet: '%s'"), todo_file);
2834 if (!todo_list->nr &&
2835 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2836 return error(_("no commits parsed."));
2838 if (!is_rebase_i(opts)) {
2839 enum todo_command valid =
2840 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2841 int i;
2843 for (i = 0; i < todo_list->nr; i++)
2844 if (valid == todo_list->items[i].command)
2845 continue;
2846 else if (valid == TODO_PICK)
2847 return error(_("cannot cherry-pick during a revert."));
2848 else
2849 return error(_("cannot revert during a cherry-pick."));
2852 if (is_rebase_i(opts)) {
2853 struct todo_list done = TODO_LIST_INIT;
2855 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2856 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2857 todo_list->done_nr = count_commands(&done);
2858 else
2859 todo_list->done_nr = 0;
2861 todo_list->total_nr = todo_list->done_nr
2862 + count_commands(todo_list);
2863 todo_list_release(&done);
2865 todo_list_write_total_nr(todo_list);
2868 return 0;
2871 static int git_config_string_dup(char **dest,
2872 const char *var, const char *value)
2874 if (!value)
2875 return config_error_nonbool(var);
2876 free(*dest);
2877 *dest = xstrdup(value);
2878 return 0;
2881 static int populate_opts_cb(const char *key, const char *value, void *data)
2883 struct replay_opts *opts = data;
2884 int error_flag = 1;
2886 if (!value)
2887 error_flag = 0;
2888 else if (!strcmp(key, "options.no-commit"))
2889 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2890 else if (!strcmp(key, "options.edit"))
2891 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2892 else if (!strcmp(key, "options.allow-empty"))
2893 opts->allow_empty =
2894 git_config_bool_or_int(key, value, &error_flag);
2895 else if (!strcmp(key, "options.allow-empty-message"))
2896 opts->allow_empty_message =
2897 git_config_bool_or_int(key, value, &error_flag);
2898 else if (!strcmp(key, "options.keep-redundant-commits"))
2899 opts->keep_redundant_commits =
2900 git_config_bool_or_int(key, value, &error_flag);
2901 else if (!strcmp(key, "options.signoff"))
2902 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2903 else if (!strcmp(key, "options.record-origin"))
2904 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2905 else if (!strcmp(key, "options.allow-ff"))
2906 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2907 else if (!strcmp(key, "options.mainline"))
2908 opts->mainline = git_config_int(key, value);
2909 else if (!strcmp(key, "options.strategy"))
2910 git_config_string_dup(&opts->strategy, key, value);
2911 else if (!strcmp(key, "options.gpg-sign"))
2912 git_config_string_dup(&opts->gpg_sign, key, value);
2913 else if (!strcmp(key, "options.strategy-option")) {
2914 strvec_push(&opts->xopts, value);
2915 } else if (!strcmp(key, "options.allow-rerere-auto"))
2916 opts->allow_rerere_auto =
2917 git_config_bool_or_int(key, value, &error_flag) ?
2918 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2919 else if (!strcmp(key, "options.default-msg-cleanup")) {
2920 opts->explicit_cleanup = 1;
2921 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2922 } else
2923 return error(_("invalid key: %s"), key);
2925 if (!error_flag)
2926 return error(_("invalid value for '%s': '%s'"), key, value);
2928 return 0;
2931 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2933 int i;
2934 int count;
2935 const char **argv;
2936 char *strategy_opts_string = raw_opts;
2938 if (*strategy_opts_string == ' ')
2939 strategy_opts_string++;
2941 count = split_cmdline(strategy_opts_string, &argv);
2942 if (count < 0)
2943 BUG("could not split '%s': %s", strategy_opts_string,
2944 split_cmdline_strerror(count));
2945 for (i = 0; i < count; i++) {
2946 const char *arg = argv[i];
2948 skip_prefix(arg, "--", &arg);
2949 strvec_push(&opts->xopts, arg);
2951 free(argv);
2954 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2956 strbuf_reset(buf);
2957 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2958 return;
2959 opts->strategy = strbuf_detach(buf, NULL);
2960 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2961 return;
2963 parse_strategy_opts(opts, buf->buf);
2966 static int read_populate_opts(struct replay_opts *opts)
2968 if (is_rebase_i(opts)) {
2969 struct strbuf buf = STRBUF_INIT;
2970 int ret = 0;
2972 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2973 READ_ONELINER_SKIP_IF_EMPTY)) {
2974 if (!starts_with(buf.buf, "-S"))
2975 strbuf_reset(&buf);
2976 else {
2977 free(opts->gpg_sign);
2978 opts->gpg_sign = xstrdup(buf.buf + 2);
2980 strbuf_reset(&buf);
2983 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2984 READ_ONELINER_SKIP_IF_EMPTY)) {
2985 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2986 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2987 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2988 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2989 strbuf_reset(&buf);
2992 if (file_exists(rebase_path_verbose()))
2993 opts->verbose = 1;
2995 if (file_exists(rebase_path_quiet()))
2996 opts->quiet = 1;
2998 if (file_exists(rebase_path_signoff())) {
2999 opts->allow_ff = 0;
3000 opts->signoff = 1;
3003 if (file_exists(rebase_path_cdate_is_adate())) {
3004 opts->allow_ff = 0;
3005 opts->committer_date_is_author_date = 1;
3008 if (file_exists(rebase_path_ignore_date())) {
3009 opts->allow_ff = 0;
3010 opts->ignore_date = 1;
3013 if (file_exists(rebase_path_reschedule_failed_exec()))
3014 opts->reschedule_failed_exec = 1;
3015 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3016 opts->reschedule_failed_exec = 0;
3018 if (file_exists(rebase_path_drop_redundant_commits()))
3019 opts->drop_redundant_commits = 1;
3021 if (file_exists(rebase_path_keep_redundant_commits()))
3022 opts->keep_redundant_commits = 1;
3024 read_strategy_opts(opts, &buf);
3025 strbuf_reset(&buf);
3027 if (read_oneliner(&opts->current_fixups,
3028 rebase_path_current_fixups(),
3029 READ_ONELINER_SKIP_IF_EMPTY)) {
3030 const char *p = opts->current_fixups.buf;
3031 opts->current_fixup_count = 1;
3032 while ((p = strchr(p, '\n'))) {
3033 opts->current_fixup_count++;
3034 p++;
3038 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3039 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3040 ret = error(_("unusable squash-onto"));
3041 goto done_rebase_i;
3043 opts->have_squash_onto = 1;
3046 done_rebase_i:
3047 strbuf_release(&buf);
3048 return ret;
3051 if (!file_exists(git_path_opts_file()))
3052 return 0;
3054 * The function git_parse_source(), called from git_config_from_file(),
3055 * may die() in case of a syntactically incorrect file. We do not care
3056 * about this case, though, because we wrote that file ourselves, so we
3057 * are pretty certain that it is syntactically correct.
3059 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3060 return error(_("malformed options sheet: '%s'"),
3061 git_path_opts_file());
3062 return 0;
3065 static void write_strategy_opts(struct replay_opts *opts)
3067 struct strbuf buf = STRBUF_INIT;
3070 * Quote strategy options so that they can be read correctly
3071 * by split_cmdline().
3073 quote_cmdline(&buf, opts->xopts.v);
3074 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3075 strbuf_release(&buf);
3078 int write_basic_state(struct replay_opts *opts, const char *head_name,
3079 struct commit *onto, const struct object_id *orig_head)
3081 if (head_name)
3082 write_file(rebase_path_head_name(), "%s\n", head_name);
3083 if (onto)
3084 write_file(rebase_path_onto(), "%s\n",
3085 oid_to_hex(&onto->object.oid));
3086 if (orig_head)
3087 write_file(rebase_path_orig_head(), "%s\n",
3088 oid_to_hex(orig_head));
3090 if (opts->quiet)
3091 write_file(rebase_path_quiet(), "%s", "");
3092 if (opts->verbose)
3093 write_file(rebase_path_verbose(), "%s", "");
3094 if (opts->strategy)
3095 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3096 if (opts->xopts.nr > 0)
3097 write_strategy_opts(opts);
3099 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3100 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3101 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3102 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3104 if (opts->gpg_sign)
3105 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3106 if (opts->signoff)
3107 write_file(rebase_path_signoff(), "--signoff\n");
3108 if (opts->drop_redundant_commits)
3109 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3110 if (opts->keep_redundant_commits)
3111 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3112 if (opts->committer_date_is_author_date)
3113 write_file(rebase_path_cdate_is_adate(), "%s", "");
3114 if (opts->ignore_date)
3115 write_file(rebase_path_ignore_date(), "%s", "");
3116 if (opts->reschedule_failed_exec)
3117 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3118 else
3119 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3121 return 0;
3124 static int walk_revs_populate_todo(struct todo_list *todo_list,
3125 struct replay_opts *opts)
3127 enum todo_command command = opts->action == REPLAY_PICK ?
3128 TODO_PICK : TODO_REVERT;
3129 const char *command_string = todo_command_info[command].str;
3130 const char *encoding;
3131 struct commit *commit;
3133 if (prepare_revs(opts))
3134 return -1;
3136 encoding = get_log_output_encoding();
3138 while ((commit = get_revision(opts->revs))) {
3139 struct todo_item *item = append_new_todo(todo_list);
3140 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3141 commit, NULL,
3142 encoding);
3143 const char *subject;
3144 int subject_len;
3146 item->command = command;
3147 item->commit = commit;
3148 item->arg_offset = 0;
3149 item->arg_len = 0;
3150 item->offset_in_buf = todo_list->buf.len;
3151 subject_len = find_commit_subject(commit_buffer, &subject);
3152 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3153 short_commit_name(commit), subject_len, subject);
3154 repo_unuse_commit_buffer(the_repository, commit,
3155 commit_buffer);
3158 if (!todo_list->nr)
3159 return error(_("empty commit set passed"));
3161 return 0;
3164 static int create_seq_dir(struct repository *r)
3166 enum replay_action action;
3167 const char *in_progress_error = NULL;
3168 const char *in_progress_advice = NULL;
3169 unsigned int advise_skip =
3170 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3171 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3173 if (!sequencer_get_last_command(r, &action)) {
3174 switch (action) {
3175 case REPLAY_REVERT:
3176 in_progress_error = _("revert is already in progress");
3177 in_progress_advice =
3178 _("try \"git revert (--continue | %s--abort | --quit)\"");
3179 break;
3180 case REPLAY_PICK:
3181 in_progress_error = _("cherry-pick is already in progress");
3182 in_progress_advice =
3183 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3184 break;
3185 default:
3186 BUG("unexpected action in create_seq_dir");
3189 if (in_progress_error) {
3190 error("%s", in_progress_error);
3191 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3192 advise(in_progress_advice,
3193 advise_skip ? "--skip | " : "");
3194 return -1;
3196 if (mkdir(git_path_seq_dir(), 0777) < 0)
3197 return error_errno(_("could not create sequencer directory '%s'"),
3198 git_path_seq_dir());
3200 return 0;
3203 static int save_head(const char *head)
3205 return write_message(head, strlen(head), git_path_head_file(), 1);
3208 static int rollback_is_safe(void)
3210 struct strbuf sb = STRBUF_INIT;
3211 struct object_id expected_head, actual_head;
3213 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3214 strbuf_trim(&sb);
3215 if (get_oid_hex(sb.buf, &expected_head)) {
3216 strbuf_release(&sb);
3217 die(_("could not parse %s"), git_path_abort_safety_file());
3219 strbuf_release(&sb);
3221 else if (errno == ENOENT)
3222 oidclr(&expected_head);
3223 else
3224 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3226 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3227 oidclr(&actual_head);
3229 return oideq(&actual_head, &expected_head);
3232 static int reset_merge(const struct object_id *oid)
3234 struct child_process cmd = CHILD_PROCESS_INIT;
3236 cmd.git_cmd = 1;
3237 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3239 if (!is_null_oid(oid))
3240 strvec_push(&cmd.args, oid_to_hex(oid));
3242 return run_command(&cmd);
3245 static int rollback_single_pick(struct repository *r)
3247 struct object_id head_oid;
3249 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3250 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3251 return error(_("no cherry-pick or revert in progress"));
3252 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3253 return error(_("cannot resolve HEAD"));
3254 if (is_null_oid(&head_oid))
3255 return error(_("cannot abort from a branch yet to be born"));
3256 return reset_merge(&head_oid);
3259 static int skip_single_pick(void)
3261 struct object_id head;
3263 if (read_ref_full("HEAD", 0, &head, NULL))
3264 return error(_("cannot resolve HEAD"));
3265 return reset_merge(&head);
3268 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3270 FILE *f;
3271 struct object_id oid;
3272 struct strbuf buf = STRBUF_INIT;
3273 const char *p;
3275 f = fopen(git_path_head_file(), "r");
3276 if (!f && errno == ENOENT) {
3278 * There is no multiple-cherry-pick in progress.
3279 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3280 * a single-cherry-pick in progress, abort that.
3282 return rollback_single_pick(r);
3284 if (!f)
3285 return error_errno(_("cannot open '%s'"), git_path_head_file());
3286 if (strbuf_getline_lf(&buf, f)) {
3287 error(_("cannot read '%s': %s"), git_path_head_file(),
3288 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3289 fclose(f);
3290 goto fail;
3292 fclose(f);
3293 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3294 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3295 git_path_head_file());
3296 goto fail;
3298 if (is_null_oid(&oid)) {
3299 error(_("cannot abort from a branch yet to be born"));
3300 goto fail;
3303 if (!rollback_is_safe()) {
3304 /* Do not error, just do not rollback */
3305 warning(_("You seem to have moved HEAD. "
3306 "Not rewinding, check your HEAD!"));
3307 } else
3308 if (reset_merge(&oid))
3309 goto fail;
3310 strbuf_release(&buf);
3311 return sequencer_remove_state(opts);
3312 fail:
3313 strbuf_release(&buf);
3314 return -1;
3317 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3319 enum replay_action action = -1;
3320 sequencer_get_last_command(r, &action);
3323 * Check whether the subcommand requested to skip the commit is actually
3324 * in progress and that it's safe to skip the commit.
3326 * opts->action tells us which subcommand requested to skip the commit.
3327 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3328 * action is in progress and we can skip the commit.
3330 * Otherwise we check that the last instruction was related to the
3331 * particular subcommand we're trying to execute and barf if that's not
3332 * the case.
3334 * Finally we check that the rollback is "safe", i.e., has the HEAD
3335 * moved? In this case, it doesn't make sense to "reset the merge" and
3336 * "skip the commit" as the user already handled this by committing. But
3337 * we'd not want to barf here, instead give advice on how to proceed. We
3338 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3339 * it gets removed when the user commits, so if it still exists we're
3340 * sure the user can't have committed before.
3342 switch (opts->action) {
3343 case REPLAY_REVERT:
3344 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3345 if (action != REPLAY_REVERT)
3346 return error(_("no revert in progress"));
3347 if (!rollback_is_safe())
3348 goto give_advice;
3350 break;
3351 case REPLAY_PICK:
3352 if (!refs_ref_exists(get_main_ref_store(r),
3353 "CHERRY_PICK_HEAD")) {
3354 if (action != REPLAY_PICK)
3355 return error(_("no cherry-pick in progress"));
3356 if (!rollback_is_safe())
3357 goto give_advice;
3359 break;
3360 default:
3361 BUG("unexpected action in sequencer_skip");
3364 if (skip_single_pick())
3365 return error(_("failed to skip the commit"));
3366 if (!is_directory(git_path_seq_dir()))
3367 return 0;
3369 return sequencer_continue(r, opts);
3371 give_advice:
3372 error(_("there is nothing to skip"));
3374 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3375 advise(_("have you committed already?\n"
3376 "try \"git %s --continue\""),
3377 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3379 return -1;
3382 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3384 struct lock_file todo_lock = LOCK_INIT;
3385 const char *todo_path = get_todo_path(opts);
3386 int next = todo_list->current, offset, fd;
3389 * rebase -i writes "git-rebase-todo" without the currently executing
3390 * command, appending it to "done" instead.
3392 if (is_rebase_i(opts))
3393 next++;
3395 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3396 if (fd < 0)
3397 return error_errno(_("could not lock '%s'"), todo_path);
3398 offset = get_item_line_offset(todo_list, next);
3399 if (write_in_full(fd, todo_list->buf.buf + offset,
3400 todo_list->buf.len - offset) < 0)
3401 return error_errno(_("could not write to '%s'"), todo_path);
3402 if (commit_lock_file(&todo_lock) < 0)
3403 return error(_("failed to finalize '%s'"), todo_path);
3405 if (is_rebase_i(opts) && next > 0) {
3406 const char *done = rebase_path_done();
3407 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3408 int ret = 0;
3410 if (fd < 0)
3411 return 0;
3412 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3413 get_item_line_length(todo_list, next - 1))
3414 < 0)
3415 ret = error_errno(_("could not write to '%s'"), done);
3416 if (close(fd) < 0)
3417 ret = error_errno(_("failed to finalize '%s'"), done);
3418 return ret;
3420 return 0;
3423 static int save_opts(struct replay_opts *opts)
3425 const char *opts_file = git_path_opts_file();
3426 int res = 0;
3428 if (opts->no_commit)
3429 res |= git_config_set_in_file_gently(opts_file,
3430 "options.no-commit", "true");
3431 if (opts->edit >= 0)
3432 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3433 opts->edit ? "true" : "false");
3434 if (opts->allow_empty)
3435 res |= git_config_set_in_file_gently(opts_file,
3436 "options.allow-empty", "true");
3437 if (opts->allow_empty_message)
3438 res |= git_config_set_in_file_gently(opts_file,
3439 "options.allow-empty-message", "true");
3440 if (opts->keep_redundant_commits)
3441 res |= git_config_set_in_file_gently(opts_file,
3442 "options.keep-redundant-commits", "true");
3443 if (opts->signoff)
3444 res |= git_config_set_in_file_gently(opts_file,
3445 "options.signoff", "true");
3446 if (opts->record_origin)
3447 res |= git_config_set_in_file_gently(opts_file,
3448 "options.record-origin", "true");
3449 if (opts->allow_ff)
3450 res |= git_config_set_in_file_gently(opts_file,
3451 "options.allow-ff", "true");
3452 if (opts->mainline) {
3453 struct strbuf buf = STRBUF_INIT;
3454 strbuf_addf(&buf, "%d", opts->mainline);
3455 res |= git_config_set_in_file_gently(opts_file,
3456 "options.mainline", buf.buf);
3457 strbuf_release(&buf);
3459 if (opts->strategy)
3460 res |= git_config_set_in_file_gently(opts_file,
3461 "options.strategy", opts->strategy);
3462 if (opts->gpg_sign)
3463 res |= git_config_set_in_file_gently(opts_file,
3464 "options.gpg-sign", opts->gpg_sign);
3465 for (size_t i = 0; i < opts->xopts.nr; i++)
3466 res |= git_config_set_multivar_in_file_gently(opts_file,
3467 "options.strategy-option",
3468 opts->xopts.v[i], "^$", 0);
3469 if (opts->allow_rerere_auto)
3470 res |= git_config_set_in_file_gently(opts_file,
3471 "options.allow-rerere-auto",
3472 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3473 "true" : "false");
3475 if (opts->explicit_cleanup)
3476 res |= git_config_set_in_file_gently(opts_file,
3477 "options.default-msg-cleanup",
3478 describe_cleanup_mode(opts->default_msg_cleanup));
3479 return res;
3482 static int make_patch(struct repository *r,
3483 struct commit *commit,
3484 struct replay_opts *opts)
3486 struct strbuf buf = STRBUF_INIT;
3487 struct rev_info log_tree_opt;
3488 const char *subject;
3489 char hex[GIT_MAX_HEXSZ + 1];
3490 int res = 0;
3492 oid_to_hex_r(hex, &commit->object.oid);
3493 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3494 return -1;
3495 res |= write_rebase_head(&commit->object.oid);
3497 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3498 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3499 repo_init_revisions(r, &log_tree_opt, NULL);
3500 log_tree_opt.abbrev = 0;
3501 log_tree_opt.diff = 1;
3502 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3503 log_tree_opt.disable_stdin = 1;
3504 log_tree_opt.no_commit_id = 1;
3505 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3506 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3507 if (!log_tree_opt.diffopt.file)
3508 res |= error_errno(_("could not open '%s'"), buf.buf);
3509 else {
3510 res |= log_tree_commit(&log_tree_opt, commit);
3511 fclose(log_tree_opt.diffopt.file);
3513 strbuf_reset(&buf);
3515 strbuf_addf(&buf, "%s/message", get_dir(opts));
3516 if (!file_exists(buf.buf)) {
3517 const char *encoding = get_commit_output_encoding();
3518 const char *commit_buffer = repo_logmsg_reencode(r,
3519 commit, NULL,
3520 encoding);
3521 find_commit_subject(commit_buffer, &subject);
3522 res |= write_message(subject, strlen(subject), buf.buf, 1);
3523 repo_unuse_commit_buffer(r, commit,
3524 commit_buffer);
3526 strbuf_release(&buf);
3527 release_revisions(&log_tree_opt);
3529 return res;
3532 static int intend_to_amend(void)
3534 struct object_id head;
3535 char *p;
3537 if (repo_get_oid(the_repository, "HEAD", &head))
3538 return error(_("cannot read HEAD"));
3540 p = oid_to_hex(&head);
3541 return write_message(p, strlen(p), rebase_path_amend(), 1);
3544 static int error_with_patch(struct repository *r,
3545 struct commit *commit,
3546 const char *subject, int subject_len,
3547 struct replay_opts *opts,
3548 int exit_code, int to_amend)
3550 if (commit) {
3551 if (make_patch(r, commit, opts))
3552 return -1;
3553 } else if (copy_file(rebase_path_message(),
3554 git_path_merge_msg(r), 0666))
3555 return error(_("unable to copy '%s' to '%s'"),
3556 git_path_merge_msg(r), rebase_path_message());
3558 if (to_amend) {
3559 if (intend_to_amend())
3560 return -1;
3562 fprintf(stderr,
3563 _("You can amend the commit now, with\n"
3564 "\n"
3565 " git commit --amend %s\n"
3566 "\n"
3567 "Once you are satisfied with your changes, run\n"
3568 "\n"
3569 " git rebase --continue\n"),
3570 gpg_sign_opt_quoted(opts));
3571 } else if (exit_code) {
3572 if (commit)
3573 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3574 short_commit_name(commit), subject_len, subject);
3575 else
3577 * We don't have the hash of the parent so
3578 * just print the line from the todo file.
3580 fprintf_ln(stderr, _("Could not merge %.*s"),
3581 subject_len, subject);
3584 return exit_code;
3587 static int error_failed_squash(struct repository *r,
3588 struct commit *commit,
3589 struct replay_opts *opts,
3590 int subject_len,
3591 const char *subject)
3593 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3594 return error(_("could not copy '%s' to '%s'"),
3595 rebase_path_squash_msg(), rebase_path_message());
3596 unlink(git_path_merge_msg(r));
3597 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3598 return error(_("could not copy '%s' to '%s'"),
3599 rebase_path_message(),
3600 git_path_merge_msg(r));
3601 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3604 static int do_exec(struct repository *r, const char *command_line)
3606 struct child_process cmd = CHILD_PROCESS_INIT;
3607 int dirty, status;
3609 fprintf(stderr, _("Executing: %s\n"), command_line);
3610 cmd.use_shell = 1;
3611 strvec_push(&cmd.args, command_line);
3612 status = run_command(&cmd);
3614 /* force re-reading of the cache */
3615 discard_index(r->index);
3616 if (repo_read_index(r) < 0)
3617 return error(_("could not read index"));
3619 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3621 if (status) {
3622 warning(_("execution failed: %s\n%s"
3623 "You can fix the problem, and then run\n"
3624 "\n"
3625 " git rebase --continue\n"
3626 "\n"),
3627 command_line,
3628 dirty ? N_("and made changes to the index and/or the "
3629 "working tree\n") : "");
3630 if (status == 127)
3631 /* command not found */
3632 status = 1;
3633 } else if (dirty) {
3634 warning(_("execution succeeded: %s\nbut "
3635 "left changes to the index and/or the working tree\n"
3636 "Commit or stash your changes, and then run\n"
3637 "\n"
3638 " git rebase --continue\n"
3639 "\n"), command_line);
3640 status = 1;
3643 return status;
3646 __attribute__((format (printf, 2, 3)))
3647 static int safe_append(const char *filename, const char *fmt, ...)
3649 va_list ap;
3650 struct lock_file lock = LOCK_INIT;
3651 int fd = hold_lock_file_for_update(&lock, filename,
3652 LOCK_REPORT_ON_ERROR);
3653 struct strbuf buf = STRBUF_INIT;
3655 if (fd < 0)
3656 return -1;
3658 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3659 error_errno(_("could not read '%s'"), filename);
3660 rollback_lock_file(&lock);
3661 return -1;
3663 strbuf_complete(&buf, '\n');
3664 va_start(ap, fmt);
3665 strbuf_vaddf(&buf, fmt, ap);
3666 va_end(ap);
3668 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3669 error_errno(_("could not write to '%s'"), filename);
3670 strbuf_release(&buf);
3671 rollback_lock_file(&lock);
3672 return -1;
3674 if (commit_lock_file(&lock) < 0) {
3675 strbuf_release(&buf);
3676 return error(_("failed to finalize '%s'"), filename);
3679 strbuf_release(&buf);
3680 return 0;
3683 static int do_label(struct repository *r, const char *name, int len)
3685 struct ref_store *refs = get_main_ref_store(r);
3686 struct ref_transaction *transaction;
3687 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3688 struct strbuf msg = STRBUF_INIT;
3689 int ret = 0;
3690 struct object_id head_oid;
3692 if (len == 1 && *name == '#')
3693 return error(_("illegal label name: '%.*s'"), len, name);
3695 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3696 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3698 transaction = ref_store_transaction_begin(refs, &err);
3699 if (!transaction) {
3700 error("%s", err.buf);
3701 ret = -1;
3702 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3703 error(_("could not read HEAD"));
3704 ret = -1;
3705 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3706 NULL, 0, msg.buf, &err) < 0 ||
3707 ref_transaction_commit(transaction, &err)) {
3708 error("%s", err.buf);
3709 ret = -1;
3711 ref_transaction_free(transaction);
3712 strbuf_release(&err);
3713 strbuf_release(&msg);
3715 if (!ret)
3716 ret = safe_append(rebase_path_refs_to_delete(),
3717 "%s\n", ref_name.buf);
3718 strbuf_release(&ref_name);
3720 return ret;
3723 static const char *sequencer_reflog_action(struct replay_opts *opts)
3725 if (!opts->reflog_action) {
3726 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3727 opts->reflog_action =
3728 xstrdup(opts->reflog_action ? opts->reflog_action
3729 : action_name(opts));
3732 return opts->reflog_action;
3735 __attribute__((format (printf, 3, 4)))
3736 static const char *reflog_message(struct replay_opts *opts,
3737 const char *sub_action, const char *fmt, ...)
3739 va_list ap;
3740 static struct strbuf buf = STRBUF_INIT;
3742 va_start(ap, fmt);
3743 strbuf_reset(&buf);
3744 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3745 if (sub_action)
3746 strbuf_addf(&buf, " (%s)", sub_action);
3747 if (fmt) {
3748 strbuf_addstr(&buf, ": ");
3749 strbuf_vaddf(&buf, fmt, ap);
3751 va_end(ap);
3753 return buf.buf;
3756 static struct commit *lookup_label(struct repository *r, const char *label,
3757 int len, struct strbuf *buf)
3759 struct commit *commit;
3760 struct object_id oid;
3762 strbuf_reset(buf);
3763 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3764 if (!read_ref(buf->buf, &oid)) {
3765 commit = lookup_commit_object(r, &oid);
3766 } else {
3767 /* fall back to non-rewritten ref or commit */
3768 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3769 commit = lookup_commit_reference_by_name(buf->buf);
3772 if (!commit)
3773 error(_("could not resolve '%s'"), buf->buf);
3775 return commit;
3778 static int do_reset(struct repository *r,
3779 const char *name, int len,
3780 struct replay_opts *opts)
3782 struct strbuf ref_name = STRBUF_INIT;
3783 struct object_id oid;
3784 struct lock_file lock = LOCK_INIT;
3785 struct tree_desc desc = { 0 };
3786 struct tree *tree;
3787 struct unpack_trees_options unpack_tree_opts = { 0 };
3788 int ret = 0;
3790 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3791 return -1;
3793 if (len == 10 && !strncmp("[new root]", name, len)) {
3794 if (!opts->have_squash_onto) {
3795 const char *hex;
3796 if (commit_tree("", 0, the_hash_algo->empty_tree,
3797 NULL, &opts->squash_onto,
3798 NULL, NULL))
3799 return error(_("writing fake root commit"));
3800 opts->have_squash_onto = 1;
3801 hex = oid_to_hex(&opts->squash_onto);
3802 if (write_message(hex, strlen(hex),
3803 rebase_path_squash_onto(), 0))
3804 return error(_("writing squash-onto"));
3806 oidcpy(&oid, &opts->squash_onto);
3807 } else {
3808 int i;
3809 struct commit *commit;
3811 /* Determine the length of the label */
3812 for (i = 0; i < len; i++)
3813 if (isspace(name[i]))
3814 break;
3815 len = i;
3817 commit = lookup_label(r, name, len, &ref_name);
3818 if (!commit) {
3819 ret = -1;
3820 goto cleanup;
3822 oid = commit->object.oid;
3825 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3826 unpack_tree_opts.head_idx = 1;
3827 unpack_tree_opts.src_index = r->index;
3828 unpack_tree_opts.dst_index = r->index;
3829 unpack_tree_opts.fn = oneway_merge;
3830 unpack_tree_opts.merge = 1;
3831 unpack_tree_opts.update = 1;
3832 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3833 unpack_tree_opts.skip_cache_tree_update = 1;
3834 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3836 if (repo_read_index_unmerged(r)) {
3837 ret = error_resolve_conflict(action_name(opts));
3838 goto cleanup;
3841 if (!fill_tree_descriptor(r, &desc, &oid)) {
3842 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3843 goto cleanup;
3846 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3847 ret = -1;
3848 goto cleanup;
3851 tree = parse_tree_indirect(&oid);
3852 prime_cache_tree(r, r->index, tree);
3854 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3855 ret = error(_("could not write index"));
3857 if (!ret)
3858 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3859 len, name), "HEAD", &oid,
3860 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3861 cleanup:
3862 free((void *)desc.buffer);
3863 if (ret < 0)
3864 rollback_lock_file(&lock);
3865 strbuf_release(&ref_name);
3866 clear_unpack_trees_porcelain(&unpack_tree_opts);
3867 return ret;
3870 static int do_merge(struct repository *r,
3871 struct commit *commit,
3872 const char *arg, int arg_len,
3873 int flags, int *check_todo, struct replay_opts *opts)
3875 int run_commit_flags = 0;
3876 struct strbuf ref_name = STRBUF_INIT;
3877 struct commit *head_commit, *merge_commit, *i;
3878 struct commit_list *bases, *j;
3879 struct commit_list *to_merge = NULL, **tail = &to_merge;
3880 const char *strategy = !opts->xopts.nr &&
3881 (!opts->strategy ||
3882 !strcmp(opts->strategy, "recursive") ||
3883 !strcmp(opts->strategy, "ort")) ?
3884 NULL : opts->strategy;
3885 struct merge_options o;
3886 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3887 static struct lock_file lock;
3888 const char *p;
3890 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3891 ret = -1;
3892 goto leave_merge;
3895 head_commit = lookup_commit_reference_by_name("HEAD");
3896 if (!head_commit) {
3897 ret = error(_("cannot merge without a current revision"));
3898 goto leave_merge;
3902 * For octopus merges, the arg starts with the list of revisions to be
3903 * merged. The list is optionally followed by '#' and the oneline.
3905 merge_arg_len = oneline_offset = arg_len;
3906 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3907 if (!*p)
3908 break;
3909 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3910 p += 1 + strspn(p + 1, " \t\n");
3911 oneline_offset = p - arg;
3912 break;
3914 k = strcspn(p, " \t\n");
3915 if (!k)
3916 continue;
3917 merge_commit = lookup_label(r, p, k, &ref_name);
3918 if (!merge_commit) {
3919 ret = error(_("unable to parse '%.*s'"), k, p);
3920 goto leave_merge;
3922 tail = &commit_list_insert(merge_commit, tail)->next;
3923 p += k;
3924 merge_arg_len = p - arg;
3927 if (!to_merge) {
3928 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3929 goto leave_merge;
3932 if (opts->have_squash_onto &&
3933 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3935 * When the user tells us to "merge" something into a
3936 * "[new root]", let's simply fast-forward to the merge head.
3938 rollback_lock_file(&lock);
3939 if (to_merge->next)
3940 ret = error(_("octopus merge cannot be executed on "
3941 "top of a [new root]"));
3942 else
3943 ret = fast_forward_to(r, &to_merge->item->object.oid,
3944 &head_commit->object.oid, 0,
3945 opts);
3946 goto leave_merge;
3950 * If HEAD is not identical to the first parent of the original merge
3951 * commit, we cannot fast-forward.
3953 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3954 oideq(&commit->parents->item->object.oid,
3955 &head_commit->object.oid);
3958 * If any merge head is different from the original one, we cannot
3959 * fast-forward.
3961 if (can_fast_forward) {
3962 struct commit_list *p = commit->parents->next;
3964 for (j = to_merge; j && p; j = j->next, p = p->next)
3965 if (!oideq(&j->item->object.oid,
3966 &p->item->object.oid)) {
3967 can_fast_forward = 0;
3968 break;
3971 * If the number of merge heads differs from the original merge
3972 * commit, we cannot fast-forward.
3974 if (j || p)
3975 can_fast_forward = 0;
3978 if (can_fast_forward) {
3979 rollback_lock_file(&lock);
3980 ret = fast_forward_to(r, &commit->object.oid,
3981 &head_commit->object.oid, 0, opts);
3982 if (flags & TODO_EDIT_MERGE_MSG)
3983 goto fast_forward_edit;
3985 goto leave_merge;
3988 if (commit) {
3989 const char *encoding = get_commit_output_encoding();
3990 const char *message = repo_logmsg_reencode(r, commit, NULL,
3991 encoding);
3992 const char *body;
3993 int len;
3995 if (!message) {
3996 ret = error(_("could not get commit message of '%s'"),
3997 oid_to_hex(&commit->object.oid));
3998 goto leave_merge;
4000 write_author_script(message);
4001 find_commit_subject(message, &body);
4002 len = strlen(body);
4003 ret = write_message(body, len, git_path_merge_msg(r), 0);
4004 repo_unuse_commit_buffer(r, commit, message);
4005 if (ret) {
4006 error_errno(_("could not write '%s'"),
4007 git_path_merge_msg(r));
4008 goto leave_merge;
4010 } else {
4011 struct strbuf buf = STRBUF_INIT;
4012 int len;
4014 strbuf_addf(&buf, "author %s", git_author_info(0));
4015 write_author_script(buf.buf);
4016 strbuf_reset(&buf);
4018 if (oneline_offset < arg_len) {
4019 p = arg + oneline_offset;
4020 len = arg_len - oneline_offset;
4021 } else {
4022 strbuf_addf(&buf, "Merge %s '%.*s'",
4023 to_merge->next ? "branches" : "branch",
4024 merge_arg_len, arg);
4025 p = buf.buf;
4026 len = buf.len;
4029 ret = write_message(p, len, git_path_merge_msg(r), 0);
4030 strbuf_release(&buf);
4031 if (ret) {
4032 error_errno(_("could not write '%s'"),
4033 git_path_merge_msg(r));
4034 goto leave_merge;
4038 if (strategy || to_merge->next) {
4039 /* Octopus merge */
4040 struct child_process cmd = CHILD_PROCESS_INIT;
4042 if (read_env_script(&cmd.env)) {
4043 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4045 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4046 goto leave_merge;
4049 if (opts->committer_date_is_author_date)
4050 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4051 opts->ignore_date ?
4052 "" :
4053 author_date_from_env(&cmd.env));
4054 if (opts->ignore_date)
4055 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4057 cmd.git_cmd = 1;
4058 strvec_push(&cmd.args, "merge");
4059 strvec_push(&cmd.args, "-s");
4060 if (!strategy)
4061 strvec_push(&cmd.args, "octopus");
4062 else {
4063 strvec_push(&cmd.args, strategy);
4064 for (k = 0; k < opts->xopts.nr; k++)
4065 strvec_pushf(&cmd.args,
4066 "-X%s", opts->xopts.v[k]);
4068 if (!(flags & TODO_EDIT_MERGE_MSG))
4069 strvec_push(&cmd.args, "--no-edit");
4070 else
4071 strvec_push(&cmd.args, "--edit");
4072 strvec_push(&cmd.args, "--no-ff");
4073 strvec_push(&cmd.args, "--no-log");
4074 strvec_push(&cmd.args, "--no-stat");
4075 strvec_push(&cmd.args, "-F");
4076 strvec_push(&cmd.args, git_path_merge_msg(r));
4077 if (opts->gpg_sign)
4078 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4079 else
4080 strvec_push(&cmd.args, "--no-gpg-sign");
4082 /* Add the tips to be merged */
4083 for (j = to_merge; j; j = j->next)
4084 strvec_push(&cmd.args,
4085 oid_to_hex(&j->item->object.oid));
4087 strbuf_release(&ref_name);
4088 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4089 NULL, 0);
4090 rollback_lock_file(&lock);
4092 ret = run_command(&cmd);
4094 /* force re-reading of the cache */
4095 if (!ret) {
4096 discard_index(r->index);
4097 if (repo_read_index(r) < 0)
4098 ret = error(_("could not read index"));
4100 goto leave_merge;
4103 merge_commit = to_merge->item;
4104 bases = repo_get_merge_bases(r, head_commit, merge_commit);
4105 if (bases && oideq(&merge_commit->object.oid,
4106 &bases->item->object.oid)) {
4107 ret = 0;
4108 /* skip merging an ancestor of HEAD */
4109 goto leave_merge;
4112 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4113 git_path_merge_head(r), 0);
4114 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4116 bases = reverse_commit_list(bases);
4118 repo_read_index(r);
4119 init_merge_options(&o, r);
4120 o.branch1 = "HEAD";
4121 o.branch2 = ref_name.buf;
4122 o.buffer_output = 2;
4124 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4126 * TODO: Should use merge_incore_recursive() and
4127 * merge_switch_to_result(), skipping the call to
4128 * merge_switch_to_result() when we don't actually need to
4129 * update the index and working copy immediately.
4131 ret = merge_ort_recursive(&o,
4132 head_commit, merge_commit, bases,
4133 &i);
4134 } else {
4135 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4136 &i);
4138 if (ret <= 0)
4139 fputs(o.obuf.buf, stdout);
4140 strbuf_release(&o.obuf);
4141 if (ret < 0) {
4142 error(_("could not even attempt to merge '%.*s'"),
4143 merge_arg_len, arg);
4144 goto leave_merge;
4147 * The return value of merge_recursive() is 1 on clean, and 0 on
4148 * unclean merge.
4150 * Let's reverse that, so that do_merge() returns 0 upon success and
4151 * 1 upon failed merge (keeping the return value -1 for the cases where
4152 * we will want to reschedule the `merge` command).
4154 ret = !ret;
4156 if (r->index->cache_changed &&
4157 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4158 ret = error(_("merge: Unable to write new index file"));
4159 goto leave_merge;
4162 rollback_lock_file(&lock);
4163 if (ret)
4164 repo_rerere(r, opts->allow_rerere_auto);
4165 else
4167 * In case of problems, we now want to return a positive
4168 * value (a negative one would indicate that the `merge`
4169 * command needs to be rescheduled).
4171 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4172 run_commit_flags);
4174 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4175 fast_forward_edit:
4176 *check_todo = 1;
4177 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4178 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4182 leave_merge:
4183 strbuf_release(&ref_name);
4184 rollback_lock_file(&lock);
4185 free_commit_list(to_merge);
4186 return ret;
4189 static int write_update_refs_state(struct string_list *refs_to_oids)
4191 int result = 0;
4192 struct lock_file lock = LOCK_INIT;
4193 FILE *fp = NULL;
4194 struct string_list_item *item;
4195 char *path;
4197 path = rebase_path_update_refs(the_repository->gitdir);
4199 if (!refs_to_oids->nr) {
4200 if (unlink(path) && errno != ENOENT)
4201 result = error_errno(_("could not unlink: %s"), path);
4202 goto cleanup;
4205 if (safe_create_leading_directories(path)) {
4206 result = error(_("unable to create leading directories of %s"),
4207 path);
4208 goto cleanup;
4211 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4212 result = error(_("another 'rebase' process appears to be running; "
4213 "'%s.lock' already exists"),
4214 path);
4215 goto cleanup;
4218 fp = fdopen_lock_file(&lock, "w");
4219 if (!fp) {
4220 result = error_errno(_("could not open '%s' for writing"), path);
4221 rollback_lock_file(&lock);
4222 goto cleanup;
4225 for_each_string_list_item(item, refs_to_oids) {
4226 struct update_ref_record *rec = item->util;
4227 fprintf(fp, "%s\n%s\n%s\n", item->string,
4228 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4231 result = commit_lock_file(&lock);
4233 cleanup:
4234 free(path);
4235 return result;
4239 * Parse the update-refs file for the current rebase, then remove the
4240 * refs that do not appear in the todo_list (and have not had updated
4241 * values stored) and add refs that are in the todo_list but not
4242 * represented in the update-refs file.
4244 * If there are changes to the update-refs list, then write the new state
4245 * to disk.
4247 void todo_list_filter_update_refs(struct repository *r,
4248 struct todo_list *todo_list)
4250 int i;
4251 int updated = 0;
4252 struct string_list update_refs = STRING_LIST_INIT_DUP;
4254 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4257 * For each item in the update_refs list, if it has no updated
4258 * value and does not appear in the todo_list, then remove it
4259 * from the update_refs list.
4261 for (i = 0; i < update_refs.nr; i++) {
4262 int j;
4263 int found = 0;
4264 const char *ref = update_refs.items[i].string;
4265 size_t reflen = strlen(ref);
4266 struct update_ref_record *rec = update_refs.items[i].util;
4268 /* OID already stored as updated. */
4269 if (!is_null_oid(&rec->after))
4270 continue;
4272 for (j = 0; !found && j < todo_list->total_nr; j++) {
4273 struct todo_item *item = &todo_list->items[j];
4274 const char *arg = todo_list->buf.buf + item->arg_offset;
4276 if (item->command != TODO_UPDATE_REF)
4277 continue;
4279 if (item->arg_len != reflen ||
4280 strncmp(arg, ref, reflen))
4281 continue;
4283 found = 1;
4286 if (!found) {
4287 free(update_refs.items[i].string);
4288 free(update_refs.items[i].util);
4290 update_refs.nr--;
4291 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4293 updated = 1;
4294 i--;
4299 * For each todo_item, check if its ref is in the update_refs list.
4300 * If not, then add it as an un-updated ref.
4302 for (i = 0; i < todo_list->total_nr; i++) {
4303 struct todo_item *item = &todo_list->items[i];
4304 const char *arg = todo_list->buf.buf + item->arg_offset;
4305 int j, found = 0;
4307 if (item->command != TODO_UPDATE_REF)
4308 continue;
4310 for (j = 0; !found && j < update_refs.nr; j++) {
4311 const char *ref = update_refs.items[j].string;
4313 found = strlen(ref) == item->arg_len &&
4314 !strncmp(ref, arg, item->arg_len);
4317 if (!found) {
4318 struct string_list_item *inserted;
4319 struct strbuf argref = STRBUF_INIT;
4321 strbuf_add(&argref, arg, item->arg_len);
4322 inserted = string_list_insert(&update_refs, argref.buf);
4323 inserted->util = init_update_ref_record(argref.buf);
4324 strbuf_release(&argref);
4325 updated = 1;
4329 if (updated)
4330 write_update_refs_state(&update_refs);
4331 string_list_clear(&update_refs, 1);
4334 static int do_update_ref(struct repository *r, const char *refname)
4336 struct string_list_item *item;
4337 struct string_list list = STRING_LIST_INIT_DUP;
4339 if (sequencer_get_update_refs_state(r->gitdir, &list))
4340 return -1;
4342 for_each_string_list_item(item, &list) {
4343 if (!strcmp(item->string, refname)) {
4344 struct update_ref_record *rec = item->util;
4345 if (read_ref("HEAD", &rec->after))
4346 return -1;
4347 break;
4351 write_update_refs_state(&list);
4352 string_list_clear(&list, 1);
4353 return 0;
4356 static int do_update_refs(struct repository *r, int quiet)
4358 int res = 0;
4359 struct string_list_item *item;
4360 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4361 struct ref_store *refs = get_main_ref_store(r);
4362 struct strbuf update_msg = STRBUF_INIT;
4363 struct strbuf error_msg = STRBUF_INIT;
4365 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4366 return res;
4368 for_each_string_list_item(item, &refs_to_oids) {
4369 struct update_ref_record *rec = item->util;
4370 int loop_res;
4372 loop_res = refs_update_ref(refs, "rewritten during rebase",
4373 item->string,
4374 &rec->after, &rec->before,
4375 0, UPDATE_REFS_MSG_ON_ERR);
4376 res |= loop_res;
4378 if (quiet)
4379 continue;
4381 if (loop_res)
4382 strbuf_addf(&error_msg, "\t%s\n", item->string);
4383 else
4384 strbuf_addf(&update_msg, "\t%s\n", item->string);
4387 if (!quiet &&
4388 (update_msg.len || error_msg.len)) {
4389 fprintf(stderr,
4390 _("Updated the following refs with %s:\n%s"),
4391 "--update-refs",
4392 update_msg.buf);
4394 if (res)
4395 fprintf(stderr,
4396 _("Failed to update the following refs with %s:\n%s"),
4397 "--update-refs",
4398 error_msg.buf);
4401 string_list_clear(&refs_to_oids, 1);
4402 strbuf_release(&update_msg);
4403 strbuf_release(&error_msg);
4404 return res;
4407 static int is_final_fixup(struct todo_list *todo_list)
4409 int i = todo_list->current;
4411 if (!is_fixup(todo_list->items[i].command))
4412 return 0;
4414 while (++i < todo_list->nr)
4415 if (is_fixup(todo_list->items[i].command))
4416 return 0;
4417 else if (!is_noop(todo_list->items[i].command))
4418 break;
4419 return 1;
4422 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4424 int i;
4426 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4427 if (!is_noop(todo_list->items[i].command))
4428 return todo_list->items[i].command;
4430 return -1;
4433 void create_autostash(struct repository *r, const char *path)
4435 struct strbuf buf = STRBUF_INIT;
4436 struct lock_file lock_file = LOCK_INIT;
4437 int fd;
4439 fd = repo_hold_locked_index(r, &lock_file, 0);
4440 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4441 if (0 <= fd)
4442 repo_update_index_if_able(r, &lock_file);
4443 rollback_lock_file(&lock_file);
4445 if (has_unstaged_changes(r, 1) ||
4446 has_uncommitted_changes(r, 1)) {
4447 struct child_process stash = CHILD_PROCESS_INIT;
4448 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4449 struct object_id oid;
4451 strvec_pushl(&stash.args,
4452 "stash", "create", "autostash", NULL);
4453 stash.git_cmd = 1;
4454 stash.no_stdin = 1;
4455 strbuf_reset(&buf);
4456 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4457 die(_("Cannot autostash"));
4458 strbuf_trim_trailing_newline(&buf);
4459 if (repo_get_oid(r, buf.buf, &oid))
4460 die(_("Unexpected stash response: '%s'"),
4461 buf.buf);
4462 strbuf_reset(&buf);
4463 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4465 if (safe_create_leading_directories_const(path))
4466 die(_("Could not create directory for '%s'"),
4467 path);
4468 write_file(path, "%s", oid_to_hex(&oid));
4469 printf(_("Created autostash: %s\n"), buf.buf);
4470 if (reset_head(r, &ropts) < 0)
4471 die(_("could not reset --hard"));
4472 discard_index(r->index);
4473 if (repo_read_index(r) < 0)
4474 die(_("could not read index"));
4476 strbuf_release(&buf);
4479 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4481 struct child_process child = CHILD_PROCESS_INIT;
4482 int ret = 0;
4484 if (attempt_apply) {
4485 child.git_cmd = 1;
4486 child.no_stdout = 1;
4487 child.no_stderr = 1;
4488 strvec_push(&child.args, "stash");
4489 strvec_push(&child.args, "apply");
4490 strvec_push(&child.args, stash_oid);
4491 ret = run_command(&child);
4494 if (attempt_apply && !ret)
4495 fprintf(stderr, _("Applied autostash.\n"));
4496 else {
4497 struct child_process store = CHILD_PROCESS_INIT;
4499 store.git_cmd = 1;
4500 strvec_push(&store.args, "stash");
4501 strvec_push(&store.args, "store");
4502 strvec_push(&store.args, "-m");
4503 strvec_push(&store.args, "autostash");
4504 strvec_push(&store.args, "-q");
4505 strvec_push(&store.args, stash_oid);
4506 if (run_command(&store))
4507 ret = error(_("cannot store %s"), stash_oid);
4508 else
4509 fprintf(stderr,
4510 _("%s\n"
4511 "Your changes are safe in the stash.\n"
4512 "You can run \"git stash pop\" or"
4513 " \"git stash drop\" at any time.\n"),
4514 attempt_apply ?
4515 _("Applying autostash resulted in conflicts.") :
4516 _("Autostash exists; creating a new stash entry."));
4519 return ret;
4522 static int apply_save_autostash(const char *path, int attempt_apply)
4524 struct strbuf stash_oid = STRBUF_INIT;
4525 int ret = 0;
4527 if (!read_oneliner(&stash_oid, path,
4528 READ_ONELINER_SKIP_IF_EMPTY)) {
4529 strbuf_release(&stash_oid);
4530 return 0;
4532 strbuf_trim(&stash_oid);
4534 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4536 unlink(path);
4537 strbuf_release(&stash_oid);
4538 return ret;
4541 int save_autostash(const char *path)
4543 return apply_save_autostash(path, 0);
4546 int apply_autostash(const char *path)
4548 return apply_save_autostash(path, 1);
4551 int apply_autostash_oid(const char *stash_oid)
4553 return apply_save_autostash_oid(stash_oid, 1);
4556 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4557 const char *onto_name, const struct object_id *onto,
4558 const struct object_id *orig_head)
4560 struct reset_head_opts ropts = {
4561 .oid = onto,
4562 .orig_head = orig_head,
4563 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4564 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4565 .head_msg = reflog_message(opts, "start", "checkout %s",
4566 onto_name),
4567 .default_reflog_action = sequencer_reflog_action(opts)
4569 if (reset_head(r, &ropts)) {
4570 apply_autostash(rebase_path_autostash());
4571 sequencer_remove_state(opts);
4572 return error(_("could not detach HEAD"));
4575 return 0;
4578 static int stopped_at_head(struct repository *r)
4580 struct object_id head;
4581 struct commit *commit;
4582 struct commit_message message;
4584 if (repo_get_oid(r, "HEAD", &head) ||
4585 !(commit = lookup_commit(r, &head)) ||
4586 repo_parse_commit(r, commit) || get_message(commit, &message))
4587 fprintf(stderr, _("Stopped at HEAD\n"));
4588 else {
4589 fprintf(stderr, _("Stopped at %s\n"), message.label);
4590 free_message(commit, &message);
4592 return 0;
4596 static int reread_todo_if_changed(struct repository *r,
4597 struct todo_list *todo_list,
4598 struct replay_opts *opts)
4600 int offset;
4601 struct strbuf buf = STRBUF_INIT;
4603 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4604 return -1;
4605 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4606 if (buf.len != todo_list->buf.len - offset ||
4607 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4608 /* Reread the todo file if it has changed. */
4609 todo_list_release(todo_list);
4610 if (read_populate_todo(r, todo_list, opts))
4611 return -1; /* message was printed */
4612 /* `current` will be incremented on return */
4613 todo_list->current = -1;
4615 strbuf_release(&buf);
4617 return 0;
4620 static const char rescheduled_advice[] =
4621 N_("Could not execute the todo command\n"
4622 "\n"
4623 " %.*s"
4624 "\n"
4625 "It has been rescheduled; To edit the command before continuing, please\n"
4626 "edit the todo list first:\n"
4627 "\n"
4628 " git rebase --edit-todo\n"
4629 " git rebase --continue\n");
4631 static int pick_commits(struct repository *r,
4632 struct todo_list *todo_list,
4633 struct replay_opts *opts)
4635 int res = 0, reschedule = 0;
4637 opts->reflog_message = sequencer_reflog_action(opts);
4638 if (opts->allow_ff)
4639 assert(!(opts->signoff || opts->no_commit ||
4640 opts->record_origin || should_edit(opts) ||
4641 opts->committer_date_is_author_date ||
4642 opts->ignore_date));
4643 if (read_and_refresh_cache(r, opts))
4644 return -1;
4646 while (todo_list->current < todo_list->nr) {
4647 struct todo_item *item = todo_list->items + todo_list->current;
4648 const char *arg = todo_item_get_arg(todo_list, item);
4649 int check_todo = 0;
4651 if (save_todo(todo_list, opts))
4652 return -1;
4653 if (is_rebase_i(opts)) {
4654 if (item->command != TODO_COMMENT) {
4655 FILE *f = fopen(rebase_path_msgnum(), "w");
4657 todo_list->done_nr++;
4659 if (f) {
4660 fprintf(f, "%d\n", todo_list->done_nr);
4661 fclose(f);
4663 if (!opts->quiet)
4664 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4665 todo_list->done_nr,
4666 todo_list->total_nr,
4667 opts->verbose ? "\n" : "\r");
4669 unlink(rebase_path_message());
4670 unlink(rebase_path_author_script());
4671 unlink(rebase_path_stopped_sha());
4672 unlink(rebase_path_amend());
4673 unlink(git_path_merge_head(r));
4674 unlink(git_path_auto_merge(r));
4675 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4677 if (item->command == TODO_BREAK) {
4678 if (!opts->verbose)
4679 term_clear_line();
4680 return stopped_at_head(r);
4683 if (item->command <= TODO_SQUASH) {
4684 if (is_rebase_i(opts))
4685 opts->reflog_message = reflog_message(opts,
4686 command_to_string(item->command), NULL);
4688 res = do_pick_commit(r, item, opts,
4689 is_final_fixup(todo_list),
4690 &check_todo);
4691 if (is_rebase_i(opts) && res < 0) {
4692 /* Reschedule */
4693 advise(_(rescheduled_advice),
4694 get_item_line_length(todo_list,
4695 todo_list->current),
4696 get_item_line(todo_list,
4697 todo_list->current));
4698 todo_list->current--;
4699 if (save_todo(todo_list, opts))
4700 return -1;
4702 if (item->command == TODO_EDIT) {
4703 struct commit *commit = item->commit;
4704 if (!res) {
4705 if (!opts->verbose)
4706 term_clear_line();
4707 fprintf(stderr,
4708 _("Stopped at %s... %.*s\n"),
4709 short_commit_name(commit),
4710 item->arg_len, arg);
4712 return error_with_patch(r, commit,
4713 arg, item->arg_len, opts, res, !res);
4715 if (is_rebase_i(opts) && !res)
4716 record_in_rewritten(&item->commit->object.oid,
4717 peek_command(todo_list, 1));
4718 if (res && is_fixup(item->command)) {
4719 if (res == 1)
4720 intend_to_amend();
4721 return error_failed_squash(r, item->commit, opts,
4722 item->arg_len, arg);
4723 } else if (res && is_rebase_i(opts) && item->commit) {
4724 int to_amend = 0;
4725 struct object_id oid;
4728 * If we are rewording and have either
4729 * fast-forwarded already, or are about to
4730 * create a new root commit, we want to amend,
4731 * otherwise we do not.
4733 if (item->command == TODO_REWORD &&
4734 !repo_get_oid(r, "HEAD", &oid) &&
4735 (oideq(&item->commit->object.oid, &oid) ||
4736 (opts->have_squash_onto &&
4737 oideq(&opts->squash_onto, &oid))))
4738 to_amend = 1;
4740 return res | error_with_patch(r, item->commit,
4741 arg, item->arg_len, opts,
4742 res, to_amend);
4744 } else if (item->command == TODO_EXEC) {
4745 char *end_of_arg = (char *)(arg + item->arg_len);
4746 int saved = *end_of_arg;
4748 if (!opts->verbose)
4749 term_clear_line();
4750 *end_of_arg = '\0';
4751 res = do_exec(r, arg);
4752 *end_of_arg = saved;
4754 if (res) {
4755 if (opts->reschedule_failed_exec)
4756 reschedule = 1;
4758 check_todo = 1;
4759 } else if (item->command == TODO_LABEL) {
4760 if ((res = do_label(r, arg, item->arg_len)))
4761 reschedule = 1;
4762 } else if (item->command == TODO_RESET) {
4763 if ((res = do_reset(r, arg, item->arg_len, opts)))
4764 reschedule = 1;
4765 } else if (item->command == TODO_MERGE) {
4766 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4767 item->flags, &check_todo, opts)) < 0)
4768 reschedule = 1;
4769 else if (item->commit)
4770 record_in_rewritten(&item->commit->object.oid,
4771 peek_command(todo_list, 1));
4772 if (res > 0)
4773 /* failed with merge conflicts */
4774 return error_with_patch(r, item->commit,
4775 arg, item->arg_len,
4776 opts, res, 0);
4777 } else if (item->command == TODO_UPDATE_REF) {
4778 struct strbuf ref = STRBUF_INIT;
4779 strbuf_add(&ref, arg, item->arg_len);
4780 if ((res = do_update_ref(r, ref.buf)))
4781 reschedule = 1;
4782 strbuf_release(&ref);
4783 } else if (!is_noop(item->command))
4784 return error(_("unknown command %d"), item->command);
4786 if (reschedule) {
4787 advise(_(rescheduled_advice),
4788 get_item_line_length(todo_list,
4789 todo_list->current),
4790 get_item_line(todo_list, todo_list->current));
4791 todo_list->current--;
4792 if (save_todo(todo_list, opts))
4793 return -1;
4794 if (item->commit)
4795 return error_with_patch(r,
4796 item->commit,
4797 arg, item->arg_len,
4798 opts, res, 0);
4799 } else if (is_rebase_i(opts) && check_todo && !res &&
4800 reread_todo_if_changed(r, todo_list, opts)) {
4801 return -1;
4804 todo_list->current++;
4805 if (res)
4806 return res;
4809 if (is_rebase_i(opts)) {
4810 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4811 struct stat st;
4813 /* Stopped in the middle, as planned? */
4814 if (todo_list->current < todo_list->nr)
4815 return 0;
4817 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4818 starts_with(head_ref.buf, "refs/")) {
4819 const char *msg;
4820 struct object_id head, orig;
4821 int res;
4823 if (repo_get_oid(r, "HEAD", &head)) {
4824 res = error(_("cannot read HEAD"));
4825 cleanup_head_ref:
4826 strbuf_release(&head_ref);
4827 strbuf_release(&buf);
4828 return res;
4830 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4831 get_oid_hex(buf.buf, &orig)) {
4832 res = error(_("could not read orig-head"));
4833 goto cleanup_head_ref;
4835 strbuf_reset(&buf);
4836 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4837 res = error(_("could not read 'onto'"));
4838 goto cleanup_head_ref;
4840 msg = reflog_message(opts, "finish", "%s onto %s",
4841 head_ref.buf, buf.buf);
4842 if (update_ref(msg, head_ref.buf, &head, &orig,
4843 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4844 res = error(_("could not update %s"),
4845 head_ref.buf);
4846 goto cleanup_head_ref;
4848 msg = reflog_message(opts, "finish", "returning to %s",
4849 head_ref.buf);
4850 if (create_symref("HEAD", head_ref.buf, msg)) {
4851 res = error(_("could not update HEAD to %s"),
4852 head_ref.buf);
4853 goto cleanup_head_ref;
4855 strbuf_reset(&buf);
4858 if (opts->verbose) {
4859 struct rev_info log_tree_opt;
4860 struct object_id orig, head;
4862 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4863 repo_init_revisions(r, &log_tree_opt, NULL);
4864 log_tree_opt.diff = 1;
4865 log_tree_opt.diffopt.output_format =
4866 DIFF_FORMAT_DIFFSTAT;
4867 log_tree_opt.disable_stdin = 1;
4869 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4870 !repo_get_oid(r, buf.buf, &orig) &&
4871 !repo_get_oid(r, "HEAD", &head)) {
4872 diff_tree_oid(&orig, &head, "",
4873 &log_tree_opt.diffopt);
4874 log_tree_diff_flush(&log_tree_opt);
4876 release_revisions(&log_tree_opt);
4878 flush_rewritten_pending();
4879 if (!stat(rebase_path_rewritten_list(), &st) &&
4880 st.st_size > 0) {
4881 struct child_process child = CHILD_PROCESS_INIT;
4882 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4884 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4885 child.git_cmd = 1;
4886 strvec_push(&child.args, "notes");
4887 strvec_push(&child.args, "copy");
4888 strvec_push(&child.args, "--for-rewrite=rebase");
4889 /* we don't care if this copying failed */
4890 run_command(&child);
4892 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4893 strvec_push(&hook_opt.args, "rebase");
4894 run_hooks_opt("post-rewrite", &hook_opt);
4896 apply_autostash(rebase_path_autostash());
4898 if (!opts->quiet) {
4899 if (!opts->verbose)
4900 term_clear_line();
4901 fprintf(stderr,
4902 _("Successfully rebased and updated %s.\n"),
4903 head_ref.buf);
4906 strbuf_release(&buf);
4907 strbuf_release(&head_ref);
4909 if (do_update_refs(r, opts->quiet))
4910 return -1;
4914 * Sequence of picks finished successfully; cleanup by
4915 * removing the .git/sequencer directory
4917 return sequencer_remove_state(opts);
4920 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4922 struct child_process cmd = CHILD_PROCESS_INIT;
4924 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4925 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4926 return error(_("no cherry-pick or revert in progress"));
4928 cmd.git_cmd = 1;
4929 strvec_push(&cmd.args, "commit");
4932 * continue_single_pick() handles the case of recovering from a
4933 * conflict. should_edit() doesn't handle that case; for a conflict,
4934 * we want to edit if the user asked for it, or if they didn't specify
4935 * and stdin is a tty.
4937 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4939 * Include --cleanup=strip as well because we don't want the
4940 * "# Conflicts:" messages.
4942 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4944 return run_command(&cmd);
4947 static int commit_staged_changes(struct repository *r,
4948 struct replay_opts *opts,
4949 struct todo_list *todo_list)
4951 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4952 unsigned int final_fixup = 0, is_clean;
4954 if (has_unstaged_changes(r, 1))
4955 return error(_("cannot rebase: You have unstaged changes."));
4957 is_clean = !has_uncommitted_changes(r, 0);
4959 if (file_exists(rebase_path_amend())) {
4960 struct strbuf rev = STRBUF_INIT;
4961 struct object_id head, to_amend;
4963 if (repo_get_oid(r, "HEAD", &head))
4964 return error(_("cannot amend non-existing commit"));
4965 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4966 return error(_("invalid file: '%s'"), rebase_path_amend());
4967 if (get_oid_hex(rev.buf, &to_amend))
4968 return error(_("invalid contents: '%s'"),
4969 rebase_path_amend());
4970 if (!is_clean && !oideq(&head, &to_amend))
4971 return error(_("\nYou have uncommitted changes in your "
4972 "working tree. Please, commit them\n"
4973 "first and then run 'git rebase "
4974 "--continue' again."));
4976 * When skipping a failed fixup/squash, we need to edit the
4977 * commit message, the current fixup list and count, and if it
4978 * was the last fixup/squash in the chain, we need to clean up
4979 * the commit message and if there was a squash, let the user
4980 * edit it.
4982 if (!is_clean || !opts->current_fixup_count)
4983 ; /* this is not the final fixup */
4984 else if (!oideq(&head, &to_amend) ||
4985 !file_exists(rebase_path_stopped_sha())) {
4986 /* was a final fixup or squash done manually? */
4987 if (!is_fixup(peek_command(todo_list, 0))) {
4988 unlink(rebase_path_fixup_msg());
4989 unlink(rebase_path_squash_msg());
4990 unlink(rebase_path_current_fixups());
4991 strbuf_reset(&opts->current_fixups);
4992 opts->current_fixup_count = 0;
4994 } else {
4995 /* we are in a fixup/squash chain */
4996 const char *p = opts->current_fixups.buf;
4997 int len = opts->current_fixups.len;
4999 opts->current_fixup_count--;
5000 if (!len)
5001 BUG("Incorrect current_fixups:\n%s", p);
5002 while (len && p[len - 1] != '\n')
5003 len--;
5004 strbuf_setlen(&opts->current_fixups, len);
5005 if (write_message(p, len, rebase_path_current_fixups(),
5006 0) < 0)
5007 return error(_("could not write file: '%s'"),
5008 rebase_path_current_fixups());
5011 * If a fixup/squash in a fixup/squash chain failed, the
5012 * commit message is already correct, no need to commit
5013 * it again.
5015 * Only if it is the final command in the fixup/squash
5016 * chain, and only if the chain is longer than a single
5017 * fixup/squash command (which was just skipped), do we
5018 * actually need to re-commit with a cleaned up commit
5019 * message.
5021 if (opts->current_fixup_count > 0 &&
5022 !is_fixup(peek_command(todo_list, 0))) {
5023 final_fixup = 1;
5025 * If there was not a single "squash" in the
5026 * chain, we only need to clean up the commit
5027 * message, no need to bother the user with
5028 * opening the commit message in the editor.
5030 if (!starts_with(p, "squash ") &&
5031 !strstr(p, "\nsquash "))
5032 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5033 } else if (is_fixup(peek_command(todo_list, 0))) {
5035 * We need to update the squash message to skip
5036 * the latest commit message.
5038 struct commit *commit;
5039 const char *path = rebase_path_squash_msg();
5040 const char *encoding = get_commit_output_encoding();
5042 if (parse_head(r, &commit) ||
5043 !(p = repo_logmsg_reencode(r, commit, NULL, encoding)) ||
5044 write_message(p, strlen(p), path, 0)) {
5045 repo_unuse_commit_buffer(r, commit, p);
5046 return error(_("could not write file: "
5047 "'%s'"), path);
5049 repo_unuse_commit_buffer(r,
5050 commit, p);
5054 strbuf_release(&rev);
5055 flags |= AMEND_MSG;
5058 if (is_clean) {
5059 if (refs_ref_exists(get_main_ref_store(r),
5060 "CHERRY_PICK_HEAD") &&
5061 refs_delete_ref(get_main_ref_store(r), "",
5062 "CHERRY_PICK_HEAD", NULL, 0))
5063 return error(_("could not remove CHERRY_PICK_HEAD"));
5064 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5065 return error_errno(_("could not remove '%s'"),
5066 git_path_merge_msg(r));
5067 if (!final_fixup)
5068 return 0;
5071 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5072 opts, flags))
5073 return error(_("could not commit staged changes."));
5074 unlink(rebase_path_amend());
5075 unlink(git_path_merge_head(r));
5076 unlink(git_path_auto_merge(r));
5077 if (final_fixup) {
5078 unlink(rebase_path_fixup_msg());
5079 unlink(rebase_path_squash_msg());
5081 if (opts->current_fixup_count > 0) {
5083 * Whether final fixup or not, we just cleaned up the commit
5084 * message...
5086 unlink(rebase_path_current_fixups());
5087 strbuf_reset(&opts->current_fixups);
5088 opts->current_fixup_count = 0;
5090 return 0;
5093 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5095 struct todo_list todo_list = TODO_LIST_INIT;
5096 int res;
5098 if (read_and_refresh_cache(r, opts))
5099 return -1;
5101 if (read_populate_opts(opts))
5102 return -1;
5103 if (is_rebase_i(opts)) {
5104 if ((res = read_populate_todo(r, &todo_list, opts)))
5105 goto release_todo_list;
5107 if (file_exists(rebase_path_dropped())) {
5108 if ((res = todo_list_check_against_backup(r, &todo_list)))
5109 goto release_todo_list;
5111 unlink(rebase_path_dropped());
5114 opts->reflog_message = reflog_message(opts, "continue", NULL);
5115 if (commit_staged_changes(r, opts, &todo_list)) {
5116 res = -1;
5117 goto release_todo_list;
5119 } else if (!file_exists(get_todo_path(opts)))
5120 return continue_single_pick(r, opts);
5121 else if ((res = read_populate_todo(r, &todo_list, opts)))
5122 goto release_todo_list;
5124 if (!is_rebase_i(opts)) {
5125 /* Verify that the conflict has been resolved */
5126 if (refs_ref_exists(get_main_ref_store(r),
5127 "CHERRY_PICK_HEAD") ||
5128 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5129 res = continue_single_pick(r, opts);
5130 if (res)
5131 goto release_todo_list;
5133 if (index_differs_from(r, "HEAD", NULL, 0)) {
5134 res = error_dirty_index(r, opts);
5135 goto release_todo_list;
5137 todo_list.current++;
5138 } else if (file_exists(rebase_path_stopped_sha())) {
5139 struct strbuf buf = STRBUF_INIT;
5140 struct object_id oid;
5142 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5143 READ_ONELINER_SKIP_IF_EMPTY) &&
5144 !get_oid_hex(buf.buf, &oid))
5145 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5146 strbuf_release(&buf);
5149 res = pick_commits(r, &todo_list, opts);
5150 release_todo_list:
5151 todo_list_release(&todo_list);
5152 return res;
5155 static int single_pick(struct repository *r,
5156 struct commit *cmit,
5157 struct replay_opts *opts)
5159 int check_todo;
5160 struct todo_item item;
5162 item.command = opts->action == REPLAY_PICK ?
5163 TODO_PICK : TODO_REVERT;
5164 item.commit = cmit;
5166 opts->reflog_message = sequencer_reflog_action(opts);
5167 return do_pick_commit(r, &item, opts, 0, &check_todo);
5170 int sequencer_pick_revisions(struct repository *r,
5171 struct replay_opts *opts)
5173 struct todo_list todo_list = TODO_LIST_INIT;
5174 struct object_id oid;
5175 int i, res;
5177 assert(opts->revs);
5178 if (read_and_refresh_cache(r, opts))
5179 return -1;
5181 for (i = 0; i < opts->revs->pending.nr; i++) {
5182 struct object_id oid;
5183 const char *name = opts->revs->pending.objects[i].name;
5185 /* This happens when using --stdin. */
5186 if (!strlen(name))
5187 continue;
5189 if (!repo_get_oid(r, name, &oid)) {
5190 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5191 enum object_type type = oid_object_info(r,
5192 &oid,
5193 NULL);
5194 return error(_("%s: can't cherry-pick a %s"),
5195 name, type_name(type));
5197 } else
5198 return error(_("%s: bad revision"), name);
5202 * If we were called as "git cherry-pick <commit>", just
5203 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5204 * REVERT_HEAD, and don't touch the sequencer state.
5205 * This means it is possible to cherry-pick in the middle
5206 * of a cherry-pick sequence.
5208 if (opts->revs->cmdline.nr == 1 &&
5209 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5210 opts->revs->no_walk &&
5211 !opts->revs->cmdline.rev->flags) {
5212 struct commit *cmit;
5213 if (prepare_revision_walk(opts->revs))
5214 return error(_("revision walk setup failed"));
5215 cmit = get_revision(opts->revs);
5216 if (!cmit)
5217 return error(_("empty commit set passed"));
5218 if (get_revision(opts->revs))
5219 BUG("unexpected extra commit from walk");
5220 return single_pick(r, cmit, opts);
5224 * Start a new cherry-pick/ revert sequence; but
5225 * first, make sure that an existing one isn't in
5226 * progress
5229 if (walk_revs_populate_todo(&todo_list, opts) ||
5230 create_seq_dir(r) < 0)
5231 return -1;
5232 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5233 return error(_("can't revert as initial commit"));
5234 if (save_head(oid_to_hex(&oid)))
5235 return -1;
5236 if (save_opts(opts))
5237 return -1;
5238 update_abort_safety_file();
5239 res = pick_commits(r, &todo_list, opts);
5240 todo_list_release(&todo_list);
5241 return res;
5244 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5246 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5247 struct strbuf sob = STRBUF_INIT;
5248 int has_footer;
5250 strbuf_addstr(&sob, sign_off_header);
5251 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5252 strbuf_addch(&sob, '\n');
5254 if (!ignore_footer)
5255 strbuf_complete_line(msgbuf);
5258 * If the whole message buffer is equal to the sob, pretend that we
5259 * found a conforming footer with a matching sob
5261 if (msgbuf->len - ignore_footer == sob.len &&
5262 !strncmp(msgbuf->buf, sob.buf, sob.len))
5263 has_footer = 3;
5264 else
5265 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5267 if (!has_footer) {
5268 const char *append_newlines = NULL;
5269 size_t len = msgbuf->len - ignore_footer;
5271 if (!len) {
5273 * The buffer is completely empty. Leave foom for
5274 * the title and body to be filled in by the user.
5276 append_newlines = "\n\n";
5277 } else if (len == 1) {
5279 * Buffer contains a single newline. Add another
5280 * so that we leave room for the title and body.
5282 append_newlines = "\n";
5283 } else if (msgbuf->buf[len - 2] != '\n') {
5285 * Buffer ends with a single newline. Add another
5286 * so that there is an empty line between the message
5287 * body and the sob.
5289 append_newlines = "\n";
5290 } /* else, the buffer already ends with two newlines. */
5292 if (append_newlines)
5293 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5294 append_newlines, strlen(append_newlines));
5297 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5298 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5299 sob.buf, sob.len);
5301 strbuf_release(&sob);
5304 struct labels_entry {
5305 struct hashmap_entry entry;
5306 char label[FLEX_ARRAY];
5309 static int labels_cmp(const void *fndata UNUSED,
5310 const struct hashmap_entry *eptr,
5311 const struct hashmap_entry *entry_or_key, const void *key)
5313 const struct labels_entry *a, *b;
5315 a = container_of(eptr, const struct labels_entry, entry);
5316 b = container_of(entry_or_key, const struct labels_entry, entry);
5318 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5321 struct string_entry {
5322 struct oidmap_entry entry;
5323 char string[FLEX_ARRAY];
5326 struct label_state {
5327 struct oidmap commit2label;
5328 struct hashmap labels;
5329 struct strbuf buf;
5332 static const char *label_oid(struct object_id *oid, const char *label,
5333 struct label_state *state)
5335 struct labels_entry *labels_entry;
5336 struct string_entry *string_entry;
5337 struct object_id dummy;
5338 int i;
5340 string_entry = oidmap_get(&state->commit2label, oid);
5341 if (string_entry)
5342 return string_entry->string;
5345 * For "uninteresting" commits, i.e. commits that are not to be
5346 * rebased, and which can therefore not be labeled, we use a unique
5347 * abbreviation of the commit name. This is slightly more complicated
5348 * than calling repo_find_unique_abbrev() because we also need to make
5349 * sure that the abbreviation does not conflict with any other
5350 * label.
5352 * We disallow "interesting" commits to be labeled by a string that
5353 * is a valid full-length hash, to ensure that we always can find an
5354 * abbreviation for any uninteresting commit's names that does not
5355 * clash with any other label.
5357 strbuf_reset(&state->buf);
5358 if (!label) {
5359 char *p;
5361 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5362 label = p = state->buf.buf;
5364 repo_find_unique_abbrev_r(the_repository, p, oid,
5365 default_abbrev);
5368 * We may need to extend the abbreviated hash so that there is
5369 * no conflicting label.
5371 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5372 size_t i = strlen(p) + 1;
5374 oid_to_hex_r(p, oid);
5375 for (; i < the_hash_algo->hexsz; i++) {
5376 char save = p[i];
5377 p[i] = '\0';
5378 if (!hashmap_get_from_hash(&state->labels,
5379 strihash(p), p))
5380 break;
5381 p[i] = save;
5384 } else {
5385 struct strbuf *buf = &state->buf;
5388 * Sanitize labels by replacing non-alpha-numeric characters
5389 * (including white-space ones) by dashes, as they might be
5390 * illegal in file names (and hence in ref names).
5392 * Note that we retain non-ASCII UTF-8 characters (identified
5393 * via the most significant bit). They should be all acceptable
5394 * in file names. We do not validate the UTF-8 here, that's not
5395 * the job of this function.
5397 for (; *label; label++)
5398 if ((*label & 0x80) || isalnum(*label))
5399 strbuf_addch(buf, *label);
5400 /* avoid leading dash and double-dashes */
5401 else if (buf->len && buf->buf[buf->len - 1] != '-')
5402 strbuf_addch(buf, '-');
5403 if (!buf->len) {
5404 strbuf_addstr(buf, "rev-");
5405 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5407 label = buf->buf;
5409 if ((buf->len == the_hash_algo->hexsz &&
5410 !get_oid_hex(label, &dummy)) ||
5411 (buf->len == 1 && *label == '#') ||
5412 hashmap_get_from_hash(&state->labels,
5413 strihash(label), label)) {
5415 * If the label already exists, or if the label is a
5416 * valid full OID, or the label is a '#' (which we use
5417 * as a separator between merge heads and oneline), we
5418 * append a dash and a number to make it unique.
5420 size_t len = buf->len;
5422 for (i = 2; ; i++) {
5423 strbuf_setlen(buf, len);
5424 strbuf_addf(buf, "-%d", i);
5425 if (!hashmap_get_from_hash(&state->labels,
5426 strihash(buf->buf),
5427 buf->buf))
5428 break;
5431 label = buf->buf;
5435 FLEX_ALLOC_STR(labels_entry, label, label);
5436 hashmap_entry_init(&labels_entry->entry, strihash(label));
5437 hashmap_add(&state->labels, &labels_entry->entry);
5439 FLEX_ALLOC_STR(string_entry, string, label);
5440 oidcpy(&string_entry->entry.oid, oid);
5441 oidmap_put(&state->commit2label, string_entry);
5443 return string_entry->string;
5446 static int make_script_with_merges(struct pretty_print_context *pp,
5447 struct rev_info *revs, struct strbuf *out,
5448 unsigned flags)
5450 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5451 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5452 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5453 int skipped_commit = 0;
5454 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5455 struct strbuf label = STRBUF_INIT;
5456 struct commit_list *commits = NULL, **tail = &commits, *iter;
5457 struct commit_list *tips = NULL, **tips_tail = &tips;
5458 struct commit *commit;
5459 struct oidmap commit2todo = OIDMAP_INIT;
5460 struct string_entry *entry;
5461 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5462 shown = OIDSET_INIT;
5463 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5465 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5466 const char *cmd_pick = abbr ? "p" : "pick",
5467 *cmd_label = abbr ? "l" : "label",
5468 *cmd_reset = abbr ? "t" : "reset",
5469 *cmd_merge = abbr ? "m" : "merge";
5471 oidmap_init(&commit2todo, 0);
5472 oidmap_init(&state.commit2label, 0);
5473 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5474 strbuf_init(&state.buf, 32);
5476 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5477 struct labels_entry *onto_label_entry;
5478 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5479 FLEX_ALLOC_STR(entry, string, "onto");
5480 oidcpy(&entry->entry.oid, oid);
5481 oidmap_put(&state.commit2label, entry);
5483 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5484 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5485 hashmap_add(&state.labels, &onto_label_entry->entry);
5489 * First phase:
5490 * - get onelines for all commits
5491 * - gather all branch tips (i.e. 2nd or later parents of merges)
5492 * - label all branch tips
5494 while ((commit = get_revision(revs))) {
5495 struct commit_list *to_merge;
5496 const char *p1, *p2;
5497 struct object_id *oid;
5498 int is_empty;
5500 tail = &commit_list_insert(commit, tail)->next;
5501 oidset_insert(&interesting, &commit->object.oid);
5503 is_empty = is_original_commit_empty(commit);
5504 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5505 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5506 warning(_("skipped previously applied commit %s"),
5507 short_commit_name(commit));
5508 skipped_commit = 1;
5509 continue;
5511 if (is_empty && !keep_empty)
5512 continue;
5514 strbuf_reset(&oneline);
5515 pretty_print_commit(pp, commit, &oneline);
5517 to_merge = commit->parents ? commit->parents->next : NULL;
5518 if (!to_merge) {
5519 /* non-merge commit: easy case */
5520 strbuf_reset(&buf);
5521 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5522 oid_to_hex(&commit->object.oid),
5523 oneline.buf);
5524 if (is_empty)
5525 strbuf_addf(&buf, " %c empty",
5526 comment_line_char);
5528 FLEX_ALLOC_STR(entry, string, buf.buf);
5529 oidcpy(&entry->entry.oid, &commit->object.oid);
5530 oidmap_put(&commit2todo, entry);
5532 continue;
5535 /* Create a label */
5536 strbuf_reset(&label);
5537 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5538 (p1 = strchr(p1, '\'')) &&
5539 (p2 = strchr(++p1, '\'')))
5540 strbuf_add(&label, p1, p2 - p1);
5541 else if (skip_prefix(oneline.buf, "Merge pull request ",
5542 &p1) &&
5543 (p1 = strstr(p1, " from ")))
5544 strbuf_addstr(&label, p1 + strlen(" from "));
5545 else
5546 strbuf_addbuf(&label, &oneline);
5548 strbuf_reset(&buf);
5549 strbuf_addf(&buf, "%s -C %s",
5550 cmd_merge, oid_to_hex(&commit->object.oid));
5552 /* label the tips of merged branches */
5553 for (; to_merge; to_merge = to_merge->next) {
5554 oid = &to_merge->item->object.oid;
5555 strbuf_addch(&buf, ' ');
5557 if (!oidset_contains(&interesting, oid)) {
5558 strbuf_addstr(&buf, label_oid(oid, NULL,
5559 &state));
5560 continue;
5563 tips_tail = &commit_list_insert(to_merge->item,
5564 tips_tail)->next;
5566 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5568 strbuf_addf(&buf, " # %s", oneline.buf);
5570 FLEX_ALLOC_STR(entry, string, buf.buf);
5571 oidcpy(&entry->entry.oid, &commit->object.oid);
5572 oidmap_put(&commit2todo, entry);
5574 if (skipped_commit)
5575 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5576 _("use --reapply-cherry-picks to include skipped commits"));
5579 * Second phase:
5580 * - label branch points
5581 * - add HEAD to the branch tips
5583 for (iter = commits; iter; iter = iter->next) {
5584 struct commit_list *parent = iter->item->parents;
5585 for (; parent; parent = parent->next) {
5586 struct object_id *oid = &parent->item->object.oid;
5587 if (!oidset_contains(&interesting, oid))
5588 continue;
5589 if (oidset_insert(&child_seen, oid))
5590 label_oid(oid, "branch-point", &state);
5593 /* Add HEAD as implicit "tip of branch" */
5594 if (!iter->next)
5595 tips_tail = &commit_list_insert(iter->item,
5596 tips_tail)->next;
5600 * Third phase: output the todo list. This is a bit tricky, as we
5601 * want to avoid jumping back and forth between revisions. To
5602 * accomplish that goal, we walk backwards from the branch tips,
5603 * gathering commits not yet shown, reversing the list on the fly,
5604 * then outputting that list (labeling revisions as needed).
5606 strbuf_addf(out, "%s onto\n", cmd_label);
5607 for (iter = tips; iter; iter = iter->next) {
5608 struct commit_list *list = NULL, *iter2;
5610 commit = iter->item;
5611 if (oidset_contains(&shown, &commit->object.oid))
5612 continue;
5613 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5615 if (entry)
5616 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5617 else
5618 strbuf_addch(out, '\n');
5620 while (oidset_contains(&interesting, &commit->object.oid) &&
5621 !oidset_contains(&shown, &commit->object.oid)) {
5622 commit_list_insert(commit, &list);
5623 if (!commit->parents) {
5624 commit = NULL;
5625 break;
5627 commit = commit->parents->item;
5630 if (!commit)
5631 strbuf_addf(out, "%s %s\n", cmd_reset,
5632 rebase_cousins || root_with_onto ?
5633 "onto" : "[new root]");
5634 else {
5635 const char *to = NULL;
5637 entry = oidmap_get(&state.commit2label,
5638 &commit->object.oid);
5639 if (entry)
5640 to = entry->string;
5641 else if (!rebase_cousins)
5642 to = label_oid(&commit->object.oid, NULL,
5643 &state);
5645 if (!to || !strcmp(to, "onto"))
5646 strbuf_addf(out, "%s onto\n", cmd_reset);
5647 else {
5648 strbuf_reset(&oneline);
5649 pretty_print_commit(pp, commit, &oneline);
5650 strbuf_addf(out, "%s %s # %s\n",
5651 cmd_reset, to, oneline.buf);
5655 for (iter2 = list; iter2; iter2 = iter2->next) {
5656 struct object_id *oid = &iter2->item->object.oid;
5657 entry = oidmap_get(&commit2todo, oid);
5658 /* only show if not already upstream */
5659 if (entry)
5660 strbuf_addf(out, "%s\n", entry->string);
5661 entry = oidmap_get(&state.commit2label, oid);
5662 if (entry)
5663 strbuf_addf(out, "%s %s\n",
5664 cmd_label, entry->string);
5665 oidset_insert(&shown, oid);
5668 free_commit_list(list);
5671 free_commit_list(commits);
5672 free_commit_list(tips);
5674 strbuf_release(&label);
5675 strbuf_release(&oneline);
5676 strbuf_release(&buf);
5678 oidmap_free(&commit2todo, 1);
5679 oidmap_free(&state.commit2label, 1);
5680 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5681 strbuf_release(&state.buf);
5683 return 0;
5686 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5687 const char **argv, unsigned flags)
5689 char *format = NULL;
5690 struct pretty_print_context pp = {0};
5691 struct rev_info revs;
5692 struct commit *commit;
5693 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5694 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5695 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5696 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5697 int skipped_commit = 0;
5698 int ret = 0;
5700 repo_init_revisions(r, &revs, NULL);
5701 revs.verbose_header = 1;
5702 if (!rebase_merges)
5703 revs.max_parents = 1;
5704 revs.cherry_mark = !reapply_cherry_picks;
5705 revs.limited = 1;
5706 revs.reverse = 1;
5707 revs.right_only = 1;
5708 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5709 revs.topo_order = 1;
5711 revs.pretty_given = 1;
5712 git_config_get_string("rebase.instructionFormat", &format);
5713 if (!format || !*format) {
5714 free(format);
5715 format = xstrdup("%s");
5717 get_commit_format(format, &revs);
5718 free(format);
5719 pp.fmt = revs.commit_format;
5720 pp.output_encoding = get_log_output_encoding();
5722 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5723 ret = error(_("make_script: unhandled options"));
5724 goto cleanup;
5727 if (prepare_revision_walk(&revs) < 0) {
5728 ret = error(_("make_script: error preparing revisions"));
5729 goto cleanup;
5732 if (rebase_merges) {
5733 ret = make_script_with_merges(&pp, &revs, out, flags);
5734 goto cleanup;
5737 while ((commit = get_revision(&revs))) {
5738 int is_empty = is_original_commit_empty(commit);
5740 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5741 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5742 warning(_("skipped previously applied commit %s"),
5743 short_commit_name(commit));
5744 skipped_commit = 1;
5745 continue;
5747 if (is_empty && !keep_empty)
5748 continue;
5749 strbuf_addf(out, "%s %s ", insn,
5750 oid_to_hex(&commit->object.oid));
5751 pretty_print_commit(&pp, commit, out);
5752 if (is_empty)
5753 strbuf_addf(out, " %c empty", comment_line_char);
5754 strbuf_addch(out, '\n');
5756 if (skipped_commit)
5757 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5758 _("use --reapply-cherry-picks to include skipped commits"));
5759 cleanup:
5760 release_revisions(&revs);
5761 return ret;
5765 * Add commands after pick and (series of) squash/fixup commands
5766 * in the todo list.
5768 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5769 struct string_list *commands)
5771 struct strbuf *buf = &todo_list->buf;
5772 size_t base_offset = buf->len;
5773 int i, insert, nr = 0, alloc = 0;
5774 struct todo_item *items = NULL, *base_items = NULL;
5776 CALLOC_ARRAY(base_items, commands->nr);
5777 for (i = 0; i < commands->nr; i++) {
5778 size_t command_len = strlen(commands->items[i].string);
5780 strbuf_addstr(buf, commands->items[i].string);
5781 strbuf_addch(buf, '\n');
5783 base_items[i].command = TODO_EXEC;
5784 base_items[i].offset_in_buf = base_offset;
5785 base_items[i].arg_offset = base_offset;
5786 base_items[i].arg_len = command_len;
5788 base_offset += command_len + 1;
5792 * Insert <commands> after every pick. Here, fixup/squash chains
5793 * are considered part of the pick, so we insert the commands *after*
5794 * those chains if there are any.
5796 * As we insert the exec commands immediately after rearranging
5797 * any fixups and before the user edits the list, a fixup chain
5798 * can never contain comments (any comments are empty picks that
5799 * have been commented out because the user did not specify
5800 * --keep-empty). So, it is safe to insert an exec command
5801 * without looking at the command following a comment.
5803 insert = 0;
5804 for (i = 0; i < todo_list->nr; i++) {
5805 enum todo_command command = todo_list->items[i].command;
5806 if (insert && !is_fixup(command)) {
5807 ALLOC_GROW(items, nr + commands->nr, alloc);
5808 COPY_ARRAY(items + nr, base_items, commands->nr);
5809 nr += commands->nr;
5811 insert = 0;
5814 ALLOC_GROW(items, nr + 1, alloc);
5815 items[nr++] = todo_list->items[i];
5817 if (command == TODO_PICK || command == TODO_MERGE)
5818 insert = 1;
5821 /* insert or append final <commands> */
5822 if (insert) {
5823 ALLOC_GROW(items, nr + commands->nr, alloc);
5824 COPY_ARRAY(items + nr, base_items, commands->nr);
5825 nr += commands->nr;
5828 free(base_items);
5829 FREE_AND_NULL(todo_list->items);
5830 todo_list->items = items;
5831 todo_list->nr = nr;
5832 todo_list->alloc = alloc;
5835 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5836 struct strbuf *buf, int num, unsigned flags)
5838 struct todo_item *item;
5839 int i, max = todo_list->nr;
5841 if (num > 0 && num < max)
5842 max = num;
5844 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5845 char cmd;
5847 /* if the item is not a command write it and continue */
5848 if (item->command >= TODO_COMMENT) {
5849 strbuf_addf(buf, "%.*s\n", item->arg_len,
5850 todo_item_get_arg(todo_list, item));
5851 continue;
5854 /* add command to the buffer */
5855 cmd = command_to_char(item->command);
5856 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5857 strbuf_addch(buf, cmd);
5858 else
5859 strbuf_addstr(buf, command_to_string(item->command));
5861 /* add commit id */
5862 if (item->commit) {
5863 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5864 short_commit_name(item->commit) :
5865 oid_to_hex(&item->commit->object.oid);
5867 if (item->command == TODO_FIXUP) {
5868 if (item->flags & TODO_EDIT_FIXUP_MSG)
5869 strbuf_addstr(buf, " -c");
5870 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5871 strbuf_addstr(buf, " -C");
5875 if (item->command == TODO_MERGE) {
5876 if (item->flags & TODO_EDIT_MERGE_MSG)
5877 strbuf_addstr(buf, " -c");
5878 else
5879 strbuf_addstr(buf, " -C");
5882 strbuf_addf(buf, " %s", oid);
5885 /* add all the rest */
5886 if (!item->arg_len)
5887 strbuf_addch(buf, '\n');
5888 else
5889 strbuf_addf(buf, " %.*s\n", item->arg_len,
5890 todo_item_get_arg(todo_list, item));
5894 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5895 const char *file, const char *shortrevisions,
5896 const char *shortonto, int num, unsigned flags)
5898 int res;
5899 struct strbuf buf = STRBUF_INIT;
5901 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5902 if (flags & TODO_LIST_APPEND_TODO_HELP)
5903 append_todo_help(count_commands(todo_list),
5904 shortrevisions, shortonto, &buf);
5906 res = write_message(buf.buf, buf.len, file, 0);
5907 strbuf_release(&buf);
5909 return res;
5912 /* skip picking commits whose parents are unchanged */
5913 static int skip_unnecessary_picks(struct repository *r,
5914 struct todo_list *todo_list,
5915 struct object_id *base_oid)
5917 struct object_id *parent_oid;
5918 int i;
5920 for (i = 0; i < todo_list->nr; i++) {
5921 struct todo_item *item = todo_list->items + i;
5923 if (item->command >= TODO_NOOP)
5924 continue;
5925 if (item->command != TODO_PICK)
5926 break;
5927 if (repo_parse_commit(r, item->commit)) {
5928 return error(_("could not parse commit '%s'"),
5929 oid_to_hex(&item->commit->object.oid));
5931 if (!item->commit->parents)
5932 break; /* root commit */
5933 if (item->commit->parents->next)
5934 break; /* merge commit */
5935 parent_oid = &item->commit->parents->item->object.oid;
5936 if (!oideq(parent_oid, base_oid))
5937 break;
5938 oidcpy(base_oid, &item->commit->object.oid);
5940 if (i > 0) {
5941 const char *done_path = rebase_path_done();
5943 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5944 error_errno(_("could not write to '%s'"), done_path);
5945 return -1;
5948 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5949 todo_list->nr -= i;
5950 todo_list->current = 0;
5951 todo_list->done_nr += i;
5953 if (is_fixup(peek_command(todo_list, 0)))
5954 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5957 return 0;
5960 struct todo_add_branch_context {
5961 struct todo_item *items;
5962 size_t items_nr;
5963 size_t items_alloc;
5964 struct strbuf *buf;
5965 struct commit *commit;
5966 struct string_list refs_to_oids;
5969 static int add_decorations_to_list(const struct commit *commit,
5970 struct todo_add_branch_context *ctx)
5972 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5973 const char *head_ref = resolve_ref_unsafe("HEAD",
5974 RESOLVE_REF_READING,
5975 NULL,
5976 NULL);
5978 while (decoration) {
5979 struct todo_item *item;
5980 const char *path;
5981 size_t base_offset = ctx->buf->len;
5984 * If the branch is the current HEAD, then it will be
5985 * updated by the default rebase behavior.
5987 if (head_ref && !strcmp(head_ref, decoration->name)) {
5988 decoration = decoration->next;
5989 continue;
5992 ALLOC_GROW(ctx->items,
5993 ctx->items_nr + 1,
5994 ctx->items_alloc);
5995 item = &ctx->items[ctx->items_nr];
5996 memset(item, 0, sizeof(*item));
5998 /* If the branch is checked out, then leave a comment instead. */
5999 if ((path = branch_checked_out(decoration->name))) {
6000 item->command = TODO_COMMENT;
6001 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6002 decoration->name, path);
6003 } else {
6004 struct string_list_item *sti;
6005 item->command = TODO_UPDATE_REF;
6006 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6008 sti = string_list_insert(&ctx->refs_to_oids,
6009 decoration->name);
6010 sti->util = init_update_ref_record(decoration->name);
6013 item->offset_in_buf = base_offset;
6014 item->arg_offset = base_offset;
6015 item->arg_len = ctx->buf->len - base_offset;
6016 ctx->items_nr++;
6018 decoration = decoration->next;
6021 return 0;
6025 * For each 'pick' command, find out if the commit has a decoration in
6026 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6028 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6030 int i, res;
6031 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6032 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6033 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6034 struct decoration_filter decoration_filter = {
6035 .include_ref_pattern = &decorate_refs_include,
6036 .exclude_ref_pattern = &decorate_refs_exclude,
6037 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6039 struct todo_add_branch_context ctx = {
6040 .buf = &todo_list->buf,
6041 .refs_to_oids = STRING_LIST_INIT_DUP,
6044 ctx.items_alloc = 2 * todo_list->nr + 1;
6045 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6047 string_list_append(&decorate_refs_include, "refs/heads/");
6048 load_ref_decorations(&decoration_filter, 0);
6050 for (i = 0; i < todo_list->nr; ) {
6051 struct todo_item *item = &todo_list->items[i];
6053 /* insert ith item into new list */
6054 ALLOC_GROW(ctx.items,
6055 ctx.items_nr + 1,
6056 ctx.items_alloc);
6058 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6060 if (item->commit) {
6061 ctx.commit = item->commit;
6062 add_decorations_to_list(item->commit, &ctx);
6066 res = write_update_refs_state(&ctx.refs_to_oids);
6068 string_list_clear(&ctx.refs_to_oids, 1);
6070 if (res) {
6071 /* we failed, so clean up the new list. */
6072 free(ctx.items);
6073 return res;
6076 free(todo_list->items);
6077 todo_list->items = ctx.items;
6078 todo_list->nr = ctx.items_nr;
6079 todo_list->alloc = ctx.items_alloc;
6081 return 0;
6084 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6085 const char *shortrevisions, const char *onto_name,
6086 struct commit *onto, const struct object_id *orig_head,
6087 struct string_list *commands, unsigned autosquash,
6088 unsigned update_refs,
6089 struct todo_list *todo_list)
6091 char shortonto[GIT_MAX_HEXSZ + 1];
6092 const char *todo_file = rebase_path_todo();
6093 struct todo_list new_todo = TODO_LIST_INIT;
6094 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6095 struct object_id oid = onto->object.oid;
6096 int res;
6098 repo_find_unique_abbrev_r(r, shortonto, &oid,
6099 DEFAULT_ABBREV);
6101 if (buf->len == 0) {
6102 struct todo_item *item = append_new_todo(todo_list);
6103 item->command = TODO_NOOP;
6104 item->commit = NULL;
6105 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6108 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6109 return -1;
6111 if (autosquash && todo_list_rearrange_squash(todo_list))
6112 return -1;
6114 if (commands->nr)
6115 todo_list_add_exec_commands(todo_list, commands);
6117 if (count_commands(todo_list) == 0) {
6118 apply_autostash(rebase_path_autostash());
6119 sequencer_remove_state(opts);
6121 return error(_("nothing to do"));
6124 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6125 shortonto, flags);
6126 if (res == -1)
6127 return -1;
6128 else if (res == -2) {
6129 apply_autostash(rebase_path_autostash());
6130 sequencer_remove_state(opts);
6132 return -1;
6133 } else if (res == -3) {
6134 apply_autostash(rebase_path_autostash());
6135 sequencer_remove_state(opts);
6136 todo_list_release(&new_todo);
6138 return error(_("nothing to do"));
6139 } else if (res == -4) {
6140 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6141 todo_list_release(&new_todo);
6143 return -1;
6146 /* Expand the commit IDs */
6147 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6148 strbuf_swap(&new_todo.buf, &buf2);
6149 strbuf_release(&buf2);
6150 new_todo.total_nr -= new_todo.nr;
6151 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6152 BUG("invalid todo list after expanding IDs:\n%s",
6153 new_todo.buf.buf);
6155 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6156 todo_list_release(&new_todo);
6157 return error(_("could not skip unnecessary pick commands"));
6160 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6161 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6162 todo_list_release(&new_todo);
6163 return error_errno(_("could not write '%s'"), todo_file);
6166 res = -1;
6168 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6169 goto cleanup;
6171 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6172 goto cleanup;
6174 todo_list_write_total_nr(&new_todo);
6175 res = pick_commits(r, &new_todo, opts);
6177 cleanup:
6178 todo_list_release(&new_todo);
6180 return res;
6183 struct subject2item_entry {
6184 struct hashmap_entry entry;
6185 int i;
6186 char subject[FLEX_ARRAY];
6189 static int subject2item_cmp(const void *fndata UNUSED,
6190 const struct hashmap_entry *eptr,
6191 const struct hashmap_entry *entry_or_key,
6192 const void *key)
6194 const struct subject2item_entry *a, *b;
6196 a = container_of(eptr, const struct subject2item_entry, entry);
6197 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6199 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6202 define_commit_slab(commit_todo_item, struct todo_item *);
6204 static int skip_fixupish(const char *subject, const char **p) {
6205 return skip_prefix(subject, "fixup! ", p) ||
6206 skip_prefix(subject, "amend! ", p) ||
6207 skip_prefix(subject, "squash! ", p);
6211 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6212 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6213 * after the former, and change "pick" to "fixup"/"squash".
6215 * Note that if the config has specified a custom instruction format, each log
6216 * message will have to be retrieved from the commit (as the oneline in the
6217 * script cannot be trusted) in order to normalize the autosquash arrangement.
6219 int todo_list_rearrange_squash(struct todo_list *todo_list)
6221 struct hashmap subject2item;
6222 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6223 char **subjects;
6224 struct commit_todo_item commit_todo;
6225 struct todo_item *items = NULL;
6227 init_commit_todo_item(&commit_todo);
6229 * The hashmap maps onelines to the respective todo list index.
6231 * If any items need to be rearranged, the next[i] value will indicate
6232 * which item was moved directly after the i'th.
6234 * In that case, last[i] will indicate the index of the latest item to
6235 * be moved to appear after the i'th.
6237 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6238 ALLOC_ARRAY(next, todo_list->nr);
6239 ALLOC_ARRAY(tail, todo_list->nr);
6240 ALLOC_ARRAY(subjects, todo_list->nr);
6241 for (i = 0; i < todo_list->nr; i++) {
6242 struct strbuf buf = STRBUF_INIT;
6243 struct todo_item *item = todo_list->items + i;
6244 const char *commit_buffer, *subject, *p;
6245 size_t subject_len;
6246 int i2 = -1;
6247 struct subject2item_entry *entry;
6249 next[i] = tail[i] = -1;
6250 if (!item->commit || item->command == TODO_DROP) {
6251 subjects[i] = NULL;
6252 continue;
6255 if (is_fixup(item->command)) {
6256 clear_commit_todo_item(&commit_todo);
6257 return error(_("the script was already rearranged."));
6260 repo_parse_commit(the_repository, item->commit);
6261 commit_buffer = repo_logmsg_reencode(the_repository,
6262 item->commit, NULL,
6263 "UTF-8");
6264 find_commit_subject(commit_buffer, &subject);
6265 format_subject(&buf, subject, " ");
6266 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6267 repo_unuse_commit_buffer(the_repository, item->commit,
6268 commit_buffer);
6269 if (skip_fixupish(subject, &p)) {
6270 struct commit *commit2;
6272 for (;;) {
6273 while (isspace(*p))
6274 p++;
6275 if (!skip_fixupish(p, &p))
6276 break;
6279 entry = hashmap_get_entry_from_hash(&subject2item,
6280 strhash(p), p,
6281 struct subject2item_entry,
6282 entry);
6283 if (entry)
6284 /* found by title */
6285 i2 = entry->i;
6286 else if (!strchr(p, ' ') &&
6287 (commit2 =
6288 lookup_commit_reference_by_name(p)) &&
6289 *commit_todo_item_at(&commit_todo, commit2))
6290 /* found by commit name */
6291 i2 = *commit_todo_item_at(&commit_todo, commit2)
6292 - todo_list->items;
6293 else {
6294 /* copy can be a prefix of the commit subject */
6295 for (i2 = 0; i2 < i; i2++)
6296 if (subjects[i2] &&
6297 starts_with(subjects[i2], p))
6298 break;
6299 if (i2 == i)
6300 i2 = -1;
6303 if (i2 >= 0) {
6304 rearranged = 1;
6305 if (starts_with(subject, "fixup!")) {
6306 todo_list->items[i].command = TODO_FIXUP;
6307 } else if (starts_with(subject, "amend!")) {
6308 todo_list->items[i].command = TODO_FIXUP;
6309 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6310 } else {
6311 todo_list->items[i].command = TODO_SQUASH;
6313 if (tail[i2] < 0) {
6314 next[i] = next[i2];
6315 next[i2] = i;
6316 } else {
6317 next[i] = next[tail[i2]];
6318 next[tail[i2]] = i;
6320 tail[i2] = i;
6321 } else if (!hashmap_get_from_hash(&subject2item,
6322 strhash(subject), subject)) {
6323 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6324 entry->i = i;
6325 hashmap_entry_init(&entry->entry,
6326 strhash(entry->subject));
6327 hashmap_put(&subject2item, &entry->entry);
6330 *commit_todo_item_at(&commit_todo, item->commit) = item;
6333 if (rearranged) {
6334 for (i = 0; i < todo_list->nr; i++) {
6335 enum todo_command command = todo_list->items[i].command;
6336 int cur = i;
6339 * Initially, all commands are 'pick's. If it is a
6340 * fixup or a squash now, we have rearranged it.
6342 if (is_fixup(command))
6343 continue;
6345 while (cur >= 0) {
6346 ALLOC_GROW(items, nr + 1, alloc);
6347 items[nr++] = todo_list->items[cur];
6348 cur = next[cur];
6352 FREE_AND_NULL(todo_list->items);
6353 todo_list->items = items;
6354 todo_list->nr = nr;
6355 todo_list->alloc = alloc;
6358 free(next);
6359 free(tail);
6360 for (i = 0; i < todo_list->nr; i++)
6361 free(subjects[i]);
6362 free(subjects);
6363 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6365 clear_commit_todo_item(&commit_todo);
6367 return 0;
6370 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6372 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6373 struct object_id cherry_pick_head, rebase_head;
6375 if (file_exists(git_path_seq_dir()))
6376 *whence = FROM_CHERRY_PICK_MULTI;
6377 if (file_exists(rebase_path()) &&
6378 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6379 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6380 oideq(&rebase_head, &cherry_pick_head))
6381 *whence = FROM_REBASE_PICK;
6382 else
6383 *whence = FROM_CHERRY_PICK_SINGLE;
6385 return 1;
6388 return 0;
6391 int sequencer_get_update_refs_state(const char *wt_dir,
6392 struct string_list *refs)
6394 int result = 0;
6395 FILE *fp = NULL;
6396 struct strbuf ref = STRBUF_INIT;
6397 struct strbuf hash = STRBUF_INIT;
6398 struct update_ref_record *rec = NULL;
6400 char *path = rebase_path_update_refs(wt_dir);
6402 fp = fopen(path, "r");
6403 if (!fp)
6404 goto cleanup;
6406 while (strbuf_getline(&ref, fp) != EOF) {
6407 struct string_list_item *item;
6409 CALLOC_ARRAY(rec, 1);
6411 if (strbuf_getline(&hash, fp) == EOF ||
6412 get_oid_hex(hash.buf, &rec->before)) {
6413 warning(_("update-refs file at '%s' is invalid"),
6414 path);
6415 result = -1;
6416 goto cleanup;
6419 if (strbuf_getline(&hash, fp) == EOF ||
6420 get_oid_hex(hash.buf, &rec->after)) {
6421 warning(_("update-refs file at '%s' is invalid"),
6422 path);
6423 result = -1;
6424 goto cleanup;
6427 item = string_list_insert(refs, ref.buf);
6428 item->util = rec;
6429 rec = NULL;
6432 cleanup:
6433 if (fp)
6434 fclose(fp);
6435 free(path);
6436 free(rec);
6437 strbuf_release(&ref);
6438 strbuf_release(&hash);
6439 return result;