replace-object.h: move read_replace_refs declaration from cache.h to here
[git.git] / sequencer.c
blobaf1e07fe765b83db556807c0dbf516af23745b43
1 #include "cache.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "hex.h"
5 #include "lockfile.h"
6 #include "dir.h"
7 #include "object-store.h"
8 #include "object.h"
9 #include "commit.h"
10 #include "sequencer.h"
11 #include "tag.h"
12 #include "run-command.h"
13 #include "hook.h"
14 #include "exec-cmd.h"
15 #include "utf8.h"
16 #include "cache-tree.h"
17 #include "diff.h"
18 #include "revision.h"
19 #include "rerere.h"
20 #include "merge-ort.h"
21 #include "merge-ort-wrappers.h"
22 #include "refs.h"
23 #include "strvec.h"
24 #include "quote.h"
25 #include "trailer.h"
26 #include "log-tree.h"
27 #include "wt-status.h"
28 #include "hashmap.h"
29 #include "notes-utils.h"
30 #include "sigchain.h"
31 #include "unpack-trees.h"
32 #include "worktree.h"
33 #include "oidmap.h"
34 #include "oidset.h"
35 #include "commit-slab.h"
36 #include "alias.h"
37 #include "commit-reach.h"
38 #include "rebase-interactive.h"
39 #include "reset.h"
40 #include "branch.h"
42 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
44 static const char sign_off_header[] = "Signed-off-by: ";
45 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
47 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
49 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
51 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
52 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
53 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
54 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
56 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
58 * The file containing rebase commands, comments, and empty lines.
59 * This file is created by "git rebase -i" then edited by the user. As
60 * the lines are processed, they are removed from the front of this
61 * file and written to the tail of 'done'.
63 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
64 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
66 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
69 * The rebase command lines that have already been processed. A line
70 * is moved here when it is first handled, before any associated user
71 * actions.
73 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
75 * The file to keep track of how many commands were already processed (e.g.
76 * for the prompt).
78 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
80 * The file to keep track of how many commands are to be processed in total
81 * (e.g. for the prompt).
83 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
85 * The commit message that is planned to be used for any changes that
86 * need to be committed following a user interaction.
88 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
90 * The file into which is accumulated the suggested commit message for
91 * squash/fixup commands. When the first of a series of squash/fixups
92 * is seen, the file is created and the commit message from the
93 * previous commit and from the first squash/fixup commit are written
94 * to it. The commit message for each subsequent squash/fixup commit
95 * is appended to the file as it is processed.
97 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
99 * If the current series of squash/fixups has not yet included a squash
100 * command, then this file exists and holds the commit message of the
101 * original "pick" commit. (If the series ends without a "squash"
102 * command, then this can be used as the commit message of the combined
103 * commit without opening the editor.)
105 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
107 * This file contains the list fixup/squash commands that have been
108 * accumulated into message-fixup or message-squash so far.
110 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
112 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
113 * GIT_AUTHOR_DATE that will be used for the commit that is currently
114 * being rebased.
116 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
118 * When an "edit" rebase command is being processed, the SHA1 of the
119 * commit to be edited is recorded in this file. When "git rebase
120 * --continue" is executed, if there are any staged changes then they
121 * will be amended to the HEAD commit, but only provided the HEAD
122 * commit is still the commit to be edited. When any other rebase
123 * command is processed, this file is deleted.
125 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
127 * When we stop at a given patch via the "edit" command, this file contains
128 * the commit object name of the corresponding patch.
130 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
132 * For the post-rewrite hook, we make a list of rewritten commits and
133 * their new sha1s. The rewritten-pending list keeps the sha1s of
134 * commits that have been processed, but not committed yet,
135 * e.g. because they are waiting for a 'squash' command.
137 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
138 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
139 "rebase-merge/rewritten-pending")
142 * The path of the file containing the OID of the "squash onto" commit, i.e.
143 * the dummy commit used for `reset [new root]`.
145 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
148 * The path of the file listing refs that need to be deleted after the rebase
149 * finishes. This is used by the `label` command to record the need for cleanup.
151 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
154 * The update-refs file stores a list of refs that will be updated at the end
155 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
156 * update the OIDs for the refs in this file, but the refs are not updated
157 * until the end of the rebase sequence.
159 * rebase_path_update_refs() returns the path to this file for a given
160 * worktree directory. For the current worktree, pass the_repository->gitdir.
162 static char *rebase_path_update_refs(const char *wt_git_dir)
164 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
168 * The following files are written by git-rebase just after parsing the
169 * command-line.
171 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
172 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
173 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
174 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
175 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
176 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
177 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
178 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
179 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
180 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
181 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
182 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
183 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
184 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
185 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
186 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
187 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
190 * A 'struct update_refs_record' represents a value in the update-refs
191 * list. We use a string_list to map refs to these (before, after) pairs.
193 struct update_ref_record {
194 struct object_id before;
195 struct object_id after;
198 static struct update_ref_record *init_update_ref_record(const char *ref)
200 struct update_ref_record *rec;
202 CALLOC_ARRAY(rec, 1);
204 oidcpy(&rec->before, null_oid());
205 oidcpy(&rec->after, null_oid());
207 /* This may fail, but that's fine, we will keep the null OID. */
208 read_ref(ref, &rec->before);
210 return rec;
213 static int git_sequencer_config(const char *k, const char *v, void *cb)
215 struct replay_opts *opts = cb;
216 int status;
218 if (!strcmp(k, "commit.cleanup")) {
219 const char *s;
221 status = git_config_string(&s, k, v);
222 if (status)
223 return status;
225 if (!strcmp(s, "verbatim")) {
226 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
227 opts->explicit_cleanup = 1;
228 } else if (!strcmp(s, "whitespace")) {
229 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
230 opts->explicit_cleanup = 1;
231 } else if (!strcmp(s, "strip")) {
232 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
233 opts->explicit_cleanup = 1;
234 } else if (!strcmp(s, "scissors")) {
235 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
236 opts->explicit_cleanup = 1;
237 } else {
238 warning(_("invalid commit message cleanup mode '%s'"),
242 free((char *)s);
243 return status;
246 if (!strcmp(k, "commit.gpgsign")) {
247 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
248 return 0;
251 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
252 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
253 if (ret == 0) {
255 * pull.twohead is allowed to be multi-valued; we only
256 * care about the first value.
258 char *tmp = strchr(opts->default_strategy, ' ');
259 if (tmp)
260 *tmp = '\0';
262 return ret;
265 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
266 opts->commit_use_reference = git_config_bool(k, v);
268 status = git_gpg_config(k, v, NULL);
269 if (status)
270 return status;
272 return git_diff_basic_config(k, v, NULL);
275 void sequencer_init_config(struct replay_opts *opts)
277 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
278 git_config(git_sequencer_config, opts);
281 static inline int is_rebase_i(const struct replay_opts *opts)
283 return opts->action == REPLAY_INTERACTIVE_REBASE;
286 static const char *get_dir(const struct replay_opts *opts)
288 if (is_rebase_i(opts))
289 return rebase_path();
290 return git_path_seq_dir();
293 static const char *get_todo_path(const struct replay_opts *opts)
295 if (is_rebase_i(opts))
296 return rebase_path_todo();
297 return git_path_todo_file();
301 * Returns 0 for non-conforming footer
302 * Returns 1 for conforming footer
303 * Returns 2 when sob exists within conforming footer
304 * Returns 3 when sob exists within conforming footer as last entry
306 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
307 size_t ignore_footer)
309 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
310 struct trailer_info info;
311 size_t i;
312 int found_sob = 0, found_sob_last = 0;
313 char saved_char;
315 opts.no_divider = 1;
317 if (ignore_footer) {
318 saved_char = sb->buf[sb->len - ignore_footer];
319 sb->buf[sb->len - ignore_footer] = '\0';
322 trailer_info_get(&info, sb->buf, &opts);
324 if (ignore_footer)
325 sb->buf[sb->len - ignore_footer] = saved_char;
327 if (info.trailer_start == info.trailer_end)
328 return 0;
330 for (i = 0; i < info.trailer_nr; i++)
331 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
332 found_sob = 1;
333 if (i == info.trailer_nr - 1)
334 found_sob_last = 1;
337 trailer_info_release(&info);
339 if (found_sob_last)
340 return 3;
341 if (found_sob)
342 return 2;
343 return 1;
346 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
348 static struct strbuf buf = STRBUF_INIT;
350 strbuf_reset(&buf);
351 if (opts->gpg_sign)
352 sq_quotef(&buf, "-S%s", opts->gpg_sign);
353 return buf.buf;
356 void replay_opts_release(struct replay_opts *opts)
358 free(opts->gpg_sign);
359 free(opts->reflog_action);
360 free(opts->default_strategy);
361 free(opts->strategy);
362 for (size_t i = 0; i < opts->xopts_nr; i++)
363 free(opts->xopts[i]);
364 free(opts->xopts);
365 strbuf_release(&opts->current_fixups);
366 if (opts->revs)
367 release_revisions(opts->revs);
368 free(opts->revs);
371 int sequencer_remove_state(struct replay_opts *opts)
373 struct strbuf buf = STRBUF_INIT;
374 int ret = 0;
376 if (is_rebase_i(opts) &&
377 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
378 char *p = buf.buf;
379 while (*p) {
380 char *eol = strchr(p, '\n');
381 if (eol)
382 *eol = '\0';
383 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
384 warning(_("could not delete '%s'"), p);
385 ret = -1;
387 if (!eol)
388 break;
389 p = eol + 1;
393 strbuf_reset(&buf);
394 strbuf_addstr(&buf, get_dir(opts));
395 if (remove_dir_recursively(&buf, 0))
396 ret = error(_("could not remove '%s'"), buf.buf);
397 strbuf_release(&buf);
399 return ret;
402 static const char *action_name(const struct replay_opts *opts)
404 switch (opts->action) {
405 case REPLAY_REVERT:
406 return N_("revert");
407 case REPLAY_PICK:
408 return N_("cherry-pick");
409 case REPLAY_INTERACTIVE_REBASE:
410 return N_("rebase");
412 die(_("unknown action: %d"), opts->action);
415 struct commit_message {
416 char *parent_label;
417 char *label;
418 char *subject;
419 const char *message;
422 static const char *short_commit_name(struct commit *commit)
424 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
427 static int get_message(struct commit *commit, struct commit_message *out)
429 const char *abbrev, *subject;
430 int subject_len;
432 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
433 abbrev = short_commit_name(commit);
435 subject_len = find_commit_subject(out->message, &subject);
437 out->subject = xmemdupz(subject, subject_len);
438 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
439 out->parent_label = xstrfmt("parent of %s", out->label);
441 return 0;
444 static void free_message(struct commit *commit, struct commit_message *msg)
446 free(msg->parent_label);
447 free(msg->label);
448 free(msg->subject);
449 unuse_commit_buffer(commit, msg->message);
452 static void print_advice(struct repository *r, int show_hint,
453 struct replay_opts *opts)
455 char *msg = getenv("GIT_CHERRY_PICK_HELP");
457 if (msg) {
458 advise("%s\n", msg);
460 * A conflict has occurred but the porcelain
461 * (typically rebase --interactive) wants to take care
462 * of the commit itself so remove CHERRY_PICK_HEAD
464 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
465 NULL, 0);
466 return;
469 if (show_hint) {
470 if (opts->no_commit)
471 advise(_("after resolving the conflicts, mark the corrected paths\n"
472 "with 'git add <paths>' or 'git rm <paths>'"));
473 else if (opts->action == REPLAY_PICK)
474 advise(_("After resolving the conflicts, mark them with\n"
475 "\"git add/rm <pathspec>\", then run\n"
476 "\"git cherry-pick --continue\".\n"
477 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
478 "To abort and get back to the state before \"git cherry-pick\",\n"
479 "run \"git cherry-pick --abort\"."));
480 else if (opts->action == REPLAY_REVERT)
481 advise(_("After resolving the conflicts, mark them with\n"
482 "\"git add/rm <pathspec>\", then run\n"
483 "\"git revert --continue\".\n"
484 "You can instead skip this commit with \"git revert --skip\".\n"
485 "To abort and get back to the state before \"git revert\",\n"
486 "run \"git revert --abort\"."));
487 else
488 BUG("unexpected pick action in print_advice()");
492 static int write_message(const void *buf, size_t len, const char *filename,
493 int append_eol)
495 struct lock_file msg_file = LOCK_INIT;
497 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
498 if (msg_fd < 0)
499 return error_errno(_("could not lock '%s'"), filename);
500 if (write_in_full(msg_fd, buf, len) < 0) {
501 error_errno(_("could not write to '%s'"), filename);
502 rollback_lock_file(&msg_file);
503 return -1;
505 if (append_eol && write(msg_fd, "\n", 1) < 0) {
506 error_errno(_("could not write eol to '%s'"), filename);
507 rollback_lock_file(&msg_file);
508 return -1;
510 if (commit_lock_file(&msg_file) < 0)
511 return error(_("failed to finalize '%s'"), filename);
513 return 0;
516 int read_oneliner(struct strbuf *buf,
517 const char *path, unsigned flags)
519 int orig_len = buf->len;
521 if (strbuf_read_file(buf, path, 0) < 0) {
522 if ((flags & READ_ONELINER_WARN_MISSING) ||
523 (errno != ENOENT && errno != ENOTDIR))
524 warning_errno(_("could not read '%s'"), path);
525 return 0;
528 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
529 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
530 --buf->len;
531 buf->buf[buf->len] = '\0';
534 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
535 return 0;
537 return 1;
540 static struct tree *empty_tree(struct repository *r)
542 return lookup_tree(r, the_hash_algo->empty_tree);
545 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
547 if (repo_read_index_unmerged(repo))
548 return error_resolve_conflict(action_name(opts));
550 error(_("your local changes would be overwritten by %s."),
551 _(action_name(opts)));
553 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
554 advise(_("commit your changes or stash them to proceed."));
555 return -1;
558 static void update_abort_safety_file(void)
560 struct object_id head;
562 /* Do nothing on a single-pick */
563 if (!file_exists(git_path_seq_dir()))
564 return;
566 if (!get_oid("HEAD", &head))
567 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
568 else
569 write_file(git_path_abort_safety_file(), "%s", "");
572 static int fast_forward_to(struct repository *r,
573 const struct object_id *to,
574 const struct object_id *from,
575 int unborn,
576 struct replay_opts *opts)
578 struct ref_transaction *transaction;
579 struct strbuf sb = STRBUF_INIT;
580 struct strbuf err = STRBUF_INIT;
582 repo_read_index(r);
583 if (checkout_fast_forward(r, from, to, 1))
584 return -1; /* the callee should have complained already */
586 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
588 transaction = ref_transaction_begin(&err);
589 if (!transaction ||
590 ref_transaction_update(transaction, "HEAD",
591 to, unborn && !is_rebase_i(opts) ?
592 null_oid() : from,
593 0, sb.buf, &err) ||
594 ref_transaction_commit(transaction, &err)) {
595 ref_transaction_free(transaction);
596 error("%s", err.buf);
597 strbuf_release(&sb);
598 strbuf_release(&err);
599 return -1;
602 strbuf_release(&sb);
603 strbuf_release(&err);
604 ref_transaction_free(transaction);
605 update_abort_safety_file();
606 return 0;
609 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
610 int use_editor)
612 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
613 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
614 COMMIT_MSG_CLEANUP_SPACE;
615 else if (!strcmp(cleanup_arg, "verbatim"))
616 return COMMIT_MSG_CLEANUP_NONE;
617 else if (!strcmp(cleanup_arg, "whitespace"))
618 return COMMIT_MSG_CLEANUP_SPACE;
619 else if (!strcmp(cleanup_arg, "strip"))
620 return COMMIT_MSG_CLEANUP_ALL;
621 else if (!strcmp(cleanup_arg, "scissors"))
622 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
623 COMMIT_MSG_CLEANUP_SPACE;
624 else
625 die(_("Invalid cleanup mode %s"), cleanup_arg);
629 * NB using int rather than enum cleanup_mode to stop clang's
630 * -Wtautological-constant-out-of-range-compare complaining that the comparison
631 * is always true.
633 static const char *describe_cleanup_mode(int cleanup_mode)
635 static const char *modes[] = { "whitespace",
636 "verbatim",
637 "scissors",
638 "strip" };
640 if (cleanup_mode < ARRAY_SIZE(modes))
641 return modes[cleanup_mode];
643 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
646 void append_conflicts_hint(struct index_state *istate,
647 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
649 int i;
651 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
652 strbuf_addch(msgbuf, '\n');
653 wt_status_append_cut_line(msgbuf);
654 strbuf_addch(msgbuf, comment_line_char);
657 strbuf_addch(msgbuf, '\n');
658 strbuf_commented_addf(msgbuf, "Conflicts:\n");
659 for (i = 0; i < istate->cache_nr;) {
660 const struct cache_entry *ce = istate->cache[i++];
661 if (ce_stage(ce)) {
662 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
663 while (i < istate->cache_nr &&
664 !strcmp(ce->name, istate->cache[i]->name))
665 i++;
670 static int do_recursive_merge(struct repository *r,
671 struct commit *base, struct commit *next,
672 const char *base_label, const char *next_label,
673 struct object_id *head, struct strbuf *msgbuf,
674 struct replay_opts *opts)
676 struct merge_options o;
677 struct merge_result result;
678 struct tree *next_tree, *base_tree, *head_tree;
679 int clean, show_output;
680 int i;
681 struct lock_file index_lock = LOCK_INIT;
683 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
684 return -1;
686 repo_read_index(r);
688 init_merge_options(&o, r);
689 o.ancestor = base ? base_label : "(empty tree)";
690 o.branch1 = "HEAD";
691 o.branch2 = next ? next_label : "(empty tree)";
692 if (is_rebase_i(opts))
693 o.buffer_output = 2;
694 o.show_rename_progress = 1;
696 head_tree = parse_tree_indirect(head);
697 next_tree = next ? get_commit_tree(next) : empty_tree(r);
698 base_tree = base ? get_commit_tree(base) : empty_tree(r);
700 for (i = 0; i < opts->xopts_nr; i++)
701 parse_merge_opt(&o, opts->xopts[i]);
703 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
704 memset(&result, 0, sizeof(result));
705 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
706 &result);
707 show_output = !is_rebase_i(opts) || !result.clean;
709 * TODO: merge_switch_to_result will update index/working tree;
710 * we only really want to do that if !result.clean || this is
711 * the final patch to be picked. But determining this is the
712 * final patch would take some work, and "head_tree" would need
713 * to be replace with the tree the index matched before we
714 * started doing any picks.
716 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
717 clean = result.clean;
718 } else {
719 ensure_full_index(r->index);
720 clean = merge_trees(&o, head_tree, next_tree, base_tree);
721 if (is_rebase_i(opts) && clean <= 0)
722 fputs(o.obuf.buf, stdout);
723 strbuf_release(&o.obuf);
725 if (clean < 0) {
726 rollback_lock_file(&index_lock);
727 return clean;
730 if (write_locked_index(r->index, &index_lock,
731 COMMIT_LOCK | SKIP_IF_UNCHANGED))
733 * TRANSLATORS: %s will be "revert", "cherry-pick" or
734 * "rebase".
736 return error(_("%s: Unable to write new index file"),
737 _(action_name(opts)));
739 if (!clean)
740 append_conflicts_hint(r->index, msgbuf,
741 opts->default_msg_cleanup);
743 return !clean;
746 static struct object_id *get_cache_tree_oid(struct index_state *istate)
748 if (!cache_tree_fully_valid(istate->cache_tree))
749 if (cache_tree_update(istate, 0)) {
750 error(_("unable to update cache tree"));
751 return NULL;
754 return &istate->cache_tree->oid;
757 static int is_index_unchanged(struct repository *r)
759 struct object_id head_oid, *cache_tree_oid;
760 struct commit *head_commit;
761 struct index_state *istate = r->index;
763 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
764 return error(_("could not resolve HEAD commit"));
766 head_commit = lookup_commit(r, &head_oid);
769 * If head_commit is NULL, check_commit, called from
770 * lookup_commit, would have indicated that head_commit is not
771 * a commit object already. parse_commit() will return failure
772 * without further complaints in such a case. Otherwise, if
773 * the commit is invalid, parse_commit() will complain. So
774 * there is nothing for us to say here. Just return failure.
776 if (parse_commit(head_commit))
777 return -1;
779 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
780 return -1;
782 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
785 static int write_author_script(const char *message)
787 struct strbuf buf = STRBUF_INIT;
788 const char *eol;
789 int res;
791 for (;;)
792 if (!*message || starts_with(message, "\n")) {
793 missing_author:
794 /* Missing 'author' line? */
795 unlink(rebase_path_author_script());
796 return 0;
797 } else if (skip_prefix(message, "author ", &message))
798 break;
799 else if ((eol = strchr(message, '\n')))
800 message = eol + 1;
801 else
802 goto missing_author;
804 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
805 while (*message && *message != '\n' && *message != '\r')
806 if (skip_prefix(message, " <", &message))
807 break;
808 else if (*message != '\'')
809 strbuf_addch(&buf, *(message++));
810 else
811 strbuf_addf(&buf, "'\\%c'", *(message++));
812 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
813 while (*message && *message != '\n' && *message != '\r')
814 if (skip_prefix(message, "> ", &message))
815 break;
816 else if (*message != '\'')
817 strbuf_addch(&buf, *(message++));
818 else
819 strbuf_addf(&buf, "'\\%c'", *(message++));
820 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
821 while (*message && *message != '\n' && *message != '\r')
822 if (*message != '\'')
823 strbuf_addch(&buf, *(message++));
824 else
825 strbuf_addf(&buf, "'\\%c'", *(message++));
826 strbuf_addch(&buf, '\'');
827 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
828 strbuf_release(&buf);
829 return res;
833 * Take a series of KEY='VALUE' lines where VALUE part is
834 * sq-quoted, and append <KEY, VALUE> at the end of the string list
836 static int parse_key_value_squoted(char *buf, struct string_list *list)
838 while (*buf) {
839 struct string_list_item *item;
840 char *np;
841 char *cp = strchr(buf, '=');
842 if (!cp) {
843 np = strchrnul(buf, '\n');
844 return error(_("no key present in '%.*s'"),
845 (int) (np - buf), buf);
847 np = strchrnul(cp, '\n');
848 *cp++ = '\0';
849 item = string_list_append(list, buf);
851 buf = np + (*np == '\n');
852 *np = '\0';
853 cp = sq_dequote(cp);
854 if (!cp)
855 return error(_("unable to dequote value of '%s'"),
856 item->string);
857 item->util = xstrdup(cp);
859 return 0;
863 * Reads and parses the state directory's "author-script" file, and sets name,
864 * email and date accordingly.
865 * Returns 0 on success, -1 if the file could not be parsed.
867 * The author script is of the format:
869 * GIT_AUTHOR_NAME='$author_name'
870 * GIT_AUTHOR_EMAIL='$author_email'
871 * GIT_AUTHOR_DATE='$author_date'
873 * where $author_name, $author_email and $author_date are quoted. We are strict
874 * with our parsing, as the file was meant to be eval'd in the now-removed
875 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
876 * from what this function expects, it is better to bail out than to do
877 * something that the user does not expect.
879 int read_author_script(const char *path, char **name, char **email, char **date,
880 int allow_missing)
882 struct strbuf buf = STRBUF_INIT;
883 struct string_list kv = STRING_LIST_INIT_DUP;
884 int retval = -1; /* assume failure */
885 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
887 if (strbuf_read_file(&buf, path, 256) <= 0) {
888 strbuf_release(&buf);
889 if (errno == ENOENT && allow_missing)
890 return 0;
891 else
892 return error_errno(_("could not open '%s' for reading"),
893 path);
896 if (parse_key_value_squoted(buf.buf, &kv))
897 goto finish;
899 for (i = 0; i < kv.nr; i++) {
900 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
901 if (name_i != -2)
902 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
903 else
904 name_i = i;
905 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
906 if (email_i != -2)
907 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
908 else
909 email_i = i;
910 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
911 if (date_i != -2)
912 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
913 else
914 date_i = i;
915 } else {
916 err = error(_("unknown variable '%s'"),
917 kv.items[i].string);
920 if (name_i == -2)
921 error(_("missing 'GIT_AUTHOR_NAME'"));
922 if (email_i == -2)
923 error(_("missing 'GIT_AUTHOR_EMAIL'"));
924 if (date_i == -2)
925 error(_("missing 'GIT_AUTHOR_DATE'"));
926 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
927 goto finish;
928 *name = kv.items[name_i].util;
929 *email = kv.items[email_i].util;
930 *date = kv.items[date_i].util;
931 retval = 0;
932 finish:
933 string_list_clear(&kv, !!retval);
934 strbuf_release(&buf);
935 return retval;
939 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
940 * file with shell quoting into struct strvec. Returns -1 on
941 * error, 0 otherwise.
943 static int read_env_script(struct strvec *env)
945 char *name, *email, *date;
947 if (read_author_script(rebase_path_author_script(),
948 &name, &email, &date, 0))
949 return -1;
951 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
952 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
953 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
954 free(name);
955 free(email);
956 free(date);
958 return 0;
961 static char *get_author(const char *message)
963 size_t len;
964 const char *a;
966 a = find_commit_header(message, "author", &len);
967 if (a)
968 return xmemdupz(a, len);
970 return NULL;
973 static const char *author_date_from_env(const struct strvec *env)
975 int i;
976 const char *date;
978 for (i = 0; i < env->nr; i++)
979 if (skip_prefix(env->v[i],
980 "GIT_AUTHOR_DATE=", &date))
981 return date;
983 * If GIT_AUTHOR_DATE is missing we should have already errored out when
984 * reading the script
986 BUG("GIT_AUTHOR_DATE missing from author script");
989 static const char staged_changes_advice[] =
990 N_("you have staged changes in your working tree\n"
991 "If these changes are meant to be squashed into the previous commit, run:\n"
992 "\n"
993 " git commit --amend %s\n"
994 "\n"
995 "If they are meant to go into a new commit, run:\n"
996 "\n"
997 " git commit %s\n"
998 "\n"
999 "In both cases, once you're done, continue with:\n"
1000 "\n"
1001 " git rebase --continue\n");
1003 #define ALLOW_EMPTY (1<<0)
1004 #define EDIT_MSG (1<<1)
1005 #define AMEND_MSG (1<<2)
1006 #define CLEANUP_MSG (1<<3)
1007 #define VERIFY_MSG (1<<4)
1008 #define CREATE_ROOT_COMMIT (1<<5)
1009 #define VERBATIM_MSG (1<<6)
1011 static int run_command_silent_on_success(struct child_process *cmd)
1013 struct strbuf buf = STRBUF_INIT;
1014 int rc;
1016 cmd->stdout_to_stderr = 1;
1017 rc = pipe_command(cmd,
1018 NULL, 0,
1019 NULL, 0,
1020 &buf, 0);
1022 if (rc)
1023 fputs(buf.buf, stderr);
1024 strbuf_release(&buf);
1025 return rc;
1029 * If we are cherry-pick, and if the merge did not result in
1030 * hand-editing, we will hit this commit and inherit the original
1031 * author date and name.
1033 * If we are revert, or if our cherry-pick results in a hand merge,
1034 * we had better say that the current user is responsible for that.
1036 * An exception is when run_git_commit() is called during an
1037 * interactive rebase: in that case, we will want to retain the
1038 * author metadata.
1040 static int run_git_commit(const char *defmsg,
1041 struct replay_opts *opts,
1042 unsigned int flags)
1044 struct child_process cmd = CHILD_PROCESS_INIT;
1046 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1047 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1049 cmd.git_cmd = 1;
1051 if (is_rebase_i(opts) &&
1052 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1053 !(!defmsg && (flags & AMEND_MSG))) &&
1054 read_env_script(&cmd.env)) {
1055 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1057 return error(_(staged_changes_advice),
1058 gpg_opt, gpg_opt);
1061 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1063 if (opts->committer_date_is_author_date)
1064 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1065 opts->ignore_date ?
1066 "" :
1067 author_date_from_env(&cmd.env));
1068 if (opts->ignore_date)
1069 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1071 strvec_push(&cmd.args, "commit");
1073 if (!(flags & VERIFY_MSG))
1074 strvec_push(&cmd.args, "-n");
1075 if ((flags & AMEND_MSG))
1076 strvec_push(&cmd.args, "--amend");
1077 if (opts->gpg_sign)
1078 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1079 else
1080 strvec_push(&cmd.args, "--no-gpg-sign");
1081 if (defmsg)
1082 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1083 else if (!(flags & EDIT_MSG))
1084 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1085 if ((flags & CLEANUP_MSG))
1086 strvec_push(&cmd.args, "--cleanup=strip");
1087 if ((flags & VERBATIM_MSG))
1088 strvec_push(&cmd.args, "--cleanup=verbatim");
1089 if ((flags & EDIT_MSG))
1090 strvec_push(&cmd.args, "-e");
1091 else if (!(flags & CLEANUP_MSG) &&
1092 !opts->signoff && !opts->record_origin &&
1093 !opts->explicit_cleanup)
1094 strvec_push(&cmd.args, "--cleanup=verbatim");
1096 if ((flags & ALLOW_EMPTY))
1097 strvec_push(&cmd.args, "--allow-empty");
1099 if (!(flags & EDIT_MSG))
1100 strvec_push(&cmd.args, "--allow-empty-message");
1102 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1103 return run_command_silent_on_success(&cmd);
1104 else
1105 return run_command(&cmd);
1108 static int rest_is_empty(const struct strbuf *sb, int start)
1110 int i, eol;
1111 const char *nl;
1113 /* Check if the rest is just whitespace and Signed-off-by's. */
1114 for (i = start; i < sb->len; i++) {
1115 nl = memchr(sb->buf + i, '\n', sb->len - i);
1116 if (nl)
1117 eol = nl - sb->buf;
1118 else
1119 eol = sb->len;
1121 if (strlen(sign_off_header) <= eol - i &&
1122 starts_with(sb->buf + i, sign_off_header)) {
1123 i = eol;
1124 continue;
1126 while (i < eol)
1127 if (!isspace(sb->buf[i++]))
1128 return 0;
1131 return 1;
1134 void cleanup_message(struct strbuf *msgbuf,
1135 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1137 if (verbose || /* Truncate the message just before the diff, if any. */
1138 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1139 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1140 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1141 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1145 * Find out if the message in the strbuf contains only whitespace and
1146 * Signed-off-by lines.
1148 int message_is_empty(const struct strbuf *sb,
1149 enum commit_msg_cleanup_mode cleanup_mode)
1151 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1152 return 0;
1153 return rest_is_empty(sb, 0);
1157 * See if the user edited the message in the editor or left what
1158 * was in the template intact
1160 int template_untouched(const struct strbuf *sb, const char *template_file,
1161 enum commit_msg_cleanup_mode cleanup_mode)
1163 struct strbuf tmpl = STRBUF_INIT;
1164 const char *start;
1166 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1167 return 0;
1169 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1170 return 0;
1172 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1173 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1174 start = sb->buf;
1175 strbuf_release(&tmpl);
1176 return rest_is_empty(sb, start - sb->buf);
1179 int update_head_with_reflog(const struct commit *old_head,
1180 const struct object_id *new_head,
1181 const char *action, const struct strbuf *msg,
1182 struct strbuf *err)
1184 struct ref_transaction *transaction;
1185 struct strbuf sb = STRBUF_INIT;
1186 const char *nl;
1187 int ret = 0;
1189 if (action) {
1190 strbuf_addstr(&sb, action);
1191 strbuf_addstr(&sb, ": ");
1194 nl = strchr(msg->buf, '\n');
1195 if (nl) {
1196 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1197 } else {
1198 strbuf_addbuf(&sb, msg);
1199 strbuf_addch(&sb, '\n');
1202 transaction = ref_transaction_begin(err);
1203 if (!transaction ||
1204 ref_transaction_update(transaction, "HEAD", new_head,
1205 old_head ? &old_head->object.oid : null_oid(),
1206 0, sb.buf, err) ||
1207 ref_transaction_commit(transaction, err)) {
1208 ret = -1;
1210 ref_transaction_free(transaction);
1211 strbuf_release(&sb);
1213 return ret;
1216 static int run_rewrite_hook(const struct object_id *oldoid,
1217 const struct object_id *newoid)
1219 struct child_process proc = CHILD_PROCESS_INIT;
1220 int code;
1221 struct strbuf sb = STRBUF_INIT;
1222 const char *hook_path = find_hook("post-rewrite");
1224 if (!hook_path)
1225 return 0;
1227 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1228 proc.in = -1;
1229 proc.stdout_to_stderr = 1;
1230 proc.trace2_hook_name = "post-rewrite";
1232 code = start_command(&proc);
1233 if (code)
1234 return code;
1235 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1236 sigchain_push(SIGPIPE, SIG_IGN);
1237 write_in_full(proc.in, sb.buf, sb.len);
1238 close(proc.in);
1239 strbuf_release(&sb);
1240 sigchain_pop(SIGPIPE);
1241 return finish_command(&proc);
1244 void commit_post_rewrite(struct repository *r,
1245 const struct commit *old_head,
1246 const struct object_id *new_head)
1248 struct notes_rewrite_cfg *cfg;
1250 cfg = init_copy_notes_for_rewrite("amend");
1251 if (cfg) {
1252 /* we are amending, so old_head is not NULL */
1253 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1254 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1256 run_rewrite_hook(&old_head->object.oid, new_head);
1259 static int run_prepare_commit_msg_hook(struct repository *r,
1260 struct strbuf *msg,
1261 const char *commit)
1263 int ret = 0;
1264 const char *name, *arg1 = NULL, *arg2 = NULL;
1266 name = git_path_commit_editmsg();
1267 if (write_message(msg->buf, msg->len, name, 0))
1268 return -1;
1270 if (commit) {
1271 arg1 = "commit";
1272 arg2 = commit;
1273 } else {
1274 arg1 = "message";
1276 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1277 arg1, arg2, NULL))
1278 ret = error(_("'prepare-commit-msg' hook failed"));
1280 return ret;
1283 static const char implicit_ident_advice_noconfig[] =
1284 N_("Your name and email address were configured automatically based\n"
1285 "on your username and hostname. Please check that they are accurate.\n"
1286 "You can suppress this message by setting them explicitly. Run the\n"
1287 "following command and follow the instructions in your editor to edit\n"
1288 "your configuration file:\n"
1289 "\n"
1290 " git config --global --edit\n"
1291 "\n"
1292 "After doing this, you may fix the identity used for this commit with:\n"
1293 "\n"
1294 " git commit --amend --reset-author\n");
1296 static const char implicit_ident_advice_config[] =
1297 N_("Your name and email address were configured automatically based\n"
1298 "on your username and hostname. Please check that they are accurate.\n"
1299 "You can suppress this message by setting them explicitly:\n"
1300 "\n"
1301 " git config --global user.name \"Your Name\"\n"
1302 " git config --global user.email you@example.com\n"
1303 "\n"
1304 "After doing this, you may fix the identity used for this commit with:\n"
1305 "\n"
1306 " git commit --amend --reset-author\n");
1308 static const char *implicit_ident_advice(void)
1310 char *user_config = interpolate_path("~/.gitconfig", 0);
1311 char *xdg_config = xdg_config_home("config");
1312 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1314 free(user_config);
1315 free(xdg_config);
1317 if (config_exists)
1318 return _(implicit_ident_advice_config);
1319 else
1320 return _(implicit_ident_advice_noconfig);
1324 void print_commit_summary(struct repository *r,
1325 const char *prefix,
1326 const struct object_id *oid,
1327 unsigned int flags)
1329 struct rev_info rev;
1330 struct commit *commit;
1331 struct strbuf format = STRBUF_INIT;
1332 const char *head;
1333 struct pretty_print_context pctx = {0};
1334 struct strbuf author_ident = STRBUF_INIT;
1335 struct strbuf committer_ident = STRBUF_INIT;
1336 struct ref_store *refs;
1338 commit = lookup_commit(r, oid);
1339 if (!commit)
1340 die(_("couldn't look up newly created commit"));
1341 if (parse_commit(commit))
1342 die(_("could not parse newly created commit"));
1344 strbuf_addstr(&format, "format:%h] %s");
1346 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1347 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1348 if (strbuf_cmp(&author_ident, &committer_ident)) {
1349 strbuf_addstr(&format, "\n Author: ");
1350 strbuf_addbuf_percentquote(&format, &author_ident);
1352 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1353 struct strbuf date = STRBUF_INIT;
1355 format_commit_message(commit, "%ad", &date, &pctx);
1356 strbuf_addstr(&format, "\n Date: ");
1357 strbuf_addbuf_percentquote(&format, &date);
1358 strbuf_release(&date);
1360 if (!committer_ident_sufficiently_given()) {
1361 strbuf_addstr(&format, "\n Committer: ");
1362 strbuf_addbuf_percentquote(&format, &committer_ident);
1363 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1364 strbuf_addch(&format, '\n');
1365 strbuf_addstr(&format, implicit_ident_advice());
1368 strbuf_release(&author_ident);
1369 strbuf_release(&committer_ident);
1371 repo_init_revisions(r, &rev, prefix);
1372 setup_revisions(0, NULL, &rev, NULL);
1374 rev.diff = 1;
1375 rev.diffopt.output_format =
1376 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1378 rev.verbose_header = 1;
1379 rev.show_root_diff = 1;
1380 get_commit_format(format.buf, &rev);
1381 rev.always_show_header = 0;
1382 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1383 diff_setup_done(&rev.diffopt);
1385 refs = get_main_ref_store(the_repository);
1386 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1387 if (!head)
1388 die(_("unable to resolve HEAD after creating commit"));
1389 if (!strcmp(head, "HEAD"))
1390 head = _("detached HEAD");
1391 else
1392 skip_prefix(head, "refs/heads/", &head);
1393 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1394 _(" (root-commit)") : "");
1396 if (!log_tree_commit(&rev, commit)) {
1397 rev.always_show_header = 1;
1398 rev.use_terminator = 1;
1399 log_tree_commit(&rev, commit);
1402 release_revisions(&rev);
1403 strbuf_release(&format);
1406 static int parse_head(struct repository *r, struct commit **head)
1408 struct commit *current_head;
1409 struct object_id oid;
1411 if (get_oid("HEAD", &oid)) {
1412 current_head = NULL;
1413 } else {
1414 current_head = lookup_commit_reference(r, &oid);
1415 if (!current_head)
1416 return error(_("could not parse HEAD"));
1417 if (!oideq(&oid, &current_head->object.oid)) {
1418 warning(_("HEAD %s is not a commit!"),
1419 oid_to_hex(&oid));
1421 if (parse_commit(current_head))
1422 return error(_("could not parse HEAD commit"));
1424 *head = current_head;
1426 return 0;
1430 * Try to commit without forking 'git commit'. In some cases we need
1431 * to run 'git commit' to display an error message
1433 * Returns:
1434 * -1 - error unable to commit
1435 * 0 - success
1436 * 1 - run 'git commit'
1438 static int try_to_commit(struct repository *r,
1439 struct strbuf *msg, const char *author,
1440 struct replay_opts *opts, unsigned int flags,
1441 struct object_id *oid)
1443 struct object_id tree;
1444 struct commit *current_head = NULL;
1445 struct commit_list *parents = NULL;
1446 struct commit_extra_header *extra = NULL;
1447 struct strbuf err = STRBUF_INIT;
1448 struct strbuf commit_msg = STRBUF_INIT;
1449 char *amend_author = NULL;
1450 const char *committer = NULL;
1451 const char *hook_commit = NULL;
1452 enum commit_msg_cleanup_mode cleanup;
1453 int res = 0;
1455 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1456 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1458 if (parse_head(r, &current_head))
1459 return -1;
1461 if (flags & AMEND_MSG) {
1462 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1463 const char *out_enc = get_commit_output_encoding();
1464 const char *message = logmsg_reencode(current_head, NULL,
1465 out_enc);
1467 if (!msg) {
1468 const char *orig_message = NULL;
1470 find_commit_subject(message, &orig_message);
1471 msg = &commit_msg;
1472 strbuf_addstr(msg, orig_message);
1473 hook_commit = "HEAD";
1475 author = amend_author = get_author(message);
1476 unuse_commit_buffer(current_head, message);
1477 if (!author) {
1478 res = error(_("unable to parse commit author"));
1479 goto out;
1481 parents = copy_commit_list(current_head->parents);
1482 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1483 } else if (current_head &&
1484 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1485 commit_list_insert(current_head, &parents);
1488 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1489 res = error(_("git write-tree failed to write a tree"));
1490 goto out;
1493 if (!(flags & ALLOW_EMPTY)) {
1494 struct commit *first_parent = current_head;
1496 if (flags & AMEND_MSG) {
1497 if (current_head->parents) {
1498 first_parent = current_head->parents->item;
1499 if (repo_parse_commit(r, first_parent)) {
1500 res = error(_("could not parse HEAD commit"));
1501 goto out;
1503 } else {
1504 first_parent = NULL;
1507 if (oideq(first_parent
1508 ? get_commit_tree_oid(first_parent)
1509 : the_hash_algo->empty_tree,
1510 &tree)) {
1511 res = 1; /* run 'git commit' to display error message */
1512 goto out;
1516 if (hook_exists("prepare-commit-msg")) {
1517 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1518 if (res)
1519 goto out;
1520 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1521 2048) < 0) {
1522 res = error_errno(_("unable to read commit message "
1523 "from '%s'"),
1524 git_path_commit_editmsg());
1525 goto out;
1527 msg = &commit_msg;
1530 if (flags & CLEANUP_MSG)
1531 cleanup = COMMIT_MSG_CLEANUP_ALL;
1532 else if (flags & VERBATIM_MSG)
1533 cleanup = COMMIT_MSG_CLEANUP_NONE;
1534 else if ((opts->signoff || opts->record_origin) &&
1535 !opts->explicit_cleanup)
1536 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1537 else
1538 cleanup = opts->default_msg_cleanup;
1540 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1541 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1542 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1543 res = 1; /* run 'git commit' to display error message */
1544 goto out;
1547 if (opts->committer_date_is_author_date) {
1548 struct ident_split id;
1549 struct strbuf date = STRBUF_INIT;
1551 if (!opts->ignore_date) {
1552 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1553 res = error(_("invalid author identity '%s'"),
1554 author);
1555 goto out;
1557 if (!id.date_begin) {
1558 res = error(_(
1559 "corrupt author: missing date information"));
1560 goto out;
1562 strbuf_addf(&date, "@%.*s %.*s",
1563 (int)(id.date_end - id.date_begin),
1564 id.date_begin,
1565 (int)(id.tz_end - id.tz_begin),
1566 id.tz_begin);
1567 } else {
1568 reset_ident_date();
1570 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1571 getenv("GIT_COMMITTER_EMAIL"),
1572 WANT_COMMITTER_IDENT,
1573 opts->ignore_date ? NULL : date.buf,
1574 IDENT_STRICT);
1575 strbuf_release(&date);
1576 } else {
1577 reset_ident_date();
1580 if (opts->ignore_date) {
1581 struct ident_split id;
1582 char *name, *email;
1584 if (split_ident_line(&id, author, strlen(author)) < 0) {
1585 error(_("invalid author identity '%s'"), author);
1586 goto out;
1588 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1589 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1590 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1591 IDENT_STRICT);
1592 free(name);
1593 free(email);
1596 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1597 author, committer, opts->gpg_sign, extra)) {
1598 res = error(_("failed to write commit object"));
1599 goto out;
1602 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1603 msg, &err)) {
1604 res = error("%s", err.buf);
1605 goto out;
1608 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1609 if (flags & AMEND_MSG)
1610 commit_post_rewrite(r, current_head, oid);
1612 out:
1613 free_commit_extra_headers(extra);
1614 strbuf_release(&err);
1615 strbuf_release(&commit_msg);
1616 free(amend_author);
1618 return res;
1621 static int write_rebase_head(struct object_id *oid)
1623 if (update_ref("rebase", "REBASE_HEAD", oid,
1624 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1625 return error(_("could not update %s"), "REBASE_HEAD");
1627 return 0;
1630 static int do_commit(struct repository *r,
1631 const char *msg_file, const char *author,
1632 struct replay_opts *opts, unsigned int flags,
1633 struct object_id *oid)
1635 int res = 1;
1637 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1638 struct object_id oid;
1639 struct strbuf sb = STRBUF_INIT;
1641 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1642 return error_errno(_("unable to read commit message "
1643 "from '%s'"),
1644 msg_file);
1646 res = try_to_commit(r, msg_file ? &sb : NULL,
1647 author, opts, flags, &oid);
1648 strbuf_release(&sb);
1649 if (!res) {
1650 refs_delete_ref(get_main_ref_store(r), "",
1651 "CHERRY_PICK_HEAD", NULL, 0);
1652 unlink(git_path_merge_msg(r));
1653 if (!is_rebase_i(opts))
1654 print_commit_summary(r, NULL, &oid,
1655 SUMMARY_SHOW_AUTHOR_DATE);
1656 return res;
1659 if (res == 1) {
1660 if (is_rebase_i(opts) && oid)
1661 if (write_rebase_head(oid))
1662 return -1;
1663 return run_git_commit(msg_file, opts, flags);
1666 return res;
1669 static int is_original_commit_empty(struct commit *commit)
1671 const struct object_id *ptree_oid;
1673 if (parse_commit(commit))
1674 return error(_("could not parse commit %s"),
1675 oid_to_hex(&commit->object.oid));
1676 if (commit->parents) {
1677 struct commit *parent = commit->parents->item;
1678 if (parse_commit(parent))
1679 return error(_("could not parse parent commit %s"),
1680 oid_to_hex(&parent->object.oid));
1681 ptree_oid = get_commit_tree_oid(parent);
1682 } else {
1683 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1686 return oideq(ptree_oid, get_commit_tree_oid(commit));
1690 * Should empty commits be allowed? Return status:
1691 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1692 * 0: Halt on empty commit
1693 * 1: Allow empty commit
1694 * 2: Drop empty commit
1696 static int allow_empty(struct repository *r,
1697 struct replay_opts *opts,
1698 struct commit *commit)
1700 int index_unchanged, originally_empty;
1703 * Four cases:
1705 * (1) we do not allow empty at all and error out.
1707 * (2) we allow ones that were initially empty, and
1708 * just drop the ones that become empty
1710 * (3) we allow ones that were initially empty, but
1711 * halt for the ones that become empty;
1713 * (4) we allow both.
1715 if (!opts->allow_empty)
1716 return 0; /* let "git commit" barf as necessary */
1718 index_unchanged = is_index_unchanged(r);
1719 if (index_unchanged < 0)
1720 return index_unchanged;
1721 if (!index_unchanged)
1722 return 0; /* we do not have to say --allow-empty */
1724 if (opts->keep_redundant_commits)
1725 return 1;
1727 originally_empty = is_original_commit_empty(commit);
1728 if (originally_empty < 0)
1729 return originally_empty;
1730 if (originally_empty)
1731 return 1;
1732 else if (opts->drop_redundant_commits)
1733 return 2;
1734 else
1735 return 0;
1738 static struct {
1739 char c;
1740 const char *str;
1741 } todo_command_info[] = {
1742 [TODO_PICK] = { 'p', "pick" },
1743 [TODO_REVERT] = { 0, "revert" },
1744 [TODO_EDIT] = { 'e', "edit" },
1745 [TODO_REWORD] = { 'r', "reword" },
1746 [TODO_FIXUP] = { 'f', "fixup" },
1747 [TODO_SQUASH] = { 's', "squash" },
1748 [TODO_EXEC] = { 'x', "exec" },
1749 [TODO_BREAK] = { 'b', "break" },
1750 [TODO_LABEL] = { 'l', "label" },
1751 [TODO_RESET] = { 't', "reset" },
1752 [TODO_MERGE] = { 'm', "merge" },
1753 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1754 [TODO_NOOP] = { 0, "noop" },
1755 [TODO_DROP] = { 'd', "drop" },
1756 [TODO_COMMENT] = { 0, NULL },
1759 static const char *command_to_string(const enum todo_command command)
1761 if (command < TODO_COMMENT)
1762 return todo_command_info[command].str;
1763 die(_("unknown command: %d"), command);
1766 static char command_to_char(const enum todo_command command)
1768 if (command < TODO_COMMENT)
1769 return todo_command_info[command].c;
1770 return comment_line_char;
1773 static int is_noop(const enum todo_command command)
1775 return TODO_NOOP <= command;
1778 static int is_fixup(enum todo_command command)
1780 return command == TODO_FIXUP || command == TODO_SQUASH;
1783 /* Does this command create a (non-merge) commit? */
1784 static int is_pick_or_similar(enum todo_command command)
1786 switch (command) {
1787 case TODO_PICK:
1788 case TODO_REVERT:
1789 case TODO_EDIT:
1790 case TODO_REWORD:
1791 case TODO_FIXUP:
1792 case TODO_SQUASH:
1793 return 1;
1794 default:
1795 return 0;
1799 enum todo_item_flags {
1800 TODO_EDIT_MERGE_MSG = (1 << 0),
1801 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1802 TODO_EDIT_FIXUP_MSG = (1 << 2),
1805 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1806 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1807 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1808 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1809 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1811 static int is_fixup_flag(enum todo_command command, unsigned flag)
1813 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1814 (flag & TODO_EDIT_FIXUP_MSG));
1818 * Wrapper around strbuf_add_commented_lines() which avoids double
1819 * commenting commit subjects.
1821 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1823 const char *s = str;
1824 while (len > 0 && s[0] == comment_line_char) {
1825 size_t count;
1826 const char *n = memchr(s, '\n', len);
1827 if (!n)
1828 count = len;
1829 else
1830 count = n - s + 1;
1831 strbuf_add(buf, s, count);
1832 s += count;
1833 len -= count;
1835 strbuf_add_commented_lines(buf, s, len);
1838 /* Does the current fixup chain contain a squash command? */
1839 static int seen_squash(struct replay_opts *opts)
1841 return starts_with(opts->current_fixups.buf, "squash") ||
1842 strstr(opts->current_fixups.buf, "\nsquash");
1845 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1847 strbuf_setlen(buf1, 2);
1848 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1849 strbuf_addch(buf1, '\n');
1850 strbuf_setlen(buf2, 2);
1851 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1852 strbuf_addch(buf2, '\n');
1856 * Comment out any un-commented commit messages, updating the message comments
1857 * to say they will be skipped but do not comment out the empty lines that
1858 * surround commit messages and their comments.
1860 static void update_squash_message_for_fixup(struct strbuf *msg)
1862 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1863 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1864 const char *s, *start;
1865 char *orig_msg;
1866 size_t orig_msg_len;
1867 int i = 1;
1869 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1870 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1871 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1872 while (s) {
1873 const char *next;
1874 size_t off;
1875 if (skip_prefix(s, buf1.buf, &next)) {
1877 * Copy the last message, preserving the blank line
1878 * preceding the current line
1880 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1881 copy_lines(msg, start, s - start - off);
1882 if (off)
1883 strbuf_addch(msg, '\n');
1885 * The next message needs to be commented out but the
1886 * message header is already commented out so just copy
1887 * it and the blank line that follows it.
1889 strbuf_addbuf(msg, &buf2);
1890 if (*next == '\n')
1891 strbuf_addch(msg, *next++);
1892 start = s = next;
1893 copy_lines = add_commented_lines;
1894 update_comment_bufs(&buf1, &buf2, ++i);
1895 } else if (skip_prefix(s, buf2.buf, &next)) {
1896 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1897 copy_lines(msg, start, s - start - off);
1898 start = s - off;
1899 s = next;
1900 copy_lines = strbuf_add;
1901 update_comment_bufs(&buf1, &buf2, ++i);
1902 } else {
1903 s = strchr(s, '\n');
1904 if (s)
1905 s++;
1908 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1909 free(orig_msg);
1910 strbuf_release(&buf1);
1911 strbuf_release(&buf2);
1914 static int append_squash_message(struct strbuf *buf, const char *body,
1915 enum todo_command command, struct replay_opts *opts,
1916 unsigned flag)
1918 const char *fixup_msg;
1919 size_t commented_len = 0, fixup_off;
1921 * amend is non-interactive and not normally used with fixup!
1922 * or squash! commits, so only comment out those subjects when
1923 * squashing commit messages.
1925 if (starts_with(body, "amend!") ||
1926 ((command == TODO_SQUASH || seen_squash(opts)) &&
1927 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1928 commented_len = commit_subject_length(body);
1930 strbuf_addf(buf, "\n%c ", comment_line_char);
1931 strbuf_addf(buf, _(nth_commit_msg_fmt),
1932 ++opts->current_fixup_count + 1);
1933 strbuf_addstr(buf, "\n\n");
1934 strbuf_add_commented_lines(buf, body, commented_len);
1935 /* buf->buf may be reallocated so store an offset into the buffer */
1936 fixup_off = buf->len;
1937 strbuf_addstr(buf, body + commented_len);
1939 /* fixup -C after squash behaves like squash */
1940 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1942 * We're replacing the commit message so we need to
1943 * append the Signed-off-by: trailer if the user
1944 * requested '--signoff'.
1946 if (opts->signoff)
1947 append_signoff(buf, 0, 0);
1949 if ((command == TODO_FIXUP) &&
1950 (flag & TODO_REPLACE_FIXUP_MSG) &&
1951 (file_exists(rebase_path_fixup_msg()) ||
1952 !file_exists(rebase_path_squash_msg()))) {
1953 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1954 if (write_message(fixup_msg, strlen(fixup_msg),
1955 rebase_path_fixup_msg(), 0) < 0)
1956 return error(_("cannot write '%s'"),
1957 rebase_path_fixup_msg());
1958 } else {
1959 unlink(rebase_path_fixup_msg());
1961 } else {
1962 unlink(rebase_path_fixup_msg());
1965 return 0;
1968 static int update_squash_messages(struct repository *r,
1969 enum todo_command command,
1970 struct commit *commit,
1971 struct replay_opts *opts,
1972 unsigned flag)
1974 struct strbuf buf = STRBUF_INIT;
1975 int res = 0;
1976 const char *message, *body;
1977 const char *encoding = get_commit_output_encoding();
1979 if (opts->current_fixup_count > 0) {
1980 struct strbuf header = STRBUF_INIT;
1981 char *eol;
1983 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1984 return error(_("could not read '%s'"),
1985 rebase_path_squash_msg());
1987 eol = buf.buf[0] != comment_line_char ?
1988 buf.buf : strchrnul(buf.buf, '\n');
1990 strbuf_addf(&header, "%c ", comment_line_char);
1991 strbuf_addf(&header, _(combined_commit_msg_fmt),
1992 opts->current_fixup_count + 2);
1993 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1994 strbuf_release(&header);
1995 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1996 update_squash_message_for_fixup(&buf);
1997 } else {
1998 struct object_id head;
1999 struct commit *head_commit;
2000 const char *head_message, *body;
2002 if (get_oid("HEAD", &head))
2003 return error(_("need a HEAD to fixup"));
2004 if (!(head_commit = lookup_commit_reference(r, &head)))
2005 return error(_("could not read HEAD"));
2006 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
2007 return error(_("could not read HEAD's commit message"));
2009 find_commit_subject(head_message, &body);
2010 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2011 rebase_path_fixup_msg(), 0) < 0) {
2012 unuse_commit_buffer(head_commit, head_message);
2013 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2015 strbuf_addf(&buf, "%c ", comment_line_char);
2016 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2017 strbuf_addf(&buf, "\n%c ", comment_line_char);
2018 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2019 _(skip_first_commit_msg_str) :
2020 _(first_commit_msg_str));
2021 strbuf_addstr(&buf, "\n\n");
2022 if (is_fixup_flag(command, flag))
2023 strbuf_add_commented_lines(&buf, body, strlen(body));
2024 else
2025 strbuf_addstr(&buf, body);
2027 unuse_commit_buffer(head_commit, head_message);
2030 if (!(message = logmsg_reencode(commit, NULL, encoding)))
2031 return error(_("could not read commit message of %s"),
2032 oid_to_hex(&commit->object.oid));
2033 find_commit_subject(message, &body);
2035 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2036 res = append_squash_message(&buf, body, command, opts, flag);
2037 } else if (command == TODO_FIXUP) {
2038 strbuf_addf(&buf, "\n%c ", comment_line_char);
2039 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2040 ++opts->current_fixup_count + 1);
2041 strbuf_addstr(&buf, "\n\n");
2042 strbuf_add_commented_lines(&buf, body, strlen(body));
2043 } else
2044 return error(_("unknown command: %d"), command);
2045 unuse_commit_buffer(commit, message);
2047 if (!res)
2048 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2050 strbuf_release(&buf);
2052 if (!res) {
2053 strbuf_addf(&opts->current_fixups, "%s%s %s",
2054 opts->current_fixups.len ? "\n" : "",
2055 command_to_string(command),
2056 oid_to_hex(&commit->object.oid));
2057 res = write_message(opts->current_fixups.buf,
2058 opts->current_fixups.len,
2059 rebase_path_current_fixups(), 0);
2062 return res;
2065 static void flush_rewritten_pending(void)
2067 struct strbuf buf = STRBUF_INIT;
2068 struct object_id newoid;
2069 FILE *out;
2071 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2072 !get_oid("HEAD", &newoid) &&
2073 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2074 char *bol = buf.buf, *eol;
2076 while (*bol) {
2077 eol = strchrnul(bol, '\n');
2078 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2079 bol, oid_to_hex(&newoid));
2080 if (!*eol)
2081 break;
2082 bol = eol + 1;
2084 fclose(out);
2085 unlink(rebase_path_rewritten_pending());
2087 strbuf_release(&buf);
2090 static void record_in_rewritten(struct object_id *oid,
2091 enum todo_command next_command)
2093 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2095 if (!out)
2096 return;
2098 fprintf(out, "%s\n", oid_to_hex(oid));
2099 fclose(out);
2101 if (!is_fixup(next_command))
2102 flush_rewritten_pending();
2105 static int should_edit(struct replay_opts *opts) {
2106 if (opts->edit < 0)
2108 * Note that we only handle the case of non-conflicted
2109 * commits; continue_single_pick() handles the conflicted
2110 * commits itself instead of calling this function.
2112 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2113 return opts->edit;
2116 static void refer_to_commit(struct replay_opts *opts,
2117 struct strbuf *msgbuf, struct commit *commit)
2119 if (opts->commit_use_reference) {
2120 struct pretty_print_context ctx = {
2121 .abbrev = DEFAULT_ABBREV,
2122 .date_mode.type = DATE_SHORT,
2124 format_commit_message(commit, "%h (%s, %ad)", msgbuf, &ctx);
2125 } else {
2126 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2130 static int do_pick_commit(struct repository *r,
2131 struct todo_item *item,
2132 struct replay_opts *opts,
2133 int final_fixup, int *check_todo)
2135 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2136 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2137 struct object_id head;
2138 struct commit *base, *next, *parent;
2139 const char *base_label, *next_label;
2140 char *author = NULL;
2141 struct commit_message msg = { NULL, NULL, NULL, NULL };
2142 struct strbuf msgbuf = STRBUF_INIT;
2143 int res, unborn = 0, reword = 0, allow, drop_commit;
2144 enum todo_command command = item->command;
2145 struct commit *commit = item->commit;
2147 if (opts->no_commit) {
2149 * We do not intend to commit immediately. We just want to
2150 * merge the differences in, so let's compute the tree
2151 * that represents the "current" state for the merge machinery
2152 * to work on.
2154 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2155 return error(_("your index file is unmerged."));
2156 } else {
2157 unborn = get_oid("HEAD", &head);
2158 /* Do we want to generate a root commit? */
2159 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2160 oideq(&head, &opts->squash_onto)) {
2161 if (is_fixup(command))
2162 return error(_("cannot fixup root commit"));
2163 flags |= CREATE_ROOT_COMMIT;
2164 unborn = 1;
2165 } else if (unborn)
2166 oidcpy(&head, the_hash_algo->empty_tree);
2167 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2168 NULL, 0))
2169 return error_dirty_index(r, opts);
2171 discard_index(r->index);
2173 if (!commit->parents)
2174 parent = NULL;
2175 else if (commit->parents->next) {
2176 /* Reverting or cherry-picking a merge commit */
2177 int cnt;
2178 struct commit_list *p;
2180 if (!opts->mainline)
2181 return error(_("commit %s is a merge but no -m option was given."),
2182 oid_to_hex(&commit->object.oid));
2184 for (cnt = 1, p = commit->parents;
2185 cnt != opts->mainline && p;
2186 cnt++)
2187 p = p->next;
2188 if (cnt != opts->mainline || !p)
2189 return error(_("commit %s does not have parent %d"),
2190 oid_to_hex(&commit->object.oid), opts->mainline);
2191 parent = p->item;
2192 } else if (1 < opts->mainline)
2194 * Non-first parent explicitly specified as mainline for
2195 * non-merge commit
2197 return error(_("commit %s does not have parent %d"),
2198 oid_to_hex(&commit->object.oid), opts->mainline);
2199 else
2200 parent = commit->parents->item;
2202 if (get_message(commit, &msg) != 0)
2203 return error(_("cannot get commit message for %s"),
2204 oid_to_hex(&commit->object.oid));
2206 if (opts->allow_ff && !is_fixup(command) &&
2207 ((parent && oideq(&parent->object.oid, &head)) ||
2208 (!parent && unborn))) {
2209 if (is_rebase_i(opts))
2210 write_author_script(msg.message);
2211 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2212 opts);
2213 if (res || command != TODO_REWORD)
2214 goto leave;
2215 reword = 1;
2216 msg_file = NULL;
2217 goto fast_forward_edit;
2219 if (parent && parse_commit(parent) < 0)
2220 /* TRANSLATORS: The first %s will be a "todo" command like
2221 "revert" or "pick", the second %s a SHA1. */
2222 return error(_("%s: cannot parse parent commit %s"),
2223 command_to_string(command),
2224 oid_to_hex(&parent->object.oid));
2227 * "commit" is an existing commit. We would want to apply
2228 * the difference it introduces since its first parent "prev"
2229 * on top of the current HEAD if we are cherry-pick. Or the
2230 * reverse of it if we are revert.
2233 if (command == TODO_REVERT) {
2234 base = commit;
2235 base_label = msg.label;
2236 next = parent;
2237 next_label = msg.parent_label;
2238 if (opts->commit_use_reference) {
2239 strbuf_addstr(&msgbuf,
2240 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2241 } else {
2242 strbuf_addstr(&msgbuf, "Revert \"");
2243 strbuf_addstr(&msgbuf, msg.subject);
2244 strbuf_addstr(&msgbuf, "\"");
2246 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2247 refer_to_commit(opts, &msgbuf, commit);
2249 if (commit->parents && commit->parents->next) {
2250 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2251 refer_to_commit(opts, &msgbuf, parent);
2253 strbuf_addstr(&msgbuf, ".\n");
2254 } else {
2255 const char *p;
2257 base = parent;
2258 base_label = msg.parent_label;
2259 next = commit;
2260 next_label = msg.label;
2262 /* Append the commit log message to msgbuf. */
2263 if (find_commit_subject(msg.message, &p))
2264 strbuf_addstr(&msgbuf, p);
2266 if (opts->record_origin) {
2267 strbuf_complete_line(&msgbuf);
2268 if (!has_conforming_footer(&msgbuf, NULL, 0))
2269 strbuf_addch(&msgbuf, '\n');
2270 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2271 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2272 strbuf_addstr(&msgbuf, ")\n");
2274 if (!is_fixup(command))
2275 author = get_author(msg.message);
2278 if (command == TODO_REWORD)
2279 reword = 1;
2280 else if (is_fixup(command)) {
2281 if (update_squash_messages(r, command, commit,
2282 opts, item->flags)) {
2283 res = -1;
2284 goto leave;
2286 flags |= AMEND_MSG;
2287 if (!final_fixup)
2288 msg_file = rebase_path_squash_msg();
2289 else if (file_exists(rebase_path_fixup_msg())) {
2290 flags |= VERBATIM_MSG;
2291 msg_file = rebase_path_fixup_msg();
2292 } else {
2293 const char *dest = git_path_squash_msg(r);
2294 unlink(dest);
2295 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2296 res = error(_("could not rename '%s' to '%s'"),
2297 rebase_path_squash_msg(), dest);
2298 goto leave;
2300 unlink(git_path_merge_msg(r));
2301 msg_file = dest;
2302 flags |= EDIT_MSG;
2306 if (opts->signoff && !is_fixup(command))
2307 append_signoff(&msgbuf, 0, 0);
2309 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2310 res = -1;
2311 else if (!opts->strategy ||
2312 !strcmp(opts->strategy, "recursive") ||
2313 !strcmp(opts->strategy, "ort") ||
2314 command == TODO_REVERT) {
2315 res = do_recursive_merge(r, base, next, base_label, next_label,
2316 &head, &msgbuf, opts);
2317 if (res < 0)
2318 goto leave;
2320 res |= write_message(msgbuf.buf, msgbuf.len,
2321 git_path_merge_msg(r), 0);
2322 } else {
2323 struct commit_list *common = NULL;
2324 struct commit_list *remotes = NULL;
2326 res = write_message(msgbuf.buf, msgbuf.len,
2327 git_path_merge_msg(r), 0);
2329 commit_list_insert(base, &common);
2330 commit_list_insert(next, &remotes);
2331 res |= try_merge_command(r, opts->strategy,
2332 opts->xopts_nr, (const char **)opts->xopts,
2333 common, oid_to_hex(&head), remotes);
2334 free_commit_list(common);
2335 free_commit_list(remotes);
2339 * If the merge was clean or if it failed due to conflict, we write
2340 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2341 * However, if the merge did not even start, then we don't want to
2342 * write it at all.
2344 if ((command == TODO_PICK || command == TODO_REWORD ||
2345 command == TODO_EDIT) && !opts->no_commit &&
2346 (res == 0 || res == 1) &&
2347 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2348 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2349 res = -1;
2350 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2351 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2352 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2353 res = -1;
2355 if (res) {
2356 error(command == TODO_REVERT
2357 ? _("could not revert %s... %s")
2358 : _("could not apply %s... %s"),
2359 short_commit_name(commit), msg.subject);
2360 print_advice(r, res == 1, opts);
2361 repo_rerere(r, opts->allow_rerere_auto);
2362 goto leave;
2365 drop_commit = 0;
2366 allow = allow_empty(r, opts, commit);
2367 if (allow < 0) {
2368 res = allow;
2369 goto leave;
2370 } else if (allow == 1) {
2371 flags |= ALLOW_EMPTY;
2372 } else if (allow == 2) {
2373 drop_commit = 1;
2374 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2375 NULL, 0);
2376 unlink(git_path_merge_msg(r));
2377 unlink(git_path_auto_merge(r));
2378 fprintf(stderr,
2379 _("dropping %s %s -- patch contents already upstream\n"),
2380 oid_to_hex(&commit->object.oid), msg.subject);
2381 } /* else allow == 0 and there's nothing special to do */
2382 if (!opts->no_commit && !drop_commit) {
2383 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2384 res = do_commit(r, msg_file, author, opts, flags,
2385 commit? &commit->object.oid : NULL);
2386 else
2387 res = error(_("unable to parse commit author"));
2388 *check_todo = !!(flags & EDIT_MSG);
2389 if (!res && reword) {
2390 fast_forward_edit:
2391 res = run_git_commit(NULL, opts, EDIT_MSG |
2392 VERIFY_MSG | AMEND_MSG |
2393 (flags & ALLOW_EMPTY));
2394 *check_todo = 1;
2399 if (!res && final_fixup) {
2400 unlink(rebase_path_fixup_msg());
2401 unlink(rebase_path_squash_msg());
2402 unlink(rebase_path_current_fixups());
2403 strbuf_reset(&opts->current_fixups);
2404 opts->current_fixup_count = 0;
2407 leave:
2408 free_message(commit, &msg);
2409 free(author);
2410 strbuf_release(&msgbuf);
2411 update_abort_safety_file();
2413 return res;
2416 static int prepare_revs(struct replay_opts *opts)
2419 * picking (but not reverting) ranges (but not individual revisions)
2420 * should be done in reverse
2422 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2423 opts->revs->reverse ^= 1;
2425 if (prepare_revision_walk(opts->revs))
2426 return error(_("revision walk setup failed"));
2428 return 0;
2431 static int read_and_refresh_cache(struct repository *r,
2432 struct replay_opts *opts)
2434 struct lock_file index_lock = LOCK_INIT;
2435 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2436 if (repo_read_index(r) < 0) {
2437 rollback_lock_file(&index_lock);
2438 return error(_("git %s: failed to read the index"),
2439 action_name(opts));
2441 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2443 if (index_fd >= 0) {
2444 if (write_locked_index(r->index, &index_lock,
2445 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2446 return error(_("git %s: failed to refresh the index"),
2447 action_name(opts));
2452 * If we are resolving merges in any way other than "ort", then
2453 * expand the sparse index.
2455 if (opts->strategy && strcmp(opts->strategy, "ort"))
2456 ensure_full_index(r->index);
2457 return 0;
2460 void todo_list_release(struct todo_list *todo_list)
2462 strbuf_release(&todo_list->buf);
2463 FREE_AND_NULL(todo_list->items);
2464 todo_list->nr = todo_list->alloc = 0;
2467 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2469 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2470 todo_list->total_nr++;
2471 return todo_list->items + todo_list->nr++;
2474 const char *todo_item_get_arg(struct todo_list *todo_list,
2475 struct todo_item *item)
2477 return todo_list->buf.buf + item->arg_offset;
2480 static int is_command(enum todo_command command, const char **bol)
2482 const char *str = todo_command_info[command].str;
2483 const char nick = todo_command_info[command].c;
2484 const char *p = *bol + 1;
2486 return skip_prefix(*bol, str, bol) ||
2487 ((nick && **bol == nick) &&
2488 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2489 (*bol = p));
2492 static int parse_insn_line(struct repository *r, struct todo_item *item,
2493 const char *buf, const char *bol, char *eol)
2495 struct object_id commit_oid;
2496 char *end_of_object_name;
2497 int i, saved, status, padding;
2499 item->flags = 0;
2501 /* left-trim */
2502 bol += strspn(bol, " \t");
2504 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2505 item->command = TODO_COMMENT;
2506 item->commit = NULL;
2507 item->arg_offset = bol - buf;
2508 item->arg_len = eol - bol;
2509 return 0;
2512 for (i = 0; i < TODO_COMMENT; i++)
2513 if (is_command(i, &bol)) {
2514 item->command = i;
2515 break;
2517 if (i >= TODO_COMMENT)
2518 return -1;
2520 /* Eat up extra spaces/ tabs before object name */
2521 padding = strspn(bol, " \t");
2522 bol += padding;
2524 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2525 if (bol != eol)
2526 return error(_("%s does not accept arguments: '%s'"),
2527 command_to_string(item->command), bol);
2528 item->commit = NULL;
2529 item->arg_offset = bol - buf;
2530 item->arg_len = eol - bol;
2531 return 0;
2534 if (!padding)
2535 return error(_("missing arguments for %s"),
2536 command_to_string(item->command));
2538 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2539 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2540 item->commit = NULL;
2541 item->arg_offset = bol - buf;
2542 item->arg_len = (int)(eol - bol);
2543 return 0;
2546 if (item->command == TODO_FIXUP) {
2547 if (skip_prefix(bol, "-C", &bol) &&
2548 (*bol == ' ' || *bol == '\t')) {
2549 bol += strspn(bol, " \t");
2550 item->flags |= TODO_REPLACE_FIXUP_MSG;
2551 } else if (skip_prefix(bol, "-c", &bol) &&
2552 (*bol == ' ' || *bol == '\t')) {
2553 bol += strspn(bol, " \t");
2554 item->flags |= TODO_EDIT_FIXUP_MSG;
2558 if (item->command == TODO_MERGE) {
2559 if (skip_prefix(bol, "-C", &bol))
2560 bol += strspn(bol, " \t");
2561 else if (skip_prefix(bol, "-c", &bol)) {
2562 bol += strspn(bol, " \t");
2563 item->flags |= TODO_EDIT_MERGE_MSG;
2564 } else {
2565 item->flags |= TODO_EDIT_MERGE_MSG;
2566 item->commit = NULL;
2567 item->arg_offset = bol - buf;
2568 item->arg_len = (int)(eol - bol);
2569 return 0;
2573 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2574 saved = *end_of_object_name;
2575 *end_of_object_name = '\0';
2576 status = get_oid(bol, &commit_oid);
2577 if (status < 0)
2578 error(_("could not parse '%s'"), bol); /* return later */
2579 *end_of_object_name = saved;
2581 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2582 item->arg_offset = bol - buf;
2583 item->arg_len = (int)(eol - bol);
2585 if (status < 0)
2586 return status;
2588 item->commit = lookup_commit_reference(r, &commit_oid);
2589 return item->commit ? 0 : -1;
2592 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2594 const char *todo_file, *bol;
2595 struct strbuf buf = STRBUF_INIT;
2596 int ret = 0;
2598 todo_file = git_path_todo_file();
2599 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2600 if (errno == ENOENT || errno == ENOTDIR)
2601 return -1;
2602 else
2603 return error_errno("unable to open '%s'", todo_file);
2605 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2606 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2607 *action = REPLAY_PICK;
2608 else if (is_command(TODO_REVERT, &bol) &&
2609 (*bol == ' ' || *bol == '\t'))
2610 *action = REPLAY_REVERT;
2611 else
2612 ret = -1;
2614 strbuf_release(&buf);
2616 return ret;
2619 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2620 struct todo_list *todo_list)
2622 struct todo_item *item;
2623 char *p = buf, *next_p;
2624 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2626 todo_list->current = todo_list->nr = 0;
2628 for (i = 1; *p; i++, p = next_p) {
2629 char *eol = strchrnul(p, '\n');
2631 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2633 if (p != eol && eol[-1] == '\r')
2634 eol--; /* strip Carriage Return */
2636 item = append_new_todo(todo_list);
2637 item->offset_in_buf = p - todo_list->buf.buf;
2638 if (parse_insn_line(r, item, buf, p, eol)) {
2639 res = error(_("invalid line %d: %.*s"),
2640 i, (int)(eol - p), p);
2641 item->command = TODO_COMMENT + 1;
2642 item->arg_offset = p - buf;
2643 item->arg_len = (int)(eol - p);
2644 item->commit = NULL;
2647 if (fixup_okay)
2648 ; /* do nothing */
2649 else if (is_fixup(item->command))
2650 return error(_("cannot '%s' without a previous commit"),
2651 command_to_string(item->command));
2652 else if (!is_noop(item->command))
2653 fixup_okay = 1;
2656 return res;
2659 static int count_commands(struct todo_list *todo_list)
2661 int count = 0, i;
2663 for (i = 0; i < todo_list->nr; i++)
2664 if (todo_list->items[i].command != TODO_COMMENT)
2665 count++;
2667 return count;
2670 static int get_item_line_offset(struct todo_list *todo_list, int index)
2672 return index < todo_list->nr ?
2673 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2676 static const char *get_item_line(struct todo_list *todo_list, int index)
2678 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2681 static int get_item_line_length(struct todo_list *todo_list, int index)
2683 return get_item_line_offset(todo_list, index + 1)
2684 - get_item_line_offset(todo_list, index);
2687 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2689 int fd;
2690 ssize_t len;
2692 fd = open(path, O_RDONLY);
2693 if (fd < 0)
2694 return error_errno(_("could not open '%s'"), path);
2695 len = strbuf_read(sb, fd, 0);
2696 close(fd);
2697 if (len < 0)
2698 return error(_("could not read '%s'."), path);
2699 return len;
2702 static int have_finished_the_last_pick(void)
2704 struct strbuf buf = STRBUF_INIT;
2705 const char *eol;
2706 const char *todo_path = git_path_todo_file();
2707 int ret = 0;
2709 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2710 if (errno == ENOENT) {
2711 return 0;
2712 } else {
2713 error_errno("unable to open '%s'", todo_path);
2714 return 0;
2717 /* If there is only one line then we are done */
2718 eol = strchr(buf.buf, '\n');
2719 if (!eol || !eol[1])
2720 ret = 1;
2722 strbuf_release(&buf);
2724 return ret;
2727 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2729 struct replay_opts opts = REPLAY_OPTS_INIT;
2730 int need_cleanup = 0;
2732 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2733 if (!refs_delete_ref(get_main_ref_store(r), "",
2734 "CHERRY_PICK_HEAD", NULL, 0) &&
2735 verbose)
2736 warning(_("cancelling a cherry picking in progress"));
2737 opts.action = REPLAY_PICK;
2738 need_cleanup = 1;
2741 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2742 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2743 NULL, 0) &&
2744 verbose)
2745 warning(_("cancelling a revert in progress"));
2746 opts.action = REPLAY_REVERT;
2747 need_cleanup = 1;
2750 unlink(git_path_auto_merge(r));
2752 if (!need_cleanup)
2753 return;
2755 if (!have_finished_the_last_pick())
2756 return;
2758 sequencer_remove_state(&opts);
2761 static void todo_list_write_total_nr(struct todo_list *todo_list)
2763 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2765 if (f) {
2766 fprintf(f, "%d\n", todo_list->total_nr);
2767 fclose(f);
2771 static int read_populate_todo(struct repository *r,
2772 struct todo_list *todo_list,
2773 struct replay_opts *opts)
2775 const char *todo_file = get_todo_path(opts);
2776 int res;
2778 strbuf_reset(&todo_list->buf);
2779 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2780 return -1;
2782 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2783 if (res) {
2784 if (is_rebase_i(opts))
2785 return error(_("please fix this using "
2786 "'git rebase --edit-todo'."));
2787 return error(_("unusable instruction sheet: '%s'"), todo_file);
2790 if (!todo_list->nr &&
2791 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2792 return error(_("no commits parsed."));
2794 if (!is_rebase_i(opts)) {
2795 enum todo_command valid =
2796 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2797 int i;
2799 for (i = 0; i < todo_list->nr; i++)
2800 if (valid == todo_list->items[i].command)
2801 continue;
2802 else if (valid == TODO_PICK)
2803 return error(_("cannot cherry-pick during a revert."));
2804 else
2805 return error(_("cannot revert during a cherry-pick."));
2808 if (is_rebase_i(opts)) {
2809 struct todo_list done = TODO_LIST_INIT;
2811 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2812 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2813 todo_list->done_nr = count_commands(&done);
2814 else
2815 todo_list->done_nr = 0;
2817 todo_list->total_nr = todo_list->done_nr
2818 + count_commands(todo_list);
2819 todo_list_release(&done);
2821 todo_list_write_total_nr(todo_list);
2824 return 0;
2827 static int git_config_string_dup(char **dest,
2828 const char *var, const char *value)
2830 if (!value)
2831 return config_error_nonbool(var);
2832 free(*dest);
2833 *dest = xstrdup(value);
2834 return 0;
2837 static int populate_opts_cb(const char *key, const char *value, void *data)
2839 struct replay_opts *opts = data;
2840 int error_flag = 1;
2842 if (!value)
2843 error_flag = 0;
2844 else if (!strcmp(key, "options.no-commit"))
2845 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2846 else if (!strcmp(key, "options.edit"))
2847 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2848 else if (!strcmp(key, "options.allow-empty"))
2849 opts->allow_empty =
2850 git_config_bool_or_int(key, value, &error_flag);
2851 else if (!strcmp(key, "options.allow-empty-message"))
2852 opts->allow_empty_message =
2853 git_config_bool_or_int(key, value, &error_flag);
2854 else if (!strcmp(key, "options.keep-redundant-commits"))
2855 opts->keep_redundant_commits =
2856 git_config_bool_or_int(key, value, &error_flag);
2857 else if (!strcmp(key, "options.signoff"))
2858 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2859 else if (!strcmp(key, "options.record-origin"))
2860 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2861 else if (!strcmp(key, "options.allow-ff"))
2862 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2863 else if (!strcmp(key, "options.mainline"))
2864 opts->mainline = git_config_int(key, value);
2865 else if (!strcmp(key, "options.strategy"))
2866 git_config_string_dup(&opts->strategy, key, value);
2867 else if (!strcmp(key, "options.gpg-sign"))
2868 git_config_string_dup(&opts->gpg_sign, key, value);
2869 else if (!strcmp(key, "options.strategy-option")) {
2870 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2871 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2872 } else if (!strcmp(key, "options.allow-rerere-auto"))
2873 opts->allow_rerere_auto =
2874 git_config_bool_or_int(key, value, &error_flag) ?
2875 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2876 else if (!strcmp(key, "options.default-msg-cleanup")) {
2877 opts->explicit_cleanup = 1;
2878 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2879 } else
2880 return error(_("invalid key: %s"), key);
2882 if (!error_flag)
2883 return error(_("invalid value for '%s': '%s'"), key, value);
2885 return 0;
2888 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2890 int i;
2891 char *strategy_opts_string = raw_opts;
2893 if (*strategy_opts_string == ' ')
2894 strategy_opts_string++;
2896 opts->xopts_nr = split_cmdline(strategy_opts_string,
2897 (const char ***)&opts->xopts);
2898 for (i = 0; i < opts->xopts_nr; i++) {
2899 const char *arg = opts->xopts[i];
2901 skip_prefix(arg, "--", &arg);
2902 opts->xopts[i] = xstrdup(arg);
2906 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2908 strbuf_reset(buf);
2909 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2910 return;
2911 free(opts->strategy);
2912 opts->strategy = strbuf_detach(buf, NULL);
2913 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2914 return;
2916 parse_strategy_opts(opts, buf->buf);
2919 static int read_populate_opts(struct replay_opts *opts)
2921 if (is_rebase_i(opts)) {
2922 struct strbuf buf = STRBUF_INIT;
2923 int ret = 0;
2925 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2926 READ_ONELINER_SKIP_IF_EMPTY)) {
2927 if (!starts_with(buf.buf, "-S"))
2928 strbuf_reset(&buf);
2929 else {
2930 free(opts->gpg_sign);
2931 opts->gpg_sign = xstrdup(buf.buf + 2);
2933 strbuf_reset(&buf);
2936 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2937 READ_ONELINER_SKIP_IF_EMPTY)) {
2938 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2939 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2940 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2941 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2942 strbuf_reset(&buf);
2945 if (file_exists(rebase_path_verbose()))
2946 opts->verbose = 1;
2948 if (file_exists(rebase_path_quiet()))
2949 opts->quiet = 1;
2951 if (file_exists(rebase_path_signoff())) {
2952 opts->allow_ff = 0;
2953 opts->signoff = 1;
2956 if (file_exists(rebase_path_cdate_is_adate())) {
2957 opts->allow_ff = 0;
2958 opts->committer_date_is_author_date = 1;
2961 if (file_exists(rebase_path_ignore_date())) {
2962 opts->allow_ff = 0;
2963 opts->ignore_date = 1;
2966 if (file_exists(rebase_path_reschedule_failed_exec()))
2967 opts->reschedule_failed_exec = 1;
2968 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2969 opts->reschedule_failed_exec = 0;
2971 if (file_exists(rebase_path_drop_redundant_commits()))
2972 opts->drop_redundant_commits = 1;
2974 if (file_exists(rebase_path_keep_redundant_commits()))
2975 opts->keep_redundant_commits = 1;
2977 read_strategy_opts(opts, &buf);
2978 strbuf_reset(&buf);
2980 if (read_oneliner(&opts->current_fixups,
2981 rebase_path_current_fixups(),
2982 READ_ONELINER_SKIP_IF_EMPTY)) {
2983 const char *p = opts->current_fixups.buf;
2984 opts->current_fixup_count = 1;
2985 while ((p = strchr(p, '\n'))) {
2986 opts->current_fixup_count++;
2987 p++;
2991 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2992 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2993 ret = error(_("unusable squash-onto"));
2994 goto done_rebase_i;
2996 opts->have_squash_onto = 1;
2999 done_rebase_i:
3000 strbuf_release(&buf);
3001 return ret;
3004 if (!file_exists(git_path_opts_file()))
3005 return 0;
3007 * The function git_parse_source(), called from git_config_from_file(),
3008 * may die() in case of a syntactically incorrect file. We do not care
3009 * about this case, though, because we wrote that file ourselves, so we
3010 * are pretty certain that it is syntactically correct.
3012 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3013 return error(_("malformed options sheet: '%s'"),
3014 git_path_opts_file());
3015 return 0;
3018 static void write_strategy_opts(struct replay_opts *opts)
3020 int i;
3021 struct strbuf buf = STRBUF_INIT;
3023 for (i = 0; i < opts->xopts_nr; ++i)
3024 strbuf_addf(&buf, " --%s", opts->xopts[i]);
3026 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3027 strbuf_release(&buf);
3030 int write_basic_state(struct replay_opts *opts, const char *head_name,
3031 struct commit *onto, const struct object_id *orig_head)
3033 if (head_name)
3034 write_file(rebase_path_head_name(), "%s\n", head_name);
3035 if (onto)
3036 write_file(rebase_path_onto(), "%s\n",
3037 oid_to_hex(&onto->object.oid));
3038 if (orig_head)
3039 write_file(rebase_path_orig_head(), "%s\n",
3040 oid_to_hex(orig_head));
3042 if (opts->quiet)
3043 write_file(rebase_path_quiet(), "%s", "");
3044 if (opts->verbose)
3045 write_file(rebase_path_verbose(), "%s", "");
3046 if (opts->strategy)
3047 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3048 if (opts->xopts_nr > 0)
3049 write_strategy_opts(opts);
3051 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3052 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3053 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3054 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3056 if (opts->gpg_sign)
3057 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3058 if (opts->signoff)
3059 write_file(rebase_path_signoff(), "--signoff\n");
3060 if (opts->drop_redundant_commits)
3061 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3062 if (opts->keep_redundant_commits)
3063 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3064 if (opts->committer_date_is_author_date)
3065 write_file(rebase_path_cdate_is_adate(), "%s", "");
3066 if (opts->ignore_date)
3067 write_file(rebase_path_ignore_date(), "%s", "");
3068 if (opts->reschedule_failed_exec)
3069 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3070 else
3071 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3073 return 0;
3076 static int walk_revs_populate_todo(struct todo_list *todo_list,
3077 struct replay_opts *opts)
3079 enum todo_command command = opts->action == REPLAY_PICK ?
3080 TODO_PICK : TODO_REVERT;
3081 const char *command_string = todo_command_info[command].str;
3082 const char *encoding;
3083 struct commit *commit;
3085 if (prepare_revs(opts))
3086 return -1;
3088 encoding = get_log_output_encoding();
3090 while ((commit = get_revision(opts->revs))) {
3091 struct todo_item *item = append_new_todo(todo_list);
3092 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3093 const char *subject;
3094 int subject_len;
3096 item->command = command;
3097 item->commit = commit;
3098 item->arg_offset = 0;
3099 item->arg_len = 0;
3100 item->offset_in_buf = todo_list->buf.len;
3101 subject_len = find_commit_subject(commit_buffer, &subject);
3102 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3103 short_commit_name(commit), subject_len, subject);
3104 unuse_commit_buffer(commit, commit_buffer);
3107 if (!todo_list->nr)
3108 return error(_("empty commit set passed"));
3110 return 0;
3113 static int create_seq_dir(struct repository *r)
3115 enum replay_action action;
3116 const char *in_progress_error = NULL;
3117 const char *in_progress_advice = NULL;
3118 unsigned int advise_skip =
3119 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3120 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3122 if (!sequencer_get_last_command(r, &action)) {
3123 switch (action) {
3124 case REPLAY_REVERT:
3125 in_progress_error = _("revert is already in progress");
3126 in_progress_advice =
3127 _("try \"git revert (--continue | %s--abort | --quit)\"");
3128 break;
3129 case REPLAY_PICK:
3130 in_progress_error = _("cherry-pick is already in progress");
3131 in_progress_advice =
3132 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3133 break;
3134 default:
3135 BUG("unexpected action in create_seq_dir");
3138 if (in_progress_error) {
3139 error("%s", in_progress_error);
3140 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3141 advise(in_progress_advice,
3142 advise_skip ? "--skip | " : "");
3143 return -1;
3145 if (mkdir(git_path_seq_dir(), 0777) < 0)
3146 return error_errno(_("could not create sequencer directory '%s'"),
3147 git_path_seq_dir());
3149 return 0;
3152 static int save_head(const char *head)
3154 struct lock_file head_lock = LOCK_INIT;
3155 struct strbuf buf = STRBUF_INIT;
3156 int fd;
3157 ssize_t written;
3159 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3160 if (fd < 0)
3161 return error_errno(_("could not lock HEAD"));
3162 strbuf_addf(&buf, "%s\n", head);
3163 written = write_in_full(fd, buf.buf, buf.len);
3164 strbuf_release(&buf);
3165 if (written < 0) {
3166 error_errno(_("could not write to '%s'"), git_path_head_file());
3167 rollback_lock_file(&head_lock);
3168 return -1;
3170 if (commit_lock_file(&head_lock) < 0)
3171 return error(_("failed to finalize '%s'"), git_path_head_file());
3172 return 0;
3175 static int rollback_is_safe(void)
3177 struct strbuf sb = STRBUF_INIT;
3178 struct object_id expected_head, actual_head;
3180 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3181 strbuf_trim(&sb);
3182 if (get_oid_hex(sb.buf, &expected_head)) {
3183 strbuf_release(&sb);
3184 die(_("could not parse %s"), git_path_abort_safety_file());
3186 strbuf_release(&sb);
3188 else if (errno == ENOENT)
3189 oidclr(&expected_head);
3190 else
3191 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3193 if (get_oid("HEAD", &actual_head))
3194 oidclr(&actual_head);
3196 return oideq(&actual_head, &expected_head);
3199 static int reset_merge(const struct object_id *oid)
3201 struct child_process cmd = CHILD_PROCESS_INIT;
3203 cmd.git_cmd = 1;
3204 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3206 if (!is_null_oid(oid))
3207 strvec_push(&cmd.args, oid_to_hex(oid));
3209 return run_command(&cmd);
3212 static int rollback_single_pick(struct repository *r)
3214 struct object_id head_oid;
3216 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3217 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3218 return error(_("no cherry-pick or revert in progress"));
3219 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3220 return error(_("cannot resolve HEAD"));
3221 if (is_null_oid(&head_oid))
3222 return error(_("cannot abort from a branch yet to be born"));
3223 return reset_merge(&head_oid);
3226 static int skip_single_pick(void)
3228 struct object_id head;
3230 if (read_ref_full("HEAD", 0, &head, NULL))
3231 return error(_("cannot resolve HEAD"));
3232 return reset_merge(&head);
3235 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3237 FILE *f;
3238 struct object_id oid;
3239 struct strbuf buf = STRBUF_INIT;
3240 const char *p;
3242 f = fopen(git_path_head_file(), "r");
3243 if (!f && errno == ENOENT) {
3245 * There is no multiple-cherry-pick in progress.
3246 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3247 * a single-cherry-pick in progress, abort that.
3249 return rollback_single_pick(r);
3251 if (!f)
3252 return error_errno(_("cannot open '%s'"), git_path_head_file());
3253 if (strbuf_getline_lf(&buf, f)) {
3254 error(_("cannot read '%s': %s"), git_path_head_file(),
3255 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3256 fclose(f);
3257 goto fail;
3259 fclose(f);
3260 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3261 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3262 git_path_head_file());
3263 goto fail;
3265 if (is_null_oid(&oid)) {
3266 error(_("cannot abort from a branch yet to be born"));
3267 goto fail;
3270 if (!rollback_is_safe()) {
3271 /* Do not error, just do not rollback */
3272 warning(_("You seem to have moved HEAD. "
3273 "Not rewinding, check your HEAD!"));
3274 } else
3275 if (reset_merge(&oid))
3276 goto fail;
3277 strbuf_release(&buf);
3278 return sequencer_remove_state(opts);
3279 fail:
3280 strbuf_release(&buf);
3281 return -1;
3284 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3286 enum replay_action action = -1;
3287 sequencer_get_last_command(r, &action);
3290 * Check whether the subcommand requested to skip the commit is actually
3291 * in progress and that it's safe to skip the commit.
3293 * opts->action tells us which subcommand requested to skip the commit.
3294 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3295 * action is in progress and we can skip the commit.
3297 * Otherwise we check that the last instruction was related to the
3298 * particular subcommand we're trying to execute and barf if that's not
3299 * the case.
3301 * Finally we check that the rollback is "safe", i.e., has the HEAD
3302 * moved? In this case, it doesn't make sense to "reset the merge" and
3303 * "skip the commit" as the user already handled this by committing. But
3304 * we'd not want to barf here, instead give advice on how to proceed. We
3305 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3306 * it gets removed when the user commits, so if it still exists we're
3307 * sure the user can't have committed before.
3309 switch (opts->action) {
3310 case REPLAY_REVERT:
3311 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3312 if (action != REPLAY_REVERT)
3313 return error(_("no revert in progress"));
3314 if (!rollback_is_safe())
3315 goto give_advice;
3317 break;
3318 case REPLAY_PICK:
3319 if (!refs_ref_exists(get_main_ref_store(r),
3320 "CHERRY_PICK_HEAD")) {
3321 if (action != REPLAY_PICK)
3322 return error(_("no cherry-pick in progress"));
3323 if (!rollback_is_safe())
3324 goto give_advice;
3326 break;
3327 default:
3328 BUG("unexpected action in sequencer_skip");
3331 if (skip_single_pick())
3332 return error(_("failed to skip the commit"));
3333 if (!is_directory(git_path_seq_dir()))
3334 return 0;
3336 return sequencer_continue(r, opts);
3338 give_advice:
3339 error(_("there is nothing to skip"));
3341 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3342 advise(_("have you committed already?\n"
3343 "try \"git %s --continue\""),
3344 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3346 return -1;
3349 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3351 struct lock_file todo_lock = LOCK_INIT;
3352 const char *todo_path = get_todo_path(opts);
3353 int next = todo_list->current, offset, fd;
3356 * rebase -i writes "git-rebase-todo" without the currently executing
3357 * command, appending it to "done" instead.
3359 if (is_rebase_i(opts))
3360 next++;
3362 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3363 if (fd < 0)
3364 return error_errno(_("could not lock '%s'"), todo_path);
3365 offset = get_item_line_offset(todo_list, next);
3366 if (write_in_full(fd, todo_list->buf.buf + offset,
3367 todo_list->buf.len - offset) < 0)
3368 return error_errno(_("could not write to '%s'"), todo_path);
3369 if (commit_lock_file(&todo_lock) < 0)
3370 return error(_("failed to finalize '%s'"), todo_path);
3372 if (is_rebase_i(opts) && next > 0) {
3373 const char *done = rebase_path_done();
3374 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3375 int ret = 0;
3377 if (fd < 0)
3378 return 0;
3379 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3380 get_item_line_length(todo_list, next - 1))
3381 < 0)
3382 ret = error_errno(_("could not write to '%s'"), done);
3383 if (close(fd) < 0)
3384 ret = error_errno(_("failed to finalize '%s'"), done);
3385 return ret;
3387 return 0;
3390 static int save_opts(struct replay_opts *opts)
3392 const char *opts_file = git_path_opts_file();
3393 int res = 0;
3395 if (opts->no_commit)
3396 res |= git_config_set_in_file_gently(opts_file,
3397 "options.no-commit", "true");
3398 if (opts->edit >= 0)
3399 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3400 opts->edit ? "true" : "false");
3401 if (opts->allow_empty)
3402 res |= git_config_set_in_file_gently(opts_file,
3403 "options.allow-empty", "true");
3404 if (opts->allow_empty_message)
3405 res |= git_config_set_in_file_gently(opts_file,
3406 "options.allow-empty-message", "true");
3407 if (opts->keep_redundant_commits)
3408 res |= git_config_set_in_file_gently(opts_file,
3409 "options.keep-redundant-commits", "true");
3410 if (opts->signoff)
3411 res |= git_config_set_in_file_gently(opts_file,
3412 "options.signoff", "true");
3413 if (opts->record_origin)
3414 res |= git_config_set_in_file_gently(opts_file,
3415 "options.record-origin", "true");
3416 if (opts->allow_ff)
3417 res |= git_config_set_in_file_gently(opts_file,
3418 "options.allow-ff", "true");
3419 if (opts->mainline) {
3420 struct strbuf buf = STRBUF_INIT;
3421 strbuf_addf(&buf, "%d", opts->mainline);
3422 res |= git_config_set_in_file_gently(opts_file,
3423 "options.mainline", buf.buf);
3424 strbuf_release(&buf);
3426 if (opts->strategy)
3427 res |= git_config_set_in_file_gently(opts_file,
3428 "options.strategy", opts->strategy);
3429 if (opts->gpg_sign)
3430 res |= git_config_set_in_file_gently(opts_file,
3431 "options.gpg-sign", opts->gpg_sign);
3432 if (opts->xopts) {
3433 int i;
3434 for (i = 0; i < opts->xopts_nr; i++)
3435 res |= git_config_set_multivar_in_file_gently(opts_file,
3436 "options.strategy-option",
3437 opts->xopts[i], "^$", 0);
3439 if (opts->allow_rerere_auto)
3440 res |= git_config_set_in_file_gently(opts_file,
3441 "options.allow-rerere-auto",
3442 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3443 "true" : "false");
3445 if (opts->explicit_cleanup)
3446 res |= git_config_set_in_file_gently(opts_file,
3447 "options.default-msg-cleanup",
3448 describe_cleanup_mode(opts->default_msg_cleanup));
3449 return res;
3452 static int make_patch(struct repository *r,
3453 struct commit *commit,
3454 struct replay_opts *opts)
3456 struct strbuf buf = STRBUF_INIT;
3457 struct rev_info log_tree_opt;
3458 const char *subject;
3459 char hex[GIT_MAX_HEXSZ + 1];
3460 int res = 0;
3462 oid_to_hex_r(hex, &commit->object.oid);
3463 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3464 return -1;
3465 res |= write_rebase_head(&commit->object.oid);
3467 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3468 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3469 repo_init_revisions(r, &log_tree_opt, NULL);
3470 log_tree_opt.abbrev = 0;
3471 log_tree_opt.diff = 1;
3472 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3473 log_tree_opt.disable_stdin = 1;
3474 log_tree_opt.no_commit_id = 1;
3475 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3476 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3477 if (!log_tree_opt.diffopt.file)
3478 res |= error_errno(_("could not open '%s'"), buf.buf);
3479 else {
3480 res |= log_tree_commit(&log_tree_opt, commit);
3481 fclose(log_tree_opt.diffopt.file);
3483 strbuf_reset(&buf);
3485 strbuf_addf(&buf, "%s/message", get_dir(opts));
3486 if (!file_exists(buf.buf)) {
3487 const char *encoding = get_commit_output_encoding();
3488 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3489 find_commit_subject(commit_buffer, &subject);
3490 res |= write_message(subject, strlen(subject), buf.buf, 1);
3491 unuse_commit_buffer(commit, commit_buffer);
3493 strbuf_release(&buf);
3494 release_revisions(&log_tree_opt);
3496 return res;
3499 static int intend_to_amend(void)
3501 struct object_id head;
3502 char *p;
3504 if (get_oid("HEAD", &head))
3505 return error(_("cannot read HEAD"));
3507 p = oid_to_hex(&head);
3508 return write_message(p, strlen(p), rebase_path_amend(), 1);
3511 static int error_with_patch(struct repository *r,
3512 struct commit *commit,
3513 const char *subject, int subject_len,
3514 struct replay_opts *opts,
3515 int exit_code, int to_amend)
3517 if (commit) {
3518 if (make_patch(r, commit, opts))
3519 return -1;
3520 } else if (copy_file(rebase_path_message(),
3521 git_path_merge_msg(r), 0666))
3522 return error(_("unable to copy '%s' to '%s'"),
3523 git_path_merge_msg(r), rebase_path_message());
3525 if (to_amend) {
3526 if (intend_to_amend())
3527 return -1;
3529 fprintf(stderr,
3530 _("You can amend the commit now, with\n"
3531 "\n"
3532 " git commit --amend %s\n"
3533 "\n"
3534 "Once you are satisfied with your changes, run\n"
3535 "\n"
3536 " git rebase --continue\n"),
3537 gpg_sign_opt_quoted(opts));
3538 } else if (exit_code) {
3539 if (commit)
3540 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3541 short_commit_name(commit), subject_len, subject);
3542 else
3544 * We don't have the hash of the parent so
3545 * just print the line from the todo file.
3547 fprintf_ln(stderr, _("Could not merge %.*s"),
3548 subject_len, subject);
3551 return exit_code;
3554 static int error_failed_squash(struct repository *r,
3555 struct commit *commit,
3556 struct replay_opts *opts,
3557 int subject_len,
3558 const char *subject)
3560 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3561 return error(_("could not copy '%s' to '%s'"),
3562 rebase_path_squash_msg(), rebase_path_message());
3563 unlink(git_path_merge_msg(r));
3564 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3565 return error(_("could not copy '%s' to '%s'"),
3566 rebase_path_message(),
3567 git_path_merge_msg(r));
3568 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3571 static int do_exec(struct repository *r, const char *command_line)
3573 struct child_process cmd = CHILD_PROCESS_INIT;
3574 int dirty, status;
3576 fprintf(stderr, _("Executing: %s\n"), command_line);
3577 cmd.use_shell = 1;
3578 strvec_push(&cmd.args, command_line);
3579 status = run_command(&cmd);
3581 /* force re-reading of the cache */
3582 discard_index(r->index);
3583 if (repo_read_index(r) < 0)
3584 return error(_("could not read index"));
3586 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3588 if (status) {
3589 warning(_("execution failed: %s\n%s"
3590 "You can fix the problem, and then run\n"
3591 "\n"
3592 " git rebase --continue\n"
3593 "\n"),
3594 command_line,
3595 dirty ? N_("and made changes to the index and/or the "
3596 "working tree\n") : "");
3597 if (status == 127)
3598 /* command not found */
3599 status = 1;
3600 } else if (dirty) {
3601 warning(_("execution succeeded: %s\nbut "
3602 "left changes to the index and/or the working tree\n"
3603 "Commit or stash your changes, and then run\n"
3604 "\n"
3605 " git rebase --continue\n"
3606 "\n"), command_line);
3607 status = 1;
3610 return status;
3613 __attribute__((format (printf, 2, 3)))
3614 static int safe_append(const char *filename, const char *fmt, ...)
3616 va_list ap;
3617 struct lock_file lock = LOCK_INIT;
3618 int fd = hold_lock_file_for_update(&lock, filename,
3619 LOCK_REPORT_ON_ERROR);
3620 struct strbuf buf = STRBUF_INIT;
3622 if (fd < 0)
3623 return -1;
3625 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3626 error_errno(_("could not read '%s'"), filename);
3627 rollback_lock_file(&lock);
3628 return -1;
3630 strbuf_complete(&buf, '\n');
3631 va_start(ap, fmt);
3632 strbuf_vaddf(&buf, fmt, ap);
3633 va_end(ap);
3635 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3636 error_errno(_("could not write to '%s'"), filename);
3637 strbuf_release(&buf);
3638 rollback_lock_file(&lock);
3639 return -1;
3641 if (commit_lock_file(&lock) < 0) {
3642 strbuf_release(&buf);
3643 rollback_lock_file(&lock);
3644 return error(_("failed to finalize '%s'"), filename);
3647 strbuf_release(&buf);
3648 return 0;
3651 static int do_label(struct repository *r, const char *name, int len)
3653 struct ref_store *refs = get_main_ref_store(r);
3654 struct ref_transaction *transaction;
3655 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3656 struct strbuf msg = STRBUF_INIT;
3657 int ret = 0;
3658 struct object_id head_oid;
3660 if (len == 1 && *name == '#')
3661 return error(_("illegal label name: '%.*s'"), len, name);
3663 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3664 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3666 transaction = ref_store_transaction_begin(refs, &err);
3667 if (!transaction) {
3668 error("%s", err.buf);
3669 ret = -1;
3670 } else if (get_oid("HEAD", &head_oid)) {
3671 error(_("could not read HEAD"));
3672 ret = -1;
3673 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3674 NULL, 0, msg.buf, &err) < 0 ||
3675 ref_transaction_commit(transaction, &err)) {
3676 error("%s", err.buf);
3677 ret = -1;
3679 ref_transaction_free(transaction);
3680 strbuf_release(&err);
3681 strbuf_release(&msg);
3683 if (!ret)
3684 ret = safe_append(rebase_path_refs_to_delete(),
3685 "%s\n", ref_name.buf);
3686 strbuf_release(&ref_name);
3688 return ret;
3691 static const char *sequencer_reflog_action(struct replay_opts *opts)
3693 if (!opts->reflog_action) {
3694 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3695 opts->reflog_action =
3696 xstrdup(opts->reflog_action ? opts->reflog_action
3697 : action_name(opts));
3700 return opts->reflog_action;
3703 __attribute__((format (printf, 3, 4)))
3704 static const char *reflog_message(struct replay_opts *opts,
3705 const char *sub_action, const char *fmt, ...)
3707 va_list ap;
3708 static struct strbuf buf = STRBUF_INIT;
3710 va_start(ap, fmt);
3711 strbuf_reset(&buf);
3712 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3713 if (sub_action)
3714 strbuf_addf(&buf, " (%s)", sub_action);
3715 if (fmt) {
3716 strbuf_addstr(&buf, ": ");
3717 strbuf_vaddf(&buf, fmt, ap);
3719 va_end(ap);
3721 return buf.buf;
3724 static struct commit *lookup_label(struct repository *r, const char *label,
3725 int len, struct strbuf *buf)
3727 struct commit *commit;
3728 struct object_id oid;
3730 strbuf_reset(buf);
3731 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3732 if (!read_ref(buf->buf, &oid)) {
3733 commit = lookup_commit_object(r, &oid);
3734 } else {
3735 /* fall back to non-rewritten ref or commit */
3736 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3737 commit = lookup_commit_reference_by_name(buf->buf);
3740 if (!commit)
3741 error(_("could not resolve '%s'"), buf->buf);
3743 return commit;
3746 static int do_reset(struct repository *r,
3747 const char *name, int len,
3748 struct replay_opts *opts)
3750 struct strbuf ref_name = STRBUF_INIT;
3751 struct object_id oid;
3752 struct lock_file lock = LOCK_INIT;
3753 struct tree_desc desc = { 0 };
3754 struct tree *tree;
3755 struct unpack_trees_options unpack_tree_opts = { 0 };
3756 int ret = 0;
3758 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3759 return -1;
3761 if (len == 10 && !strncmp("[new root]", name, len)) {
3762 if (!opts->have_squash_onto) {
3763 const char *hex;
3764 if (commit_tree("", 0, the_hash_algo->empty_tree,
3765 NULL, &opts->squash_onto,
3766 NULL, NULL))
3767 return error(_("writing fake root commit"));
3768 opts->have_squash_onto = 1;
3769 hex = oid_to_hex(&opts->squash_onto);
3770 if (write_message(hex, strlen(hex),
3771 rebase_path_squash_onto(), 0))
3772 return error(_("writing squash-onto"));
3774 oidcpy(&oid, &opts->squash_onto);
3775 } else {
3776 int i;
3777 struct commit *commit;
3779 /* Determine the length of the label */
3780 for (i = 0; i < len; i++)
3781 if (isspace(name[i]))
3782 break;
3783 len = i;
3785 commit = lookup_label(r, name, len, &ref_name);
3786 if (!commit) {
3787 ret = -1;
3788 goto cleanup;
3790 oid = commit->object.oid;
3793 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3794 unpack_tree_opts.head_idx = 1;
3795 unpack_tree_opts.src_index = r->index;
3796 unpack_tree_opts.dst_index = r->index;
3797 unpack_tree_opts.fn = oneway_merge;
3798 unpack_tree_opts.merge = 1;
3799 unpack_tree_opts.update = 1;
3800 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3801 unpack_tree_opts.skip_cache_tree_update = 1;
3802 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3804 if (repo_read_index_unmerged(r)) {
3805 ret = error_resolve_conflict(action_name(opts));
3806 goto cleanup;
3809 if (!fill_tree_descriptor(r, &desc, &oid)) {
3810 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3811 goto cleanup;
3814 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3815 ret = -1;
3816 goto cleanup;
3819 tree = parse_tree_indirect(&oid);
3820 prime_cache_tree(r, r->index, tree);
3822 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3823 ret = error(_("could not write index"));
3825 if (!ret)
3826 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3827 len, name), "HEAD", &oid,
3828 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3829 cleanup:
3830 free((void *)desc.buffer);
3831 if (ret < 0)
3832 rollback_lock_file(&lock);
3833 strbuf_release(&ref_name);
3834 clear_unpack_trees_porcelain(&unpack_tree_opts);
3835 return ret;
3838 static int do_merge(struct repository *r,
3839 struct commit *commit,
3840 const char *arg, int arg_len,
3841 int flags, int *check_todo, struct replay_opts *opts)
3843 int run_commit_flags = 0;
3844 struct strbuf ref_name = STRBUF_INIT;
3845 struct commit *head_commit, *merge_commit, *i;
3846 struct commit_list *bases, *j;
3847 struct commit_list *to_merge = NULL, **tail = &to_merge;
3848 const char *strategy = !opts->xopts_nr &&
3849 (!opts->strategy ||
3850 !strcmp(opts->strategy, "recursive") ||
3851 !strcmp(opts->strategy, "ort")) ?
3852 NULL : opts->strategy;
3853 struct merge_options o;
3854 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3855 static struct lock_file lock;
3856 const char *p;
3858 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3859 ret = -1;
3860 goto leave_merge;
3863 head_commit = lookup_commit_reference_by_name("HEAD");
3864 if (!head_commit) {
3865 ret = error(_("cannot merge without a current revision"));
3866 goto leave_merge;
3870 * For octopus merges, the arg starts with the list of revisions to be
3871 * merged. The list is optionally followed by '#' and the oneline.
3873 merge_arg_len = oneline_offset = arg_len;
3874 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3875 if (!*p)
3876 break;
3877 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3878 p += 1 + strspn(p + 1, " \t\n");
3879 oneline_offset = p - arg;
3880 break;
3882 k = strcspn(p, " \t\n");
3883 if (!k)
3884 continue;
3885 merge_commit = lookup_label(r, p, k, &ref_name);
3886 if (!merge_commit) {
3887 ret = error(_("unable to parse '%.*s'"), k, p);
3888 goto leave_merge;
3890 tail = &commit_list_insert(merge_commit, tail)->next;
3891 p += k;
3892 merge_arg_len = p - arg;
3895 if (!to_merge) {
3896 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3897 goto leave_merge;
3900 if (opts->have_squash_onto &&
3901 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3903 * When the user tells us to "merge" something into a
3904 * "[new root]", let's simply fast-forward to the merge head.
3906 rollback_lock_file(&lock);
3907 if (to_merge->next)
3908 ret = error(_("octopus merge cannot be executed on "
3909 "top of a [new root]"));
3910 else
3911 ret = fast_forward_to(r, &to_merge->item->object.oid,
3912 &head_commit->object.oid, 0,
3913 opts);
3914 goto leave_merge;
3918 * If HEAD is not identical to the first parent of the original merge
3919 * commit, we cannot fast-forward.
3921 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3922 oideq(&commit->parents->item->object.oid,
3923 &head_commit->object.oid);
3926 * If any merge head is different from the original one, we cannot
3927 * fast-forward.
3929 if (can_fast_forward) {
3930 struct commit_list *p = commit->parents->next;
3932 for (j = to_merge; j && p; j = j->next, p = p->next)
3933 if (!oideq(&j->item->object.oid,
3934 &p->item->object.oid)) {
3935 can_fast_forward = 0;
3936 break;
3939 * If the number of merge heads differs from the original merge
3940 * commit, we cannot fast-forward.
3942 if (j || p)
3943 can_fast_forward = 0;
3946 if (can_fast_forward) {
3947 rollback_lock_file(&lock);
3948 ret = fast_forward_to(r, &commit->object.oid,
3949 &head_commit->object.oid, 0, opts);
3950 if (flags & TODO_EDIT_MERGE_MSG)
3951 goto fast_forward_edit;
3953 goto leave_merge;
3956 if (commit) {
3957 const char *encoding = get_commit_output_encoding();
3958 const char *message = logmsg_reencode(commit, NULL, encoding);
3959 const char *body;
3960 int len;
3962 if (!message) {
3963 ret = error(_("could not get commit message of '%s'"),
3964 oid_to_hex(&commit->object.oid));
3965 goto leave_merge;
3967 write_author_script(message);
3968 find_commit_subject(message, &body);
3969 len = strlen(body);
3970 ret = write_message(body, len, git_path_merge_msg(r), 0);
3971 unuse_commit_buffer(commit, message);
3972 if (ret) {
3973 error_errno(_("could not write '%s'"),
3974 git_path_merge_msg(r));
3975 goto leave_merge;
3977 } else {
3978 struct strbuf buf = STRBUF_INIT;
3979 int len;
3981 strbuf_addf(&buf, "author %s", git_author_info(0));
3982 write_author_script(buf.buf);
3983 strbuf_reset(&buf);
3985 if (oneline_offset < arg_len) {
3986 p = arg + oneline_offset;
3987 len = arg_len - oneline_offset;
3988 } else {
3989 strbuf_addf(&buf, "Merge %s '%.*s'",
3990 to_merge->next ? "branches" : "branch",
3991 merge_arg_len, arg);
3992 p = buf.buf;
3993 len = buf.len;
3996 ret = write_message(p, len, git_path_merge_msg(r), 0);
3997 strbuf_release(&buf);
3998 if (ret) {
3999 error_errno(_("could not write '%s'"),
4000 git_path_merge_msg(r));
4001 goto leave_merge;
4005 if (strategy || to_merge->next) {
4006 /* Octopus merge */
4007 struct child_process cmd = CHILD_PROCESS_INIT;
4009 if (read_env_script(&cmd.env)) {
4010 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4012 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4013 goto leave_merge;
4016 if (opts->committer_date_is_author_date)
4017 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4018 opts->ignore_date ?
4019 "" :
4020 author_date_from_env(&cmd.env));
4021 if (opts->ignore_date)
4022 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4024 cmd.git_cmd = 1;
4025 strvec_push(&cmd.args, "merge");
4026 strvec_push(&cmd.args, "-s");
4027 if (!strategy)
4028 strvec_push(&cmd.args, "octopus");
4029 else {
4030 strvec_push(&cmd.args, strategy);
4031 for (k = 0; k < opts->xopts_nr; k++)
4032 strvec_pushf(&cmd.args,
4033 "-X%s", opts->xopts[k]);
4035 if (!(flags & TODO_EDIT_MERGE_MSG))
4036 strvec_push(&cmd.args, "--no-edit");
4037 else
4038 strvec_push(&cmd.args, "--edit");
4039 strvec_push(&cmd.args, "--no-ff");
4040 strvec_push(&cmd.args, "--no-log");
4041 strvec_push(&cmd.args, "--no-stat");
4042 strvec_push(&cmd.args, "-F");
4043 strvec_push(&cmd.args, git_path_merge_msg(r));
4044 if (opts->gpg_sign)
4045 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4046 else
4047 strvec_push(&cmd.args, "--no-gpg-sign");
4049 /* Add the tips to be merged */
4050 for (j = to_merge; j; j = j->next)
4051 strvec_push(&cmd.args,
4052 oid_to_hex(&j->item->object.oid));
4054 strbuf_release(&ref_name);
4055 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4056 NULL, 0);
4057 rollback_lock_file(&lock);
4059 ret = run_command(&cmd);
4061 /* force re-reading of the cache */
4062 if (!ret) {
4063 discard_index(r->index);
4064 if (repo_read_index(r) < 0)
4065 ret = error(_("could not read index"));
4067 goto leave_merge;
4070 merge_commit = to_merge->item;
4071 bases = get_merge_bases(head_commit, merge_commit);
4072 if (bases && oideq(&merge_commit->object.oid,
4073 &bases->item->object.oid)) {
4074 ret = 0;
4075 /* skip merging an ancestor of HEAD */
4076 goto leave_merge;
4079 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4080 git_path_merge_head(r), 0);
4081 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4083 bases = reverse_commit_list(bases);
4085 repo_read_index(r);
4086 init_merge_options(&o, r);
4087 o.branch1 = "HEAD";
4088 o.branch2 = ref_name.buf;
4089 o.buffer_output = 2;
4091 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4093 * TODO: Should use merge_incore_recursive() and
4094 * merge_switch_to_result(), skipping the call to
4095 * merge_switch_to_result() when we don't actually need to
4096 * update the index and working copy immediately.
4098 ret = merge_ort_recursive(&o,
4099 head_commit, merge_commit, bases,
4100 &i);
4101 } else {
4102 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4103 &i);
4105 if (ret <= 0)
4106 fputs(o.obuf.buf, stdout);
4107 strbuf_release(&o.obuf);
4108 if (ret < 0) {
4109 error(_("could not even attempt to merge '%.*s'"),
4110 merge_arg_len, arg);
4111 goto leave_merge;
4114 * The return value of merge_recursive() is 1 on clean, and 0 on
4115 * unclean merge.
4117 * Let's reverse that, so that do_merge() returns 0 upon success and
4118 * 1 upon failed merge (keeping the return value -1 for the cases where
4119 * we will want to reschedule the `merge` command).
4121 ret = !ret;
4123 if (r->index->cache_changed &&
4124 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4125 ret = error(_("merge: Unable to write new index file"));
4126 goto leave_merge;
4129 rollback_lock_file(&lock);
4130 if (ret)
4131 repo_rerere(r, opts->allow_rerere_auto);
4132 else
4134 * In case of problems, we now want to return a positive
4135 * value (a negative one would indicate that the `merge`
4136 * command needs to be rescheduled).
4138 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4139 run_commit_flags);
4141 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4142 fast_forward_edit:
4143 *check_todo = 1;
4144 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4145 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4149 leave_merge:
4150 strbuf_release(&ref_name);
4151 rollback_lock_file(&lock);
4152 free_commit_list(to_merge);
4153 return ret;
4156 static int write_update_refs_state(struct string_list *refs_to_oids)
4158 int result = 0;
4159 struct lock_file lock = LOCK_INIT;
4160 FILE *fp = NULL;
4161 struct string_list_item *item;
4162 char *path;
4164 path = rebase_path_update_refs(the_repository->gitdir);
4166 if (!refs_to_oids->nr) {
4167 if (unlink(path) && errno != ENOENT)
4168 result = error_errno(_("could not unlink: %s"), path);
4169 goto cleanup;
4172 if (safe_create_leading_directories(path)) {
4173 result = error(_("unable to create leading directories of %s"),
4174 path);
4175 goto cleanup;
4178 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4179 result = error(_("another 'rebase' process appears to be running; "
4180 "'%s.lock' already exists"),
4181 path);
4182 goto cleanup;
4185 fp = fdopen_lock_file(&lock, "w");
4186 if (!fp) {
4187 result = error_errno(_("could not open '%s' for writing"), path);
4188 rollback_lock_file(&lock);
4189 goto cleanup;
4192 for_each_string_list_item(item, refs_to_oids) {
4193 struct update_ref_record *rec = item->util;
4194 fprintf(fp, "%s\n%s\n%s\n", item->string,
4195 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4198 result = commit_lock_file(&lock);
4200 cleanup:
4201 free(path);
4202 return result;
4206 * Parse the update-refs file for the current rebase, then remove the
4207 * refs that do not appear in the todo_list (and have not had updated
4208 * values stored) and add refs that are in the todo_list but not
4209 * represented in the update-refs file.
4211 * If there are changes to the update-refs list, then write the new state
4212 * to disk.
4214 void todo_list_filter_update_refs(struct repository *r,
4215 struct todo_list *todo_list)
4217 int i;
4218 int updated = 0;
4219 struct string_list update_refs = STRING_LIST_INIT_DUP;
4221 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4224 * For each item in the update_refs list, if it has no updated
4225 * value and does not appear in the todo_list, then remove it
4226 * from the update_refs list.
4228 for (i = 0; i < update_refs.nr; i++) {
4229 int j;
4230 int found = 0;
4231 const char *ref = update_refs.items[i].string;
4232 size_t reflen = strlen(ref);
4233 struct update_ref_record *rec = update_refs.items[i].util;
4235 /* OID already stored as updated. */
4236 if (!is_null_oid(&rec->after))
4237 continue;
4239 for (j = 0; !found && j < todo_list->total_nr; j++) {
4240 struct todo_item *item = &todo_list->items[j];
4241 const char *arg = todo_list->buf.buf + item->arg_offset;
4243 if (item->command != TODO_UPDATE_REF)
4244 continue;
4246 if (item->arg_len != reflen ||
4247 strncmp(arg, ref, reflen))
4248 continue;
4250 found = 1;
4253 if (!found) {
4254 free(update_refs.items[i].string);
4255 free(update_refs.items[i].util);
4257 update_refs.nr--;
4258 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4260 updated = 1;
4261 i--;
4266 * For each todo_item, check if its ref is in the update_refs list.
4267 * If not, then add it as an un-updated ref.
4269 for (i = 0; i < todo_list->total_nr; i++) {
4270 struct todo_item *item = &todo_list->items[i];
4271 const char *arg = todo_list->buf.buf + item->arg_offset;
4272 int j, found = 0;
4274 if (item->command != TODO_UPDATE_REF)
4275 continue;
4277 for (j = 0; !found && j < update_refs.nr; j++) {
4278 const char *ref = update_refs.items[j].string;
4280 found = strlen(ref) == item->arg_len &&
4281 !strncmp(ref, arg, item->arg_len);
4284 if (!found) {
4285 struct string_list_item *inserted;
4286 struct strbuf argref = STRBUF_INIT;
4288 strbuf_add(&argref, arg, item->arg_len);
4289 inserted = string_list_insert(&update_refs, argref.buf);
4290 inserted->util = init_update_ref_record(argref.buf);
4291 strbuf_release(&argref);
4292 updated = 1;
4296 if (updated)
4297 write_update_refs_state(&update_refs);
4298 string_list_clear(&update_refs, 1);
4301 static int do_update_ref(struct repository *r, const char *refname)
4303 struct string_list_item *item;
4304 struct string_list list = STRING_LIST_INIT_DUP;
4306 if (sequencer_get_update_refs_state(r->gitdir, &list))
4307 return -1;
4309 for_each_string_list_item(item, &list) {
4310 if (!strcmp(item->string, refname)) {
4311 struct update_ref_record *rec = item->util;
4312 if (read_ref("HEAD", &rec->after))
4313 return -1;
4314 break;
4318 write_update_refs_state(&list);
4319 string_list_clear(&list, 1);
4320 return 0;
4323 static int do_update_refs(struct repository *r, int quiet)
4325 int res = 0;
4326 struct string_list_item *item;
4327 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4328 struct ref_store *refs = get_main_ref_store(r);
4329 struct strbuf update_msg = STRBUF_INIT;
4330 struct strbuf error_msg = STRBUF_INIT;
4332 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4333 return res;
4335 for_each_string_list_item(item, &refs_to_oids) {
4336 struct update_ref_record *rec = item->util;
4337 int loop_res;
4339 loop_res = refs_update_ref(refs, "rewritten during rebase",
4340 item->string,
4341 &rec->after, &rec->before,
4342 0, UPDATE_REFS_MSG_ON_ERR);
4343 res |= loop_res;
4345 if (quiet)
4346 continue;
4348 if (loop_res)
4349 strbuf_addf(&error_msg, "\t%s\n", item->string);
4350 else
4351 strbuf_addf(&update_msg, "\t%s\n", item->string);
4354 if (!quiet &&
4355 (update_msg.len || error_msg.len)) {
4356 fprintf(stderr,
4357 _("Updated the following refs with %s:\n%s"),
4358 "--update-refs",
4359 update_msg.buf);
4361 if (res)
4362 fprintf(stderr,
4363 _("Failed to update the following refs with %s:\n%s"),
4364 "--update-refs",
4365 error_msg.buf);
4368 string_list_clear(&refs_to_oids, 1);
4369 strbuf_release(&update_msg);
4370 strbuf_release(&error_msg);
4371 return res;
4374 static int is_final_fixup(struct todo_list *todo_list)
4376 int i = todo_list->current;
4378 if (!is_fixup(todo_list->items[i].command))
4379 return 0;
4381 while (++i < todo_list->nr)
4382 if (is_fixup(todo_list->items[i].command))
4383 return 0;
4384 else if (!is_noop(todo_list->items[i].command))
4385 break;
4386 return 1;
4389 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4391 int i;
4393 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4394 if (!is_noop(todo_list->items[i].command))
4395 return todo_list->items[i].command;
4397 return -1;
4400 void create_autostash(struct repository *r, const char *path)
4402 struct strbuf buf = STRBUF_INIT;
4403 struct lock_file lock_file = LOCK_INIT;
4404 int fd;
4406 fd = repo_hold_locked_index(r, &lock_file, 0);
4407 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4408 if (0 <= fd)
4409 repo_update_index_if_able(r, &lock_file);
4410 rollback_lock_file(&lock_file);
4412 if (has_unstaged_changes(r, 1) ||
4413 has_uncommitted_changes(r, 1)) {
4414 struct child_process stash = CHILD_PROCESS_INIT;
4415 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4416 struct object_id oid;
4418 strvec_pushl(&stash.args,
4419 "stash", "create", "autostash", NULL);
4420 stash.git_cmd = 1;
4421 stash.no_stdin = 1;
4422 strbuf_reset(&buf);
4423 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4424 die(_("Cannot autostash"));
4425 strbuf_trim_trailing_newline(&buf);
4426 if (get_oid(buf.buf, &oid))
4427 die(_("Unexpected stash response: '%s'"),
4428 buf.buf);
4429 strbuf_reset(&buf);
4430 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4432 if (safe_create_leading_directories_const(path))
4433 die(_("Could not create directory for '%s'"),
4434 path);
4435 write_file(path, "%s", oid_to_hex(&oid));
4436 printf(_("Created autostash: %s\n"), buf.buf);
4437 if (reset_head(r, &ropts) < 0)
4438 die(_("could not reset --hard"));
4439 discard_index(r->index);
4440 if (repo_read_index(r) < 0)
4441 die(_("could not read index"));
4443 strbuf_release(&buf);
4446 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4448 struct child_process child = CHILD_PROCESS_INIT;
4449 int ret = 0;
4451 if (attempt_apply) {
4452 child.git_cmd = 1;
4453 child.no_stdout = 1;
4454 child.no_stderr = 1;
4455 strvec_push(&child.args, "stash");
4456 strvec_push(&child.args, "apply");
4457 strvec_push(&child.args, stash_oid);
4458 ret = run_command(&child);
4461 if (attempt_apply && !ret)
4462 fprintf(stderr, _("Applied autostash.\n"));
4463 else {
4464 struct child_process store = CHILD_PROCESS_INIT;
4466 store.git_cmd = 1;
4467 strvec_push(&store.args, "stash");
4468 strvec_push(&store.args, "store");
4469 strvec_push(&store.args, "-m");
4470 strvec_push(&store.args, "autostash");
4471 strvec_push(&store.args, "-q");
4472 strvec_push(&store.args, stash_oid);
4473 if (run_command(&store))
4474 ret = error(_("cannot store %s"), stash_oid);
4475 else
4476 fprintf(stderr,
4477 _("%s\n"
4478 "Your changes are safe in the stash.\n"
4479 "You can run \"git stash pop\" or"
4480 " \"git stash drop\" at any time.\n"),
4481 attempt_apply ?
4482 _("Applying autostash resulted in conflicts.") :
4483 _("Autostash exists; creating a new stash entry."));
4486 return ret;
4489 static int apply_save_autostash(const char *path, int attempt_apply)
4491 struct strbuf stash_oid = STRBUF_INIT;
4492 int ret = 0;
4494 if (!read_oneliner(&stash_oid, path,
4495 READ_ONELINER_SKIP_IF_EMPTY)) {
4496 strbuf_release(&stash_oid);
4497 return 0;
4499 strbuf_trim(&stash_oid);
4501 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4503 unlink(path);
4504 strbuf_release(&stash_oid);
4505 return ret;
4508 int save_autostash(const char *path)
4510 return apply_save_autostash(path, 0);
4513 int apply_autostash(const char *path)
4515 return apply_save_autostash(path, 1);
4518 int apply_autostash_oid(const char *stash_oid)
4520 return apply_save_autostash_oid(stash_oid, 1);
4523 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4524 const char *onto_name, const struct object_id *onto,
4525 const struct object_id *orig_head)
4527 struct reset_head_opts ropts = {
4528 .oid = onto,
4529 .orig_head = orig_head,
4530 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4531 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4532 .head_msg = reflog_message(opts, "start", "checkout %s",
4533 onto_name),
4534 .default_reflog_action = sequencer_reflog_action(opts)
4536 if (reset_head(r, &ropts)) {
4537 apply_autostash(rebase_path_autostash());
4538 sequencer_remove_state(opts);
4539 return error(_("could not detach HEAD"));
4542 return 0;
4545 static int stopped_at_head(struct repository *r)
4547 struct object_id head;
4548 struct commit *commit;
4549 struct commit_message message;
4551 if (get_oid("HEAD", &head) ||
4552 !(commit = lookup_commit(r, &head)) ||
4553 parse_commit(commit) || get_message(commit, &message))
4554 fprintf(stderr, _("Stopped at HEAD\n"));
4555 else {
4556 fprintf(stderr, _("Stopped at %s\n"), message.label);
4557 free_message(commit, &message);
4559 return 0;
4563 static int reread_todo_if_changed(struct repository *r,
4564 struct todo_list *todo_list,
4565 struct replay_opts *opts)
4567 int offset;
4568 struct strbuf buf = STRBUF_INIT;
4570 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4571 return -1;
4572 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4573 if (buf.len != todo_list->buf.len - offset ||
4574 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4575 /* Reread the todo file if it has changed. */
4576 todo_list_release(todo_list);
4577 if (read_populate_todo(r, todo_list, opts))
4578 return -1; /* message was printed */
4579 /* `current` will be incremented on return */
4580 todo_list->current = -1;
4582 strbuf_release(&buf);
4584 return 0;
4587 static const char rescheduled_advice[] =
4588 N_("Could not execute the todo command\n"
4589 "\n"
4590 " %.*s"
4591 "\n"
4592 "It has been rescheduled; To edit the command before continuing, please\n"
4593 "edit the todo list first:\n"
4594 "\n"
4595 " git rebase --edit-todo\n"
4596 " git rebase --continue\n");
4598 static int pick_commits(struct repository *r,
4599 struct todo_list *todo_list,
4600 struct replay_opts *opts)
4602 int res = 0, reschedule = 0;
4604 opts->reflog_message = sequencer_reflog_action(opts);
4605 if (opts->allow_ff)
4606 assert(!(opts->signoff || opts->no_commit ||
4607 opts->record_origin || should_edit(opts) ||
4608 opts->committer_date_is_author_date ||
4609 opts->ignore_date));
4610 if (read_and_refresh_cache(r, opts))
4611 return -1;
4613 while (todo_list->current < todo_list->nr) {
4614 struct todo_item *item = todo_list->items + todo_list->current;
4615 const char *arg = todo_item_get_arg(todo_list, item);
4616 int check_todo = 0;
4618 if (save_todo(todo_list, opts))
4619 return -1;
4620 if (is_rebase_i(opts)) {
4621 if (item->command != TODO_COMMENT) {
4622 FILE *f = fopen(rebase_path_msgnum(), "w");
4624 todo_list->done_nr++;
4626 if (f) {
4627 fprintf(f, "%d\n", todo_list->done_nr);
4628 fclose(f);
4630 if (!opts->quiet)
4631 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4632 todo_list->done_nr,
4633 todo_list->total_nr,
4634 opts->verbose ? "\n" : "\r");
4636 unlink(rebase_path_message());
4637 unlink(rebase_path_author_script());
4638 unlink(rebase_path_stopped_sha());
4639 unlink(rebase_path_amend());
4640 unlink(git_path_merge_head(r));
4641 unlink(git_path_auto_merge(r));
4642 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4644 if (item->command == TODO_BREAK) {
4645 if (!opts->verbose)
4646 term_clear_line();
4647 return stopped_at_head(r);
4650 if (item->command <= TODO_SQUASH) {
4651 if (is_rebase_i(opts))
4652 opts->reflog_message = reflog_message(opts,
4653 command_to_string(item->command), NULL);
4655 res = do_pick_commit(r, item, opts,
4656 is_final_fixup(todo_list),
4657 &check_todo);
4658 if (is_rebase_i(opts) && res < 0) {
4659 /* Reschedule */
4660 advise(_(rescheduled_advice),
4661 get_item_line_length(todo_list,
4662 todo_list->current),
4663 get_item_line(todo_list,
4664 todo_list->current));
4665 todo_list->current--;
4666 if (save_todo(todo_list, opts))
4667 return -1;
4669 if (item->command == TODO_EDIT) {
4670 struct commit *commit = item->commit;
4671 if (!res) {
4672 if (!opts->verbose)
4673 term_clear_line();
4674 fprintf(stderr,
4675 _("Stopped at %s... %.*s\n"),
4676 short_commit_name(commit),
4677 item->arg_len, arg);
4679 return error_with_patch(r, commit,
4680 arg, item->arg_len, opts, res, !res);
4682 if (is_rebase_i(opts) && !res)
4683 record_in_rewritten(&item->commit->object.oid,
4684 peek_command(todo_list, 1));
4685 if (res && is_fixup(item->command)) {
4686 if (res == 1)
4687 intend_to_amend();
4688 return error_failed_squash(r, item->commit, opts,
4689 item->arg_len, arg);
4690 } else if (res && is_rebase_i(opts) && item->commit) {
4691 int to_amend = 0;
4692 struct object_id oid;
4695 * If we are rewording and have either
4696 * fast-forwarded already, or are about to
4697 * create a new root commit, we want to amend,
4698 * otherwise we do not.
4700 if (item->command == TODO_REWORD &&
4701 !get_oid("HEAD", &oid) &&
4702 (oideq(&item->commit->object.oid, &oid) ||
4703 (opts->have_squash_onto &&
4704 oideq(&opts->squash_onto, &oid))))
4705 to_amend = 1;
4707 return res | error_with_patch(r, item->commit,
4708 arg, item->arg_len, opts,
4709 res, to_amend);
4711 } else if (item->command == TODO_EXEC) {
4712 char *end_of_arg = (char *)(arg + item->arg_len);
4713 int saved = *end_of_arg;
4715 if (!opts->verbose)
4716 term_clear_line();
4717 *end_of_arg = '\0';
4718 res = do_exec(r, arg);
4719 *end_of_arg = saved;
4721 if (res) {
4722 if (opts->reschedule_failed_exec)
4723 reschedule = 1;
4725 check_todo = 1;
4726 } else if (item->command == TODO_LABEL) {
4727 if ((res = do_label(r, arg, item->arg_len)))
4728 reschedule = 1;
4729 } else if (item->command == TODO_RESET) {
4730 if ((res = do_reset(r, arg, item->arg_len, opts)))
4731 reschedule = 1;
4732 } else if (item->command == TODO_MERGE) {
4733 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4734 item->flags, &check_todo, opts)) < 0)
4735 reschedule = 1;
4736 else if (item->commit)
4737 record_in_rewritten(&item->commit->object.oid,
4738 peek_command(todo_list, 1));
4739 if (res > 0)
4740 /* failed with merge conflicts */
4741 return error_with_patch(r, item->commit,
4742 arg, item->arg_len,
4743 opts, res, 0);
4744 } else if (item->command == TODO_UPDATE_REF) {
4745 struct strbuf ref = STRBUF_INIT;
4746 strbuf_add(&ref, arg, item->arg_len);
4747 if ((res = do_update_ref(r, ref.buf)))
4748 reschedule = 1;
4749 strbuf_release(&ref);
4750 } else if (!is_noop(item->command))
4751 return error(_("unknown command %d"), item->command);
4753 if (reschedule) {
4754 advise(_(rescheduled_advice),
4755 get_item_line_length(todo_list,
4756 todo_list->current),
4757 get_item_line(todo_list, todo_list->current));
4758 todo_list->current--;
4759 if (save_todo(todo_list, opts))
4760 return -1;
4761 if (item->commit)
4762 return error_with_patch(r,
4763 item->commit,
4764 arg, item->arg_len,
4765 opts, res, 0);
4766 } else if (is_rebase_i(opts) && check_todo && !res &&
4767 reread_todo_if_changed(r, todo_list, opts)) {
4768 return -1;
4771 todo_list->current++;
4772 if (res)
4773 return res;
4776 if (is_rebase_i(opts)) {
4777 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4778 struct stat st;
4780 /* Stopped in the middle, as planned? */
4781 if (todo_list->current < todo_list->nr)
4782 return 0;
4784 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4785 starts_with(head_ref.buf, "refs/")) {
4786 const char *msg;
4787 struct object_id head, orig;
4788 int res;
4790 if (get_oid("HEAD", &head)) {
4791 res = error(_("cannot read HEAD"));
4792 cleanup_head_ref:
4793 strbuf_release(&head_ref);
4794 strbuf_release(&buf);
4795 return res;
4797 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4798 get_oid_hex(buf.buf, &orig)) {
4799 res = error(_("could not read orig-head"));
4800 goto cleanup_head_ref;
4802 strbuf_reset(&buf);
4803 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4804 res = error(_("could not read 'onto'"));
4805 goto cleanup_head_ref;
4807 msg = reflog_message(opts, "finish", "%s onto %s",
4808 head_ref.buf, buf.buf);
4809 if (update_ref(msg, head_ref.buf, &head, &orig,
4810 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4811 res = error(_("could not update %s"),
4812 head_ref.buf);
4813 goto cleanup_head_ref;
4815 msg = reflog_message(opts, "finish", "returning to %s",
4816 head_ref.buf);
4817 if (create_symref("HEAD", head_ref.buf, msg)) {
4818 res = error(_("could not update HEAD to %s"),
4819 head_ref.buf);
4820 goto cleanup_head_ref;
4822 strbuf_reset(&buf);
4825 if (opts->verbose) {
4826 struct rev_info log_tree_opt;
4827 struct object_id orig, head;
4829 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4830 repo_init_revisions(r, &log_tree_opt, NULL);
4831 log_tree_opt.diff = 1;
4832 log_tree_opt.diffopt.output_format =
4833 DIFF_FORMAT_DIFFSTAT;
4834 log_tree_opt.disable_stdin = 1;
4836 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4837 !get_oid(buf.buf, &orig) &&
4838 !get_oid("HEAD", &head)) {
4839 diff_tree_oid(&orig, &head, "",
4840 &log_tree_opt.diffopt);
4841 log_tree_diff_flush(&log_tree_opt);
4843 release_revisions(&log_tree_opt);
4845 flush_rewritten_pending();
4846 if (!stat(rebase_path_rewritten_list(), &st) &&
4847 st.st_size > 0) {
4848 struct child_process child = CHILD_PROCESS_INIT;
4849 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4851 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4852 child.git_cmd = 1;
4853 strvec_push(&child.args, "notes");
4854 strvec_push(&child.args, "copy");
4855 strvec_push(&child.args, "--for-rewrite=rebase");
4856 /* we don't care if this copying failed */
4857 run_command(&child);
4859 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4860 strvec_push(&hook_opt.args, "rebase");
4861 run_hooks_opt("post-rewrite", &hook_opt);
4863 apply_autostash(rebase_path_autostash());
4865 if (!opts->quiet) {
4866 if (!opts->verbose)
4867 term_clear_line();
4868 fprintf(stderr,
4869 _("Successfully rebased and updated %s.\n"),
4870 head_ref.buf);
4873 strbuf_release(&buf);
4874 strbuf_release(&head_ref);
4876 if (do_update_refs(r, opts->quiet))
4877 return -1;
4881 * Sequence of picks finished successfully; cleanup by
4882 * removing the .git/sequencer directory
4884 return sequencer_remove_state(opts);
4887 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4889 struct child_process cmd = CHILD_PROCESS_INIT;
4891 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4892 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4893 return error(_("no cherry-pick or revert in progress"));
4895 cmd.git_cmd = 1;
4896 strvec_push(&cmd.args, "commit");
4899 * continue_single_pick() handles the case of recovering from a
4900 * conflict. should_edit() doesn't handle that case; for a conflict,
4901 * we want to edit if the user asked for it, or if they didn't specify
4902 * and stdin is a tty.
4904 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4906 * Include --cleanup=strip as well because we don't want the
4907 * "# Conflicts:" messages.
4909 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
4911 return run_command(&cmd);
4914 static int commit_staged_changes(struct repository *r,
4915 struct replay_opts *opts,
4916 struct todo_list *todo_list)
4918 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4919 unsigned int final_fixup = 0, is_clean;
4921 if (has_unstaged_changes(r, 1))
4922 return error(_("cannot rebase: You have unstaged changes."));
4924 is_clean = !has_uncommitted_changes(r, 0);
4926 if (file_exists(rebase_path_amend())) {
4927 struct strbuf rev = STRBUF_INIT;
4928 struct object_id head, to_amend;
4930 if (get_oid("HEAD", &head))
4931 return error(_("cannot amend non-existing commit"));
4932 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4933 return error(_("invalid file: '%s'"), rebase_path_amend());
4934 if (get_oid_hex(rev.buf, &to_amend))
4935 return error(_("invalid contents: '%s'"),
4936 rebase_path_amend());
4937 if (!is_clean && !oideq(&head, &to_amend))
4938 return error(_("\nYou have uncommitted changes in your "
4939 "working tree. Please, commit them\n"
4940 "first and then run 'git rebase "
4941 "--continue' again."));
4943 * When skipping a failed fixup/squash, we need to edit the
4944 * commit message, the current fixup list and count, and if it
4945 * was the last fixup/squash in the chain, we need to clean up
4946 * the commit message and if there was a squash, let the user
4947 * edit it.
4949 if (!is_clean || !opts->current_fixup_count)
4950 ; /* this is not the final fixup */
4951 else if (!oideq(&head, &to_amend) ||
4952 !file_exists(rebase_path_stopped_sha())) {
4953 /* was a final fixup or squash done manually? */
4954 if (!is_fixup(peek_command(todo_list, 0))) {
4955 unlink(rebase_path_fixup_msg());
4956 unlink(rebase_path_squash_msg());
4957 unlink(rebase_path_current_fixups());
4958 strbuf_reset(&opts->current_fixups);
4959 opts->current_fixup_count = 0;
4961 } else {
4962 /* we are in a fixup/squash chain */
4963 const char *p = opts->current_fixups.buf;
4964 int len = opts->current_fixups.len;
4966 opts->current_fixup_count--;
4967 if (!len)
4968 BUG("Incorrect current_fixups:\n%s", p);
4969 while (len && p[len - 1] != '\n')
4970 len--;
4971 strbuf_setlen(&opts->current_fixups, len);
4972 if (write_message(p, len, rebase_path_current_fixups(),
4973 0) < 0)
4974 return error(_("could not write file: '%s'"),
4975 rebase_path_current_fixups());
4978 * If a fixup/squash in a fixup/squash chain failed, the
4979 * commit message is already correct, no need to commit
4980 * it again.
4982 * Only if it is the final command in the fixup/squash
4983 * chain, and only if the chain is longer than a single
4984 * fixup/squash command (which was just skipped), do we
4985 * actually need to re-commit with a cleaned up commit
4986 * message.
4988 if (opts->current_fixup_count > 0 &&
4989 !is_fixup(peek_command(todo_list, 0))) {
4990 final_fixup = 1;
4992 * If there was not a single "squash" in the
4993 * chain, we only need to clean up the commit
4994 * message, no need to bother the user with
4995 * opening the commit message in the editor.
4997 if (!starts_with(p, "squash ") &&
4998 !strstr(p, "\nsquash "))
4999 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5000 } else if (is_fixup(peek_command(todo_list, 0))) {
5002 * We need to update the squash message to skip
5003 * the latest commit message.
5005 struct commit *commit;
5006 const char *path = rebase_path_squash_msg();
5007 const char *encoding = get_commit_output_encoding();
5009 if (parse_head(r, &commit) ||
5010 !(p = logmsg_reencode(commit, NULL, encoding)) ||
5011 write_message(p, strlen(p), path, 0)) {
5012 unuse_commit_buffer(commit, p);
5013 return error(_("could not write file: "
5014 "'%s'"), path);
5016 unuse_commit_buffer(commit, p);
5020 strbuf_release(&rev);
5021 flags |= AMEND_MSG;
5024 if (is_clean) {
5025 if (refs_ref_exists(get_main_ref_store(r),
5026 "CHERRY_PICK_HEAD") &&
5027 refs_delete_ref(get_main_ref_store(r), "",
5028 "CHERRY_PICK_HEAD", NULL, 0))
5029 return error(_("could not remove CHERRY_PICK_HEAD"));
5030 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5031 return error_errno(_("could not remove '%s'"),
5032 git_path_merge_msg(r));
5033 if (!final_fixup)
5034 return 0;
5037 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5038 opts, flags))
5039 return error(_("could not commit staged changes."));
5040 unlink(rebase_path_amend());
5041 unlink(git_path_merge_head(r));
5042 unlink(git_path_auto_merge(r));
5043 if (final_fixup) {
5044 unlink(rebase_path_fixup_msg());
5045 unlink(rebase_path_squash_msg());
5047 if (opts->current_fixup_count > 0) {
5049 * Whether final fixup or not, we just cleaned up the commit
5050 * message...
5052 unlink(rebase_path_current_fixups());
5053 strbuf_reset(&opts->current_fixups);
5054 opts->current_fixup_count = 0;
5056 return 0;
5059 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5061 struct todo_list todo_list = TODO_LIST_INIT;
5062 int res;
5064 if (read_and_refresh_cache(r, opts))
5065 return -1;
5067 if (read_populate_opts(opts))
5068 return -1;
5069 if (is_rebase_i(opts)) {
5070 if ((res = read_populate_todo(r, &todo_list, opts)))
5071 goto release_todo_list;
5073 if (file_exists(rebase_path_dropped())) {
5074 if ((res = todo_list_check_against_backup(r, &todo_list)))
5075 goto release_todo_list;
5077 unlink(rebase_path_dropped());
5080 opts->reflog_message = reflog_message(opts, "continue", NULL);
5081 if (commit_staged_changes(r, opts, &todo_list)) {
5082 res = -1;
5083 goto release_todo_list;
5085 } else if (!file_exists(get_todo_path(opts)))
5086 return continue_single_pick(r, opts);
5087 else if ((res = read_populate_todo(r, &todo_list, opts)))
5088 goto release_todo_list;
5090 if (!is_rebase_i(opts)) {
5091 /* Verify that the conflict has been resolved */
5092 if (refs_ref_exists(get_main_ref_store(r),
5093 "CHERRY_PICK_HEAD") ||
5094 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5095 res = continue_single_pick(r, opts);
5096 if (res)
5097 goto release_todo_list;
5099 if (index_differs_from(r, "HEAD", NULL, 0)) {
5100 res = error_dirty_index(r, opts);
5101 goto release_todo_list;
5103 todo_list.current++;
5104 } else if (file_exists(rebase_path_stopped_sha())) {
5105 struct strbuf buf = STRBUF_INIT;
5106 struct object_id oid;
5108 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5109 READ_ONELINER_SKIP_IF_EMPTY) &&
5110 !get_oid_hex(buf.buf, &oid))
5111 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5112 strbuf_release(&buf);
5115 res = pick_commits(r, &todo_list, opts);
5116 release_todo_list:
5117 todo_list_release(&todo_list);
5118 return res;
5121 static int single_pick(struct repository *r,
5122 struct commit *cmit,
5123 struct replay_opts *opts)
5125 int check_todo;
5126 struct todo_item item;
5128 item.command = opts->action == REPLAY_PICK ?
5129 TODO_PICK : TODO_REVERT;
5130 item.commit = cmit;
5132 opts->reflog_message = sequencer_reflog_action(opts);
5133 return do_pick_commit(r, &item, opts, 0, &check_todo);
5136 int sequencer_pick_revisions(struct repository *r,
5137 struct replay_opts *opts)
5139 struct todo_list todo_list = TODO_LIST_INIT;
5140 struct object_id oid;
5141 int i, res;
5143 assert(opts->revs);
5144 if (read_and_refresh_cache(r, opts))
5145 return -1;
5147 for (i = 0; i < opts->revs->pending.nr; i++) {
5148 struct object_id oid;
5149 const char *name = opts->revs->pending.objects[i].name;
5151 /* This happens when using --stdin. */
5152 if (!strlen(name))
5153 continue;
5155 if (!get_oid(name, &oid)) {
5156 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5157 enum object_type type = oid_object_info(r,
5158 &oid,
5159 NULL);
5160 return error(_("%s: can't cherry-pick a %s"),
5161 name, type_name(type));
5163 } else
5164 return error(_("%s: bad revision"), name);
5168 * If we were called as "git cherry-pick <commit>", just
5169 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5170 * REVERT_HEAD, and don't touch the sequencer state.
5171 * This means it is possible to cherry-pick in the middle
5172 * of a cherry-pick sequence.
5174 if (opts->revs->cmdline.nr == 1 &&
5175 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5176 opts->revs->no_walk &&
5177 !opts->revs->cmdline.rev->flags) {
5178 struct commit *cmit;
5179 if (prepare_revision_walk(opts->revs))
5180 return error(_("revision walk setup failed"));
5181 cmit = get_revision(opts->revs);
5182 if (!cmit)
5183 return error(_("empty commit set passed"));
5184 if (get_revision(opts->revs))
5185 BUG("unexpected extra commit from walk");
5186 return single_pick(r, cmit, opts);
5190 * Start a new cherry-pick/ revert sequence; but
5191 * first, make sure that an existing one isn't in
5192 * progress
5195 if (walk_revs_populate_todo(&todo_list, opts) ||
5196 create_seq_dir(r) < 0)
5197 return -1;
5198 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
5199 return error(_("can't revert as initial commit"));
5200 if (save_head(oid_to_hex(&oid)))
5201 return -1;
5202 if (save_opts(opts))
5203 return -1;
5204 update_abort_safety_file();
5205 res = pick_commits(r, &todo_list, opts);
5206 todo_list_release(&todo_list);
5207 return res;
5210 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5212 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5213 struct strbuf sob = STRBUF_INIT;
5214 int has_footer;
5216 strbuf_addstr(&sob, sign_off_header);
5217 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5218 strbuf_addch(&sob, '\n');
5220 if (!ignore_footer)
5221 strbuf_complete_line(msgbuf);
5224 * If the whole message buffer is equal to the sob, pretend that we
5225 * found a conforming footer with a matching sob
5227 if (msgbuf->len - ignore_footer == sob.len &&
5228 !strncmp(msgbuf->buf, sob.buf, sob.len))
5229 has_footer = 3;
5230 else
5231 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5233 if (!has_footer) {
5234 const char *append_newlines = NULL;
5235 size_t len = msgbuf->len - ignore_footer;
5237 if (!len) {
5239 * The buffer is completely empty. Leave foom for
5240 * the title and body to be filled in by the user.
5242 append_newlines = "\n\n";
5243 } else if (len == 1) {
5245 * Buffer contains a single newline. Add another
5246 * so that we leave room for the title and body.
5248 append_newlines = "\n";
5249 } else if (msgbuf->buf[len - 2] != '\n') {
5251 * Buffer ends with a single newline. Add another
5252 * so that there is an empty line between the message
5253 * body and the sob.
5255 append_newlines = "\n";
5256 } /* else, the buffer already ends with two newlines. */
5258 if (append_newlines)
5259 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5260 append_newlines, strlen(append_newlines));
5263 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5264 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5265 sob.buf, sob.len);
5267 strbuf_release(&sob);
5270 struct labels_entry {
5271 struct hashmap_entry entry;
5272 char label[FLEX_ARRAY];
5275 static int labels_cmp(const void *fndata UNUSED,
5276 const struct hashmap_entry *eptr,
5277 const struct hashmap_entry *entry_or_key, const void *key)
5279 const struct labels_entry *a, *b;
5281 a = container_of(eptr, const struct labels_entry, entry);
5282 b = container_of(entry_or_key, const struct labels_entry, entry);
5284 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5287 struct string_entry {
5288 struct oidmap_entry entry;
5289 char string[FLEX_ARRAY];
5292 struct label_state {
5293 struct oidmap commit2label;
5294 struct hashmap labels;
5295 struct strbuf buf;
5298 static const char *label_oid(struct object_id *oid, const char *label,
5299 struct label_state *state)
5301 struct labels_entry *labels_entry;
5302 struct string_entry *string_entry;
5303 struct object_id dummy;
5304 int i;
5306 string_entry = oidmap_get(&state->commit2label, oid);
5307 if (string_entry)
5308 return string_entry->string;
5311 * For "uninteresting" commits, i.e. commits that are not to be
5312 * rebased, and which can therefore not be labeled, we use a unique
5313 * abbreviation of the commit name. This is slightly more complicated
5314 * than calling find_unique_abbrev() because we also need to make
5315 * sure that the abbreviation does not conflict with any other
5316 * label.
5318 * We disallow "interesting" commits to be labeled by a string that
5319 * is a valid full-length hash, to ensure that we always can find an
5320 * abbreviation for any uninteresting commit's names that does not
5321 * clash with any other label.
5323 strbuf_reset(&state->buf);
5324 if (!label) {
5325 char *p;
5327 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5328 label = p = state->buf.buf;
5330 find_unique_abbrev_r(p, oid, default_abbrev);
5333 * We may need to extend the abbreviated hash so that there is
5334 * no conflicting label.
5336 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5337 size_t i = strlen(p) + 1;
5339 oid_to_hex_r(p, oid);
5340 for (; i < the_hash_algo->hexsz; i++) {
5341 char save = p[i];
5342 p[i] = '\0';
5343 if (!hashmap_get_from_hash(&state->labels,
5344 strihash(p), p))
5345 break;
5346 p[i] = save;
5349 } else {
5350 struct strbuf *buf = &state->buf;
5353 * Sanitize labels by replacing non-alpha-numeric characters
5354 * (including white-space ones) by dashes, as they might be
5355 * illegal in file names (and hence in ref names).
5357 * Note that we retain non-ASCII UTF-8 characters (identified
5358 * via the most significant bit). They should be all acceptable
5359 * in file names. We do not validate the UTF-8 here, that's not
5360 * the job of this function.
5362 for (; *label; label++)
5363 if ((*label & 0x80) || isalnum(*label))
5364 strbuf_addch(buf, *label);
5365 /* avoid leading dash and double-dashes */
5366 else if (buf->len && buf->buf[buf->len - 1] != '-')
5367 strbuf_addch(buf, '-');
5368 if (!buf->len) {
5369 strbuf_addstr(buf, "rev-");
5370 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5372 label = buf->buf;
5374 if ((buf->len == the_hash_algo->hexsz &&
5375 !get_oid_hex(label, &dummy)) ||
5376 (buf->len == 1 && *label == '#') ||
5377 hashmap_get_from_hash(&state->labels,
5378 strihash(label), label)) {
5380 * If the label already exists, or if the label is a
5381 * valid full OID, or the label is a '#' (which we use
5382 * as a separator between merge heads and oneline), we
5383 * append a dash and a number to make it unique.
5385 size_t len = buf->len;
5387 for (i = 2; ; i++) {
5388 strbuf_setlen(buf, len);
5389 strbuf_addf(buf, "-%d", i);
5390 if (!hashmap_get_from_hash(&state->labels,
5391 strihash(buf->buf),
5392 buf->buf))
5393 break;
5396 label = buf->buf;
5400 FLEX_ALLOC_STR(labels_entry, label, label);
5401 hashmap_entry_init(&labels_entry->entry, strihash(label));
5402 hashmap_add(&state->labels, &labels_entry->entry);
5404 FLEX_ALLOC_STR(string_entry, string, label);
5405 oidcpy(&string_entry->entry.oid, oid);
5406 oidmap_put(&state->commit2label, string_entry);
5408 return string_entry->string;
5411 static int make_script_with_merges(struct pretty_print_context *pp,
5412 struct rev_info *revs, struct strbuf *out,
5413 unsigned flags)
5415 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5416 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5417 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5418 int skipped_commit = 0;
5419 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5420 struct strbuf label = STRBUF_INIT;
5421 struct commit_list *commits = NULL, **tail = &commits, *iter;
5422 struct commit_list *tips = NULL, **tips_tail = &tips;
5423 struct commit *commit;
5424 struct oidmap commit2todo = OIDMAP_INIT;
5425 struct string_entry *entry;
5426 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5427 shown = OIDSET_INIT;
5428 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5430 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5431 const char *cmd_pick = abbr ? "p" : "pick",
5432 *cmd_label = abbr ? "l" : "label",
5433 *cmd_reset = abbr ? "t" : "reset",
5434 *cmd_merge = abbr ? "m" : "merge";
5436 oidmap_init(&commit2todo, 0);
5437 oidmap_init(&state.commit2label, 0);
5438 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5439 strbuf_init(&state.buf, 32);
5441 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5442 struct labels_entry *onto_label_entry;
5443 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5444 FLEX_ALLOC_STR(entry, string, "onto");
5445 oidcpy(&entry->entry.oid, oid);
5446 oidmap_put(&state.commit2label, entry);
5448 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5449 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5450 hashmap_add(&state.labels, &onto_label_entry->entry);
5454 * First phase:
5455 * - get onelines for all commits
5456 * - gather all branch tips (i.e. 2nd or later parents of merges)
5457 * - label all branch tips
5459 while ((commit = get_revision(revs))) {
5460 struct commit_list *to_merge;
5461 const char *p1, *p2;
5462 struct object_id *oid;
5463 int is_empty;
5465 tail = &commit_list_insert(commit, tail)->next;
5466 oidset_insert(&interesting, &commit->object.oid);
5468 is_empty = is_original_commit_empty(commit);
5469 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5470 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5471 warning(_("skipped previously applied commit %s"),
5472 short_commit_name(commit));
5473 skipped_commit = 1;
5474 continue;
5476 if (is_empty && !keep_empty)
5477 continue;
5479 strbuf_reset(&oneline);
5480 pretty_print_commit(pp, commit, &oneline);
5482 to_merge = commit->parents ? commit->parents->next : NULL;
5483 if (!to_merge) {
5484 /* non-merge commit: easy case */
5485 strbuf_reset(&buf);
5486 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5487 oid_to_hex(&commit->object.oid),
5488 oneline.buf);
5489 if (is_empty)
5490 strbuf_addf(&buf, " %c empty",
5491 comment_line_char);
5493 FLEX_ALLOC_STR(entry, string, buf.buf);
5494 oidcpy(&entry->entry.oid, &commit->object.oid);
5495 oidmap_put(&commit2todo, entry);
5497 continue;
5500 /* Create a label */
5501 strbuf_reset(&label);
5502 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5503 (p1 = strchr(p1, '\'')) &&
5504 (p2 = strchr(++p1, '\'')))
5505 strbuf_add(&label, p1, p2 - p1);
5506 else if (skip_prefix(oneline.buf, "Merge pull request ",
5507 &p1) &&
5508 (p1 = strstr(p1, " from ")))
5509 strbuf_addstr(&label, p1 + strlen(" from "));
5510 else
5511 strbuf_addbuf(&label, &oneline);
5513 strbuf_reset(&buf);
5514 strbuf_addf(&buf, "%s -C %s",
5515 cmd_merge, oid_to_hex(&commit->object.oid));
5517 /* label the tips of merged branches */
5518 for (; to_merge; to_merge = to_merge->next) {
5519 oid = &to_merge->item->object.oid;
5520 strbuf_addch(&buf, ' ');
5522 if (!oidset_contains(&interesting, oid)) {
5523 strbuf_addstr(&buf, label_oid(oid, NULL,
5524 &state));
5525 continue;
5528 tips_tail = &commit_list_insert(to_merge->item,
5529 tips_tail)->next;
5531 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5533 strbuf_addf(&buf, " # %s", oneline.buf);
5535 FLEX_ALLOC_STR(entry, string, buf.buf);
5536 oidcpy(&entry->entry.oid, &commit->object.oid);
5537 oidmap_put(&commit2todo, entry);
5539 if (skipped_commit)
5540 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5541 _("use --reapply-cherry-picks to include skipped commits"));
5544 * Second phase:
5545 * - label branch points
5546 * - add HEAD to the branch tips
5548 for (iter = commits; iter; iter = iter->next) {
5549 struct commit_list *parent = iter->item->parents;
5550 for (; parent; parent = parent->next) {
5551 struct object_id *oid = &parent->item->object.oid;
5552 if (!oidset_contains(&interesting, oid))
5553 continue;
5554 if (oidset_insert(&child_seen, oid))
5555 label_oid(oid, "branch-point", &state);
5558 /* Add HEAD as implicit "tip of branch" */
5559 if (!iter->next)
5560 tips_tail = &commit_list_insert(iter->item,
5561 tips_tail)->next;
5565 * Third phase: output the todo list. This is a bit tricky, as we
5566 * want to avoid jumping back and forth between revisions. To
5567 * accomplish that goal, we walk backwards from the branch tips,
5568 * gathering commits not yet shown, reversing the list on the fly,
5569 * then outputting that list (labeling revisions as needed).
5571 strbuf_addf(out, "%s onto\n", cmd_label);
5572 for (iter = tips; iter; iter = iter->next) {
5573 struct commit_list *list = NULL, *iter2;
5575 commit = iter->item;
5576 if (oidset_contains(&shown, &commit->object.oid))
5577 continue;
5578 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5580 if (entry)
5581 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5582 else
5583 strbuf_addch(out, '\n');
5585 while (oidset_contains(&interesting, &commit->object.oid) &&
5586 !oidset_contains(&shown, &commit->object.oid)) {
5587 commit_list_insert(commit, &list);
5588 if (!commit->parents) {
5589 commit = NULL;
5590 break;
5592 commit = commit->parents->item;
5595 if (!commit)
5596 strbuf_addf(out, "%s %s\n", cmd_reset,
5597 rebase_cousins || root_with_onto ?
5598 "onto" : "[new root]");
5599 else {
5600 const char *to = NULL;
5602 entry = oidmap_get(&state.commit2label,
5603 &commit->object.oid);
5604 if (entry)
5605 to = entry->string;
5606 else if (!rebase_cousins)
5607 to = label_oid(&commit->object.oid, NULL,
5608 &state);
5610 if (!to || !strcmp(to, "onto"))
5611 strbuf_addf(out, "%s onto\n", cmd_reset);
5612 else {
5613 strbuf_reset(&oneline);
5614 pretty_print_commit(pp, commit, &oneline);
5615 strbuf_addf(out, "%s %s # %s\n",
5616 cmd_reset, to, oneline.buf);
5620 for (iter2 = list; iter2; iter2 = iter2->next) {
5621 struct object_id *oid = &iter2->item->object.oid;
5622 entry = oidmap_get(&commit2todo, oid);
5623 /* only show if not already upstream */
5624 if (entry)
5625 strbuf_addf(out, "%s\n", entry->string);
5626 entry = oidmap_get(&state.commit2label, oid);
5627 if (entry)
5628 strbuf_addf(out, "%s %s\n",
5629 cmd_label, entry->string);
5630 oidset_insert(&shown, oid);
5633 free_commit_list(list);
5636 free_commit_list(commits);
5637 free_commit_list(tips);
5639 strbuf_release(&label);
5640 strbuf_release(&oneline);
5641 strbuf_release(&buf);
5643 oidmap_free(&commit2todo, 1);
5644 oidmap_free(&state.commit2label, 1);
5645 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5646 strbuf_release(&state.buf);
5648 return 0;
5651 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5652 const char **argv, unsigned flags)
5654 char *format = NULL;
5655 struct pretty_print_context pp = {0};
5656 struct rev_info revs;
5657 struct commit *commit;
5658 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5659 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5660 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5661 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5662 int skipped_commit = 0;
5663 int ret = 0;
5665 repo_init_revisions(r, &revs, NULL);
5666 revs.verbose_header = 1;
5667 if (!rebase_merges)
5668 revs.max_parents = 1;
5669 revs.cherry_mark = !reapply_cherry_picks;
5670 revs.limited = 1;
5671 revs.reverse = 1;
5672 revs.right_only = 1;
5673 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5674 revs.topo_order = 1;
5676 revs.pretty_given = 1;
5677 git_config_get_string("rebase.instructionFormat", &format);
5678 if (!format || !*format) {
5679 free(format);
5680 format = xstrdup("%s");
5682 get_commit_format(format, &revs);
5683 free(format);
5684 pp.fmt = revs.commit_format;
5685 pp.output_encoding = get_log_output_encoding();
5687 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5688 ret = error(_("make_script: unhandled options"));
5689 goto cleanup;
5692 if (prepare_revision_walk(&revs) < 0) {
5693 ret = error(_("make_script: error preparing revisions"));
5694 goto cleanup;
5697 if (rebase_merges) {
5698 ret = make_script_with_merges(&pp, &revs, out, flags);
5699 goto cleanup;
5702 while ((commit = get_revision(&revs))) {
5703 int is_empty = is_original_commit_empty(commit);
5705 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5706 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5707 warning(_("skipped previously applied commit %s"),
5708 short_commit_name(commit));
5709 skipped_commit = 1;
5710 continue;
5712 if (is_empty && !keep_empty)
5713 continue;
5714 strbuf_addf(out, "%s %s ", insn,
5715 oid_to_hex(&commit->object.oid));
5716 pretty_print_commit(&pp, commit, out);
5717 if (is_empty)
5718 strbuf_addf(out, " %c empty", comment_line_char);
5719 strbuf_addch(out, '\n');
5721 if (skipped_commit)
5722 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5723 _("use --reapply-cherry-picks to include skipped commits"));
5724 cleanup:
5725 release_revisions(&revs);
5726 return ret;
5730 * Add commands after pick and (series of) squash/fixup commands
5731 * in the todo list.
5733 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5734 struct string_list *commands)
5736 struct strbuf *buf = &todo_list->buf;
5737 size_t base_offset = buf->len;
5738 int i, insert, nr = 0, alloc = 0;
5739 struct todo_item *items = NULL, *base_items = NULL;
5741 CALLOC_ARRAY(base_items, commands->nr);
5742 for (i = 0; i < commands->nr; i++) {
5743 size_t command_len = strlen(commands->items[i].string);
5745 strbuf_addstr(buf, commands->items[i].string);
5746 strbuf_addch(buf, '\n');
5748 base_items[i].command = TODO_EXEC;
5749 base_items[i].offset_in_buf = base_offset;
5750 base_items[i].arg_offset = base_offset;
5751 base_items[i].arg_len = command_len;
5753 base_offset += command_len + 1;
5757 * Insert <commands> after every pick. Here, fixup/squash chains
5758 * are considered part of the pick, so we insert the commands *after*
5759 * those chains if there are any.
5761 * As we insert the exec commands immediately after rearranging
5762 * any fixups and before the user edits the list, a fixup chain
5763 * can never contain comments (any comments are empty picks that
5764 * have been commented out because the user did not specify
5765 * --keep-empty). So, it is safe to insert an exec command
5766 * without looking at the command following a comment.
5768 insert = 0;
5769 for (i = 0; i < todo_list->nr; i++) {
5770 enum todo_command command = todo_list->items[i].command;
5771 if (insert && !is_fixup(command)) {
5772 ALLOC_GROW(items, nr + commands->nr, alloc);
5773 COPY_ARRAY(items + nr, base_items, commands->nr);
5774 nr += commands->nr;
5776 insert = 0;
5779 ALLOC_GROW(items, nr + 1, alloc);
5780 items[nr++] = todo_list->items[i];
5782 if (command == TODO_PICK || command == TODO_MERGE)
5783 insert = 1;
5786 /* insert or append final <commands> */
5787 if (insert) {
5788 ALLOC_GROW(items, nr + commands->nr, alloc);
5789 COPY_ARRAY(items + nr, base_items, commands->nr);
5790 nr += commands->nr;
5793 free(base_items);
5794 FREE_AND_NULL(todo_list->items);
5795 todo_list->items = items;
5796 todo_list->nr = nr;
5797 todo_list->alloc = alloc;
5800 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5801 struct strbuf *buf, int num, unsigned flags)
5803 struct todo_item *item;
5804 int i, max = todo_list->nr;
5806 if (num > 0 && num < max)
5807 max = num;
5809 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5810 char cmd;
5812 /* if the item is not a command write it and continue */
5813 if (item->command >= TODO_COMMENT) {
5814 strbuf_addf(buf, "%.*s\n", item->arg_len,
5815 todo_item_get_arg(todo_list, item));
5816 continue;
5819 /* add command to the buffer */
5820 cmd = command_to_char(item->command);
5821 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5822 strbuf_addch(buf, cmd);
5823 else
5824 strbuf_addstr(buf, command_to_string(item->command));
5826 /* add commit id */
5827 if (item->commit) {
5828 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5829 short_commit_name(item->commit) :
5830 oid_to_hex(&item->commit->object.oid);
5832 if (item->command == TODO_FIXUP) {
5833 if (item->flags & TODO_EDIT_FIXUP_MSG)
5834 strbuf_addstr(buf, " -c");
5835 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5836 strbuf_addstr(buf, " -C");
5840 if (item->command == TODO_MERGE) {
5841 if (item->flags & TODO_EDIT_MERGE_MSG)
5842 strbuf_addstr(buf, " -c");
5843 else
5844 strbuf_addstr(buf, " -C");
5847 strbuf_addf(buf, " %s", oid);
5850 /* add all the rest */
5851 if (!item->arg_len)
5852 strbuf_addch(buf, '\n');
5853 else
5854 strbuf_addf(buf, " %.*s\n", item->arg_len,
5855 todo_item_get_arg(todo_list, item));
5859 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5860 const char *file, const char *shortrevisions,
5861 const char *shortonto, int num, unsigned flags)
5863 int res;
5864 struct strbuf buf = STRBUF_INIT;
5866 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5867 if (flags & TODO_LIST_APPEND_TODO_HELP)
5868 append_todo_help(count_commands(todo_list),
5869 shortrevisions, shortonto, &buf);
5871 res = write_message(buf.buf, buf.len, file, 0);
5872 strbuf_release(&buf);
5874 return res;
5877 /* skip picking commits whose parents are unchanged */
5878 static int skip_unnecessary_picks(struct repository *r,
5879 struct todo_list *todo_list,
5880 struct object_id *base_oid)
5882 struct object_id *parent_oid;
5883 int i;
5885 for (i = 0; i < todo_list->nr; i++) {
5886 struct todo_item *item = todo_list->items + i;
5888 if (item->command >= TODO_NOOP)
5889 continue;
5890 if (item->command != TODO_PICK)
5891 break;
5892 if (parse_commit(item->commit)) {
5893 return error(_("could not parse commit '%s'"),
5894 oid_to_hex(&item->commit->object.oid));
5896 if (!item->commit->parents)
5897 break; /* root commit */
5898 if (item->commit->parents->next)
5899 break; /* merge commit */
5900 parent_oid = &item->commit->parents->item->object.oid;
5901 if (!oideq(parent_oid, base_oid))
5902 break;
5903 oidcpy(base_oid, &item->commit->object.oid);
5905 if (i > 0) {
5906 const char *done_path = rebase_path_done();
5908 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5909 error_errno(_("could not write to '%s'"), done_path);
5910 return -1;
5913 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5914 todo_list->nr -= i;
5915 todo_list->current = 0;
5916 todo_list->done_nr += i;
5918 if (is_fixup(peek_command(todo_list, 0)))
5919 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5922 return 0;
5925 struct todo_add_branch_context {
5926 struct todo_item *items;
5927 size_t items_nr;
5928 size_t items_alloc;
5929 struct strbuf *buf;
5930 struct commit *commit;
5931 struct string_list refs_to_oids;
5934 static int add_decorations_to_list(const struct commit *commit,
5935 struct todo_add_branch_context *ctx)
5937 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5938 const char *head_ref = resolve_ref_unsafe("HEAD",
5939 RESOLVE_REF_READING,
5940 NULL,
5941 NULL);
5943 while (decoration) {
5944 struct todo_item *item;
5945 const char *path;
5946 size_t base_offset = ctx->buf->len;
5949 * If the branch is the current HEAD, then it will be
5950 * updated by the default rebase behavior.
5952 if (head_ref && !strcmp(head_ref, decoration->name)) {
5953 decoration = decoration->next;
5954 continue;
5957 ALLOC_GROW(ctx->items,
5958 ctx->items_nr + 1,
5959 ctx->items_alloc);
5960 item = &ctx->items[ctx->items_nr];
5961 memset(item, 0, sizeof(*item));
5963 /* If the branch is checked out, then leave a comment instead. */
5964 if ((path = branch_checked_out(decoration->name))) {
5965 item->command = TODO_COMMENT;
5966 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
5967 decoration->name, path);
5968 } else {
5969 struct string_list_item *sti;
5970 item->command = TODO_UPDATE_REF;
5971 strbuf_addf(ctx->buf, "%s\n", decoration->name);
5973 sti = string_list_insert(&ctx->refs_to_oids,
5974 decoration->name);
5975 sti->util = init_update_ref_record(decoration->name);
5978 item->offset_in_buf = base_offset;
5979 item->arg_offset = base_offset;
5980 item->arg_len = ctx->buf->len - base_offset;
5981 ctx->items_nr++;
5983 decoration = decoration->next;
5986 return 0;
5990 * For each 'pick' command, find out if the commit has a decoration in
5991 * refs/heads/. If so, then add a 'label for-update-refs/' command.
5993 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
5995 int i, res;
5996 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
5997 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
5998 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
5999 struct decoration_filter decoration_filter = {
6000 .include_ref_pattern = &decorate_refs_include,
6001 .exclude_ref_pattern = &decorate_refs_exclude,
6002 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6004 struct todo_add_branch_context ctx = {
6005 .buf = &todo_list->buf,
6006 .refs_to_oids = STRING_LIST_INIT_DUP,
6009 ctx.items_alloc = 2 * todo_list->nr + 1;
6010 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6012 string_list_append(&decorate_refs_include, "refs/heads/");
6013 load_ref_decorations(&decoration_filter, 0);
6015 for (i = 0; i < todo_list->nr; ) {
6016 struct todo_item *item = &todo_list->items[i];
6018 /* insert ith item into new list */
6019 ALLOC_GROW(ctx.items,
6020 ctx.items_nr + 1,
6021 ctx.items_alloc);
6023 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6025 if (item->commit) {
6026 ctx.commit = item->commit;
6027 add_decorations_to_list(item->commit, &ctx);
6031 res = write_update_refs_state(&ctx.refs_to_oids);
6033 string_list_clear(&ctx.refs_to_oids, 1);
6035 if (res) {
6036 /* we failed, so clean up the new list. */
6037 free(ctx.items);
6038 return res;
6041 free(todo_list->items);
6042 todo_list->items = ctx.items;
6043 todo_list->nr = ctx.items_nr;
6044 todo_list->alloc = ctx.items_alloc;
6046 return 0;
6049 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6050 const char *shortrevisions, const char *onto_name,
6051 struct commit *onto, const struct object_id *orig_head,
6052 struct string_list *commands, unsigned autosquash,
6053 unsigned update_refs,
6054 struct todo_list *todo_list)
6056 char shortonto[GIT_MAX_HEXSZ + 1];
6057 const char *todo_file = rebase_path_todo();
6058 struct todo_list new_todo = TODO_LIST_INIT;
6059 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6060 struct object_id oid = onto->object.oid;
6061 int res;
6063 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
6065 if (buf->len == 0) {
6066 struct todo_item *item = append_new_todo(todo_list);
6067 item->command = TODO_NOOP;
6068 item->commit = NULL;
6069 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6072 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6073 return -1;
6075 if (autosquash && todo_list_rearrange_squash(todo_list))
6076 return -1;
6078 if (commands->nr)
6079 todo_list_add_exec_commands(todo_list, commands);
6081 if (count_commands(todo_list) == 0) {
6082 apply_autostash(rebase_path_autostash());
6083 sequencer_remove_state(opts);
6085 return error(_("nothing to do"));
6088 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6089 shortonto, flags);
6090 if (res == -1)
6091 return -1;
6092 else if (res == -2) {
6093 apply_autostash(rebase_path_autostash());
6094 sequencer_remove_state(opts);
6096 return -1;
6097 } else if (res == -3) {
6098 apply_autostash(rebase_path_autostash());
6099 sequencer_remove_state(opts);
6100 todo_list_release(&new_todo);
6102 return error(_("nothing to do"));
6103 } else if (res == -4) {
6104 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6105 todo_list_release(&new_todo);
6107 return -1;
6110 /* Expand the commit IDs */
6111 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6112 strbuf_swap(&new_todo.buf, &buf2);
6113 strbuf_release(&buf2);
6114 new_todo.total_nr -= new_todo.nr;
6115 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6116 BUG("invalid todo list after expanding IDs:\n%s",
6117 new_todo.buf.buf);
6119 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6120 todo_list_release(&new_todo);
6121 return error(_("could not skip unnecessary pick commands"));
6124 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6125 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6126 todo_list_release(&new_todo);
6127 return error_errno(_("could not write '%s'"), todo_file);
6130 res = -1;
6132 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6133 goto cleanup;
6135 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6136 goto cleanup;
6138 todo_list_write_total_nr(&new_todo);
6139 res = pick_commits(r, &new_todo, opts);
6141 cleanup:
6142 todo_list_release(&new_todo);
6144 return res;
6147 struct subject2item_entry {
6148 struct hashmap_entry entry;
6149 int i;
6150 char subject[FLEX_ARRAY];
6153 static int subject2item_cmp(const void *fndata UNUSED,
6154 const struct hashmap_entry *eptr,
6155 const struct hashmap_entry *entry_or_key,
6156 const void *key)
6158 const struct subject2item_entry *a, *b;
6160 a = container_of(eptr, const struct subject2item_entry, entry);
6161 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6163 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6166 define_commit_slab(commit_todo_item, struct todo_item *);
6168 static int skip_fixupish(const char *subject, const char **p) {
6169 return skip_prefix(subject, "fixup! ", p) ||
6170 skip_prefix(subject, "amend! ", p) ||
6171 skip_prefix(subject, "squash! ", p);
6175 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6176 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6177 * after the former, and change "pick" to "fixup"/"squash".
6179 * Note that if the config has specified a custom instruction format, each log
6180 * message will have to be retrieved from the commit (as the oneline in the
6181 * script cannot be trusted) in order to normalize the autosquash arrangement.
6183 int todo_list_rearrange_squash(struct todo_list *todo_list)
6185 struct hashmap subject2item;
6186 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6187 char **subjects;
6188 struct commit_todo_item commit_todo;
6189 struct todo_item *items = NULL;
6191 init_commit_todo_item(&commit_todo);
6193 * The hashmap maps onelines to the respective todo list index.
6195 * If any items need to be rearranged, the next[i] value will indicate
6196 * which item was moved directly after the i'th.
6198 * In that case, last[i] will indicate the index of the latest item to
6199 * be moved to appear after the i'th.
6201 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6202 ALLOC_ARRAY(next, todo_list->nr);
6203 ALLOC_ARRAY(tail, todo_list->nr);
6204 ALLOC_ARRAY(subjects, todo_list->nr);
6205 for (i = 0; i < todo_list->nr; i++) {
6206 struct strbuf buf = STRBUF_INIT;
6207 struct todo_item *item = todo_list->items + i;
6208 const char *commit_buffer, *subject, *p;
6209 size_t subject_len;
6210 int i2 = -1;
6211 struct subject2item_entry *entry;
6213 next[i] = tail[i] = -1;
6214 if (!item->commit || item->command == TODO_DROP) {
6215 subjects[i] = NULL;
6216 continue;
6219 if (is_fixup(item->command)) {
6220 clear_commit_todo_item(&commit_todo);
6221 return error(_("the script was already rearranged."));
6224 parse_commit(item->commit);
6225 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
6226 find_commit_subject(commit_buffer, &subject);
6227 format_subject(&buf, subject, " ");
6228 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6229 unuse_commit_buffer(item->commit, commit_buffer);
6230 if (skip_fixupish(subject, &p)) {
6231 struct commit *commit2;
6233 for (;;) {
6234 while (isspace(*p))
6235 p++;
6236 if (!skip_fixupish(p, &p))
6237 break;
6240 entry = hashmap_get_entry_from_hash(&subject2item,
6241 strhash(p), p,
6242 struct subject2item_entry,
6243 entry);
6244 if (entry)
6245 /* found by title */
6246 i2 = entry->i;
6247 else if (!strchr(p, ' ') &&
6248 (commit2 =
6249 lookup_commit_reference_by_name(p)) &&
6250 *commit_todo_item_at(&commit_todo, commit2))
6251 /* found by commit name */
6252 i2 = *commit_todo_item_at(&commit_todo, commit2)
6253 - todo_list->items;
6254 else {
6255 /* copy can be a prefix of the commit subject */
6256 for (i2 = 0; i2 < i; i2++)
6257 if (subjects[i2] &&
6258 starts_with(subjects[i2], p))
6259 break;
6260 if (i2 == i)
6261 i2 = -1;
6264 if (i2 >= 0) {
6265 rearranged = 1;
6266 if (starts_with(subject, "fixup!")) {
6267 todo_list->items[i].command = TODO_FIXUP;
6268 } else if (starts_with(subject, "amend!")) {
6269 todo_list->items[i].command = TODO_FIXUP;
6270 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6271 } else {
6272 todo_list->items[i].command = TODO_SQUASH;
6274 if (tail[i2] < 0) {
6275 next[i] = next[i2];
6276 next[i2] = i;
6277 } else {
6278 next[i] = next[tail[i2]];
6279 next[tail[i2]] = i;
6281 tail[i2] = i;
6282 } else if (!hashmap_get_from_hash(&subject2item,
6283 strhash(subject), subject)) {
6284 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6285 entry->i = i;
6286 hashmap_entry_init(&entry->entry,
6287 strhash(entry->subject));
6288 hashmap_put(&subject2item, &entry->entry);
6291 *commit_todo_item_at(&commit_todo, item->commit) = item;
6294 if (rearranged) {
6295 for (i = 0; i < todo_list->nr; i++) {
6296 enum todo_command command = todo_list->items[i].command;
6297 int cur = i;
6300 * Initially, all commands are 'pick's. If it is a
6301 * fixup or a squash now, we have rearranged it.
6303 if (is_fixup(command))
6304 continue;
6306 while (cur >= 0) {
6307 ALLOC_GROW(items, nr + 1, alloc);
6308 items[nr++] = todo_list->items[cur];
6309 cur = next[cur];
6313 FREE_AND_NULL(todo_list->items);
6314 todo_list->items = items;
6315 todo_list->nr = nr;
6316 todo_list->alloc = alloc;
6319 free(next);
6320 free(tail);
6321 for (i = 0; i < todo_list->nr; i++)
6322 free(subjects[i]);
6323 free(subjects);
6324 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6326 clear_commit_todo_item(&commit_todo);
6328 return 0;
6331 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6333 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6334 struct object_id cherry_pick_head, rebase_head;
6336 if (file_exists(git_path_seq_dir()))
6337 *whence = FROM_CHERRY_PICK_MULTI;
6338 if (file_exists(rebase_path()) &&
6339 !get_oid("REBASE_HEAD", &rebase_head) &&
6340 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
6341 oideq(&rebase_head, &cherry_pick_head))
6342 *whence = FROM_REBASE_PICK;
6343 else
6344 *whence = FROM_CHERRY_PICK_SINGLE;
6346 return 1;
6349 return 0;
6352 int sequencer_get_update_refs_state(const char *wt_dir,
6353 struct string_list *refs)
6355 int result = 0;
6356 FILE *fp = NULL;
6357 struct strbuf ref = STRBUF_INIT;
6358 struct strbuf hash = STRBUF_INIT;
6359 struct update_ref_record *rec = NULL;
6361 char *path = rebase_path_update_refs(wt_dir);
6363 fp = fopen(path, "r");
6364 if (!fp)
6365 goto cleanup;
6367 while (strbuf_getline(&ref, fp) != EOF) {
6368 struct string_list_item *item;
6370 CALLOC_ARRAY(rec, 1);
6372 if (strbuf_getline(&hash, fp) == EOF ||
6373 get_oid_hex(hash.buf, &rec->before)) {
6374 warning(_("update-refs file at '%s' is invalid"),
6375 path);
6376 result = -1;
6377 goto cleanup;
6380 if (strbuf_getline(&hash, fp) == EOF ||
6381 get_oid_hex(hash.buf, &rec->after)) {
6382 warning(_("update-refs file at '%s' is invalid"),
6383 path);
6384 result = -1;
6385 goto cleanup;
6388 item = string_list_insert(refs, ref.buf);
6389 item->util = rec;
6390 rec = NULL;
6393 cleanup:
6394 if (fp)
6395 fclose(fp);
6396 free(path);
6397 free(rec);
6398 strbuf_release(&ref);
6399 strbuf_release(&hash);
6400 return result;