fsmonitor: avoid memory leak in `fsm_settings__get_incompatible_msg()`
[git/debian.git] / sequencer.c
blob950733af2adf2a4156360cf2ca35bc92330e8f69
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "hook.h"
12 #include "exec-cmd.h"
13 #include "utf8.h"
14 #include "cache-tree.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "rerere.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
20 #include "refs.h"
21 #include "strvec.h"
22 #include "quote.h"
23 #include "trailer.h"
24 #include "log-tree.h"
25 #include "wt-status.h"
26 #include "hashmap.h"
27 #include "notes-utils.h"
28 #include "sigchain.h"
29 #include "unpack-trees.h"
30 #include "worktree.h"
31 #include "oidmap.h"
32 #include "oidset.h"
33 #include "commit-slab.h"
34 #include "alias.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
37 #include "reset.h"
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
41 static const char sign_off_header[] = "Signed-off-by: ";
42 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
44 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
46 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
48 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
49 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
50 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
51 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
53 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
55 * The file containing rebase commands, comments, and empty lines.
56 * This file is created by "git rebase -i" then edited by the user. As
57 * the lines are processed, they are removed from the front of this
58 * file and written to the tail of 'done'.
60 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
61 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
63 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
66 * The rebase command lines that have already been processed. A line
67 * is moved here when it is first handled, before any associated user
68 * actions.
70 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
72 * The file to keep track of how many commands were already processed (e.g.
73 * for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
77 * The file to keep track of how many commands are to be processed in total
78 * (e.g. for the prompt).
80 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
82 * The commit message that is planned to be used for any changes that
83 * need to be committed following a user interaction.
85 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
87 * The file into which is accumulated the suggested commit message for
88 * squash/fixup commands. When the first of a series of squash/fixups
89 * is seen, the file is created and the commit message from the
90 * previous commit and from the first squash/fixup commit are written
91 * to it. The commit message for each subsequent squash/fixup commit
92 * is appended to the file as it is processed.
94 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
96 * If the current series of squash/fixups has not yet included a squash
97 * command, then this file exists and holds the commit message of the
98 * original "pick" commit. (If the series ends without a "squash"
99 * command, then this can be used as the commit message of the combined
100 * commit without opening the editor.)
102 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
104 * This file contains the list fixup/squash commands that have been
105 * accumulated into message-fixup or message-squash so far.
107 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
109 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
110 * GIT_AUTHOR_DATE that will be used for the commit that is currently
111 * being rebased.
113 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
115 * When an "edit" rebase command is being processed, the SHA1 of the
116 * commit to be edited is recorded in this file. When "git rebase
117 * --continue" is executed, if there are any staged changes then they
118 * will be amended to the HEAD commit, but only provided the HEAD
119 * commit is still the commit to be edited. When any other rebase
120 * command is processed, this file is deleted.
122 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
124 * When we stop at a given patch via the "edit" command, this file contains
125 * the commit object name of the corresponding patch.
127 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
129 * For the post-rewrite hook, we make a list of rewritten commits and
130 * their new sha1s. The rewritten-pending list keeps the sha1s of
131 * commits that have been processed, but not committed yet,
132 * e.g. because they are waiting for a 'squash' command.
134 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
135 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
136 "rebase-merge/rewritten-pending")
139 * The path of the file containing the OID of the "squash onto" commit, i.e.
140 * the dummy commit used for `reset [new root]`.
142 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
145 * The path of the file listing refs that need to be deleted after the rebase
146 * finishes. This is used by the `label` command to record the need for cleanup.
148 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
151 * The following files are written by git-rebase just after parsing the
152 * command-line.
154 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
155 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
156 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
157 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
158 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
159 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
160 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
161 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
162 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
163 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
164 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
165 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
166 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
167 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
170 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
172 static int git_sequencer_config(const char *k, const char *v, void *cb)
174 struct replay_opts *opts = cb;
175 int status;
177 if (!strcmp(k, "commit.cleanup")) {
178 const char *s;
180 status = git_config_string(&s, k, v);
181 if (status)
182 return status;
184 if (!strcmp(s, "verbatim")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "whitespace")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
189 opts->explicit_cleanup = 1;
190 } else if (!strcmp(s, "strip")) {
191 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
192 opts->explicit_cleanup = 1;
193 } else if (!strcmp(s, "scissors")) {
194 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
195 opts->explicit_cleanup = 1;
196 } else {
197 warning(_("invalid commit message cleanup mode '%s'"),
201 free((char *)s);
202 return status;
205 if (!strcmp(k, "commit.gpgsign")) {
206 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
207 return 0;
210 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
211 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212 if (ret == 0) {
214 * pull.twohead is allowed to be multi-valued; we only
215 * care about the first value.
217 char *tmp = strchr(opts->default_strategy, ' ');
218 if (tmp)
219 *tmp = '\0';
221 return ret;
224 status = git_gpg_config(k, v, NULL);
225 if (status)
226 return status;
228 return git_diff_basic_config(k, v, NULL);
231 void sequencer_init_config(struct replay_opts *opts)
233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
234 git_config(git_sequencer_config, opts);
237 static inline int is_rebase_i(const struct replay_opts *opts)
239 return opts->action == REPLAY_INTERACTIVE_REBASE;
242 static const char *get_dir(const struct replay_opts *opts)
244 if (is_rebase_i(opts))
245 return rebase_path();
246 return git_path_seq_dir();
249 static const char *get_todo_path(const struct replay_opts *opts)
251 if (is_rebase_i(opts))
252 return rebase_path_todo();
253 return git_path_todo_file();
257 * Returns 0 for non-conforming footer
258 * Returns 1 for conforming footer
259 * Returns 2 when sob exists within conforming footer
260 * Returns 3 when sob exists within conforming footer as last entry
262 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
263 size_t ignore_footer)
265 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
266 struct trailer_info info;
267 size_t i;
268 int found_sob = 0, found_sob_last = 0;
269 char saved_char;
271 opts.no_divider = 1;
273 if (ignore_footer) {
274 saved_char = sb->buf[sb->len - ignore_footer];
275 sb->buf[sb->len - ignore_footer] = '\0';
278 trailer_info_get(&info, sb->buf, &opts);
280 if (ignore_footer)
281 sb->buf[sb->len - ignore_footer] = saved_char;
283 if (info.trailer_start == info.trailer_end)
284 return 0;
286 for (i = 0; i < info.trailer_nr; i++)
287 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
288 found_sob = 1;
289 if (i == info.trailer_nr - 1)
290 found_sob_last = 1;
293 trailer_info_release(&info);
295 if (found_sob_last)
296 return 3;
297 if (found_sob)
298 return 2;
299 return 1;
302 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
304 static struct strbuf buf = STRBUF_INIT;
306 strbuf_reset(&buf);
307 if (opts->gpg_sign)
308 sq_quotef(&buf, "-S%s", opts->gpg_sign);
309 return buf.buf;
312 int sequencer_remove_state(struct replay_opts *opts)
314 struct strbuf buf = STRBUF_INIT;
315 int i, ret = 0;
317 if (is_rebase_i(opts) &&
318 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319 char *p = buf.buf;
320 while (*p) {
321 char *eol = strchr(p, '\n');
322 if (eol)
323 *eol = '\0';
324 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
325 warning(_("could not delete '%s'"), p);
326 ret = -1;
328 if (!eol)
329 break;
330 p = eol + 1;
334 free(opts->gpg_sign);
335 free(opts->default_strategy);
336 free(opts->strategy);
337 for (i = 0; i < opts->xopts_nr; i++)
338 free(opts->xopts[i]);
339 free(opts->xopts);
340 strbuf_release(&opts->current_fixups);
342 strbuf_reset(&buf);
343 strbuf_addstr(&buf, get_dir(opts));
344 if (remove_dir_recursively(&buf, 0))
345 ret = error(_("could not remove '%s'"), buf.buf);
346 strbuf_release(&buf);
348 return ret;
351 static const char *action_name(const struct replay_opts *opts)
353 switch (opts->action) {
354 case REPLAY_REVERT:
355 return N_("revert");
356 case REPLAY_PICK:
357 return N_("cherry-pick");
358 case REPLAY_INTERACTIVE_REBASE:
359 return N_("rebase");
361 die(_("unknown action: %d"), opts->action);
364 struct commit_message {
365 char *parent_label;
366 char *label;
367 char *subject;
368 const char *message;
371 static const char *short_commit_name(struct commit *commit)
373 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
376 static int get_message(struct commit *commit, struct commit_message *out)
378 const char *abbrev, *subject;
379 int subject_len;
381 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
382 abbrev = short_commit_name(commit);
384 subject_len = find_commit_subject(out->message, &subject);
386 out->subject = xmemdupz(subject, subject_len);
387 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
388 out->parent_label = xstrfmt("parent of %s", out->label);
390 return 0;
393 static void free_message(struct commit *commit, struct commit_message *msg)
395 free(msg->parent_label);
396 free(msg->label);
397 free(msg->subject);
398 unuse_commit_buffer(commit, msg->message);
401 static void print_advice(struct repository *r, int show_hint,
402 struct replay_opts *opts)
404 char *msg = getenv("GIT_CHERRY_PICK_HELP");
406 if (msg) {
407 advise("%s\n", msg);
409 * A conflict has occurred but the porcelain
410 * (typically rebase --interactive) wants to take care
411 * of the commit itself so remove CHERRY_PICK_HEAD
413 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
414 NULL, 0);
415 return;
418 if (show_hint) {
419 if (opts->no_commit)
420 advise(_("after resolving the conflicts, mark the corrected paths\n"
421 "with 'git add <paths>' or 'git rm <paths>'"));
422 else if (opts->action == REPLAY_PICK)
423 advise(_("After resolving the conflicts, mark them with\n"
424 "\"git add/rm <pathspec>\", then run\n"
425 "\"git cherry-pick --continue\".\n"
426 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
427 "To abort and get back to the state before \"git cherry-pick\",\n"
428 "run \"git cherry-pick --abort\"."));
429 else if (opts->action == REPLAY_REVERT)
430 advise(_("After resolving the conflicts, mark them with\n"
431 "\"git add/rm <pathspec>\", then run\n"
432 "\"git revert --continue\".\n"
433 "You can instead skip this commit with \"git revert --skip\".\n"
434 "To abort and get back to the state before \"git revert\",\n"
435 "run \"git revert --abort\"."));
436 else
437 BUG("unexpected pick action in print_advice()");
441 static int write_message(const void *buf, size_t len, const char *filename,
442 int append_eol)
444 struct lock_file msg_file = LOCK_INIT;
446 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
447 if (msg_fd < 0)
448 return error_errno(_("could not lock '%s'"), filename);
449 if (write_in_full(msg_fd, buf, len) < 0) {
450 error_errno(_("could not write to '%s'"), filename);
451 rollback_lock_file(&msg_file);
452 return -1;
454 if (append_eol && write(msg_fd, "\n", 1) < 0) {
455 error_errno(_("could not write eol to '%s'"), filename);
456 rollback_lock_file(&msg_file);
457 return -1;
459 if (commit_lock_file(&msg_file) < 0)
460 return error(_("failed to finalize '%s'"), filename);
462 return 0;
465 int read_oneliner(struct strbuf *buf,
466 const char *path, unsigned flags)
468 int orig_len = buf->len;
470 if (strbuf_read_file(buf, path, 0) < 0) {
471 if ((flags & READ_ONELINER_WARN_MISSING) ||
472 (errno != ENOENT && errno != ENOTDIR))
473 warning_errno(_("could not read '%s'"), path);
474 return 0;
477 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
478 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
479 --buf->len;
480 buf->buf[buf->len] = '\0';
483 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
484 return 0;
486 return 1;
489 static struct tree *empty_tree(struct repository *r)
491 return lookup_tree(r, the_hash_algo->empty_tree);
494 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
496 if (repo_read_index_unmerged(repo))
497 return error_resolve_conflict(_(action_name(opts)));
499 error(_("your local changes would be overwritten by %s."),
500 _(action_name(opts)));
502 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
503 advise(_("commit your changes or stash them to proceed."));
504 return -1;
507 static void update_abort_safety_file(void)
509 struct object_id head;
511 /* Do nothing on a single-pick */
512 if (!file_exists(git_path_seq_dir()))
513 return;
515 if (!get_oid("HEAD", &head))
516 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
517 else
518 write_file(git_path_abort_safety_file(), "%s", "");
521 static int fast_forward_to(struct repository *r,
522 const struct object_id *to,
523 const struct object_id *from,
524 int unborn,
525 struct replay_opts *opts)
527 struct ref_transaction *transaction;
528 struct strbuf sb = STRBUF_INIT;
529 struct strbuf err = STRBUF_INIT;
531 repo_read_index(r);
532 if (checkout_fast_forward(r, from, to, 1))
533 return -1; /* the callee should have complained already */
535 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
537 transaction = ref_transaction_begin(&err);
538 if (!transaction ||
539 ref_transaction_update(transaction, "HEAD",
540 to, unborn && !is_rebase_i(opts) ?
541 null_oid() : from,
542 0, sb.buf, &err) ||
543 ref_transaction_commit(transaction, &err)) {
544 ref_transaction_free(transaction);
545 error("%s", err.buf);
546 strbuf_release(&sb);
547 strbuf_release(&err);
548 return -1;
551 strbuf_release(&sb);
552 strbuf_release(&err);
553 ref_transaction_free(transaction);
554 update_abort_safety_file();
555 return 0;
558 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
559 int use_editor)
561 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
562 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
563 COMMIT_MSG_CLEANUP_SPACE;
564 else if (!strcmp(cleanup_arg, "verbatim"))
565 return COMMIT_MSG_CLEANUP_NONE;
566 else if (!strcmp(cleanup_arg, "whitespace"))
567 return COMMIT_MSG_CLEANUP_SPACE;
568 else if (!strcmp(cleanup_arg, "strip"))
569 return COMMIT_MSG_CLEANUP_ALL;
570 else if (!strcmp(cleanup_arg, "scissors"))
571 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
572 COMMIT_MSG_CLEANUP_SPACE;
573 else
574 die(_("Invalid cleanup mode %s"), cleanup_arg);
578 * NB using int rather than enum cleanup_mode to stop clang's
579 * -Wtautological-constant-out-of-range-compare complaining that the comparison
580 * is always true.
582 static const char *describe_cleanup_mode(int cleanup_mode)
584 static const char *modes[] = { "whitespace",
585 "verbatim",
586 "scissors",
587 "strip" };
589 if (cleanup_mode < ARRAY_SIZE(modes))
590 return modes[cleanup_mode];
592 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
595 void append_conflicts_hint(struct index_state *istate,
596 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
598 int i;
600 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
601 strbuf_addch(msgbuf, '\n');
602 wt_status_append_cut_line(msgbuf);
603 strbuf_addch(msgbuf, comment_line_char);
606 strbuf_addch(msgbuf, '\n');
607 strbuf_commented_addf(msgbuf, "Conflicts:\n");
608 for (i = 0; i < istate->cache_nr;) {
609 const struct cache_entry *ce = istate->cache[i++];
610 if (ce_stage(ce)) {
611 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
612 while (i < istate->cache_nr &&
613 !strcmp(ce->name, istate->cache[i]->name))
614 i++;
619 static int do_recursive_merge(struct repository *r,
620 struct commit *base, struct commit *next,
621 const char *base_label, const char *next_label,
622 struct object_id *head, struct strbuf *msgbuf,
623 struct replay_opts *opts)
625 struct merge_options o;
626 struct merge_result result;
627 struct tree *next_tree, *base_tree, *head_tree;
628 int clean, show_output;
629 int i;
630 struct lock_file index_lock = LOCK_INIT;
632 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
633 return -1;
635 repo_read_index(r);
637 init_merge_options(&o, r);
638 o.ancestor = base ? base_label : "(empty tree)";
639 o.branch1 = "HEAD";
640 o.branch2 = next ? next_label : "(empty tree)";
641 if (is_rebase_i(opts))
642 o.buffer_output = 2;
643 o.show_rename_progress = 1;
645 head_tree = parse_tree_indirect(head);
646 next_tree = next ? get_commit_tree(next) : empty_tree(r);
647 base_tree = base ? get_commit_tree(base) : empty_tree(r);
649 for (i = 0; i < opts->xopts_nr; i++)
650 parse_merge_opt(&o, opts->xopts[i]);
652 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
653 memset(&result, 0, sizeof(result));
654 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
655 &result);
656 show_output = !is_rebase_i(opts) || !result.clean;
658 * TODO: merge_switch_to_result will update index/working tree;
659 * we only really want to do that if !result.clean || this is
660 * the final patch to be picked. But determining this is the
661 * final patch would take some work, and "head_tree" would need
662 * to be replace with the tree the index matched before we
663 * started doing any picks.
665 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
666 clean = result.clean;
667 } else {
668 ensure_full_index(r->index);
669 clean = merge_trees(&o, head_tree, next_tree, base_tree);
670 if (is_rebase_i(opts) && clean <= 0)
671 fputs(o.obuf.buf, stdout);
672 strbuf_release(&o.obuf);
674 if (clean < 0) {
675 rollback_lock_file(&index_lock);
676 return clean;
679 if (write_locked_index(r->index, &index_lock,
680 COMMIT_LOCK | SKIP_IF_UNCHANGED))
682 * TRANSLATORS: %s will be "revert", "cherry-pick" or
683 * "rebase".
685 return error(_("%s: Unable to write new index file"),
686 _(action_name(opts)));
688 if (!clean)
689 append_conflicts_hint(r->index, msgbuf,
690 opts->default_msg_cleanup);
692 return !clean;
695 static struct object_id *get_cache_tree_oid(struct index_state *istate)
697 if (!cache_tree_fully_valid(istate->cache_tree))
698 if (cache_tree_update(istate, 0)) {
699 error(_("unable to update cache tree"));
700 return NULL;
703 return &istate->cache_tree->oid;
706 static int is_index_unchanged(struct repository *r)
708 struct object_id head_oid, *cache_tree_oid;
709 struct commit *head_commit;
710 struct index_state *istate = r->index;
712 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
713 return error(_("could not resolve HEAD commit"));
715 head_commit = lookup_commit(r, &head_oid);
718 * If head_commit is NULL, check_commit, called from
719 * lookup_commit, would have indicated that head_commit is not
720 * a commit object already. parse_commit() will return failure
721 * without further complaints in such a case. Otherwise, if
722 * the commit is invalid, parse_commit() will complain. So
723 * there is nothing for us to say here. Just return failure.
725 if (parse_commit(head_commit))
726 return -1;
728 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
729 return -1;
731 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
734 static int write_author_script(const char *message)
736 struct strbuf buf = STRBUF_INIT;
737 const char *eol;
738 int res;
740 for (;;)
741 if (!*message || starts_with(message, "\n")) {
742 missing_author:
743 /* Missing 'author' line? */
744 unlink(rebase_path_author_script());
745 return 0;
746 } else if (skip_prefix(message, "author ", &message))
747 break;
748 else if ((eol = strchr(message, '\n')))
749 message = eol + 1;
750 else
751 goto missing_author;
753 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
754 while (*message && *message != '\n' && *message != '\r')
755 if (skip_prefix(message, " <", &message))
756 break;
757 else if (*message != '\'')
758 strbuf_addch(&buf, *(message++));
759 else
760 strbuf_addf(&buf, "'\\%c'", *(message++));
761 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
762 while (*message && *message != '\n' && *message != '\r')
763 if (skip_prefix(message, "> ", &message))
764 break;
765 else if (*message != '\'')
766 strbuf_addch(&buf, *(message++));
767 else
768 strbuf_addf(&buf, "'\\%c'", *(message++));
769 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
770 while (*message && *message != '\n' && *message != '\r')
771 if (*message != '\'')
772 strbuf_addch(&buf, *(message++));
773 else
774 strbuf_addf(&buf, "'\\%c'", *(message++));
775 strbuf_addch(&buf, '\'');
776 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
777 strbuf_release(&buf);
778 return res;
782 * Take a series of KEY='VALUE' lines where VALUE part is
783 * sq-quoted, and append <KEY, VALUE> at the end of the string list
785 static int parse_key_value_squoted(char *buf, struct string_list *list)
787 while (*buf) {
788 struct string_list_item *item;
789 char *np;
790 char *cp = strchr(buf, '=');
791 if (!cp) {
792 np = strchrnul(buf, '\n');
793 return error(_("no key present in '%.*s'"),
794 (int) (np - buf), buf);
796 np = strchrnul(cp, '\n');
797 *cp++ = '\0';
798 item = string_list_append(list, buf);
800 buf = np + (*np == '\n');
801 *np = '\0';
802 cp = sq_dequote(cp);
803 if (!cp)
804 return error(_("unable to dequote value of '%s'"),
805 item->string);
806 item->util = xstrdup(cp);
808 return 0;
812 * Reads and parses the state directory's "author-script" file, and sets name,
813 * email and date accordingly.
814 * Returns 0 on success, -1 if the file could not be parsed.
816 * The author script is of the format:
818 * GIT_AUTHOR_NAME='$author_name'
819 * GIT_AUTHOR_EMAIL='$author_email'
820 * GIT_AUTHOR_DATE='$author_date'
822 * where $author_name, $author_email and $author_date are quoted. We are strict
823 * with our parsing, as the file was meant to be eval'd in the now-removed
824 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
825 * from what this function expects, it is better to bail out than to do
826 * something that the user does not expect.
828 int read_author_script(const char *path, char **name, char **email, char **date,
829 int allow_missing)
831 struct strbuf buf = STRBUF_INIT;
832 struct string_list kv = STRING_LIST_INIT_DUP;
833 int retval = -1; /* assume failure */
834 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
836 if (strbuf_read_file(&buf, path, 256) <= 0) {
837 strbuf_release(&buf);
838 if (errno == ENOENT && allow_missing)
839 return 0;
840 else
841 return error_errno(_("could not open '%s' for reading"),
842 path);
845 if (parse_key_value_squoted(buf.buf, &kv))
846 goto finish;
848 for (i = 0; i < kv.nr; i++) {
849 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
850 if (name_i != -2)
851 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
852 else
853 name_i = i;
854 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
855 if (email_i != -2)
856 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
857 else
858 email_i = i;
859 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
860 if (date_i != -2)
861 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
862 else
863 date_i = i;
864 } else {
865 err = error(_("unknown variable '%s'"),
866 kv.items[i].string);
869 if (name_i == -2)
870 error(_("missing 'GIT_AUTHOR_NAME'"));
871 if (email_i == -2)
872 error(_("missing 'GIT_AUTHOR_EMAIL'"));
873 if (date_i == -2)
874 error(_("missing 'GIT_AUTHOR_DATE'"));
875 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
876 goto finish;
877 *name = kv.items[name_i].util;
878 *email = kv.items[email_i].util;
879 *date = kv.items[date_i].util;
880 retval = 0;
881 finish:
882 string_list_clear(&kv, !!retval);
883 strbuf_release(&buf);
884 return retval;
888 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
889 * file with shell quoting into struct strvec. Returns -1 on
890 * error, 0 otherwise.
892 static int read_env_script(struct strvec *env)
894 char *name, *email, *date;
896 if (read_author_script(rebase_path_author_script(),
897 &name, &email, &date, 0))
898 return -1;
900 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
901 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
902 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
903 free(name);
904 free(email);
905 free(date);
907 return 0;
910 static char *get_author(const char *message)
912 size_t len;
913 const char *a;
915 a = find_commit_header(message, "author", &len);
916 if (a)
917 return xmemdupz(a, len);
919 return NULL;
922 static const char *author_date_from_env(const struct strvec *env)
924 int i;
925 const char *date;
927 for (i = 0; i < env->nr; i++)
928 if (skip_prefix(env->v[i],
929 "GIT_AUTHOR_DATE=", &date))
930 return date;
932 * If GIT_AUTHOR_DATE is missing we should have already errored out when
933 * reading the script
935 BUG("GIT_AUTHOR_DATE missing from author script");
938 static const char staged_changes_advice[] =
939 N_("you have staged changes in your working tree\n"
940 "If these changes are meant to be squashed into the previous commit, run:\n"
941 "\n"
942 " git commit --amend %s\n"
943 "\n"
944 "If they are meant to go into a new commit, run:\n"
945 "\n"
946 " git commit %s\n"
947 "\n"
948 "In both cases, once you're done, continue with:\n"
949 "\n"
950 " git rebase --continue\n");
952 #define ALLOW_EMPTY (1<<0)
953 #define EDIT_MSG (1<<1)
954 #define AMEND_MSG (1<<2)
955 #define CLEANUP_MSG (1<<3)
956 #define VERIFY_MSG (1<<4)
957 #define CREATE_ROOT_COMMIT (1<<5)
958 #define VERBATIM_MSG (1<<6)
960 static int run_command_silent_on_success(struct child_process *cmd)
962 struct strbuf buf = STRBUF_INIT;
963 int rc;
965 cmd->stdout_to_stderr = 1;
966 rc = pipe_command(cmd,
967 NULL, 0,
968 NULL, 0,
969 &buf, 0);
971 if (rc)
972 fputs(buf.buf, stderr);
973 strbuf_release(&buf);
974 return rc;
978 * If we are cherry-pick, and if the merge did not result in
979 * hand-editing, we will hit this commit and inherit the original
980 * author date and name.
982 * If we are revert, or if our cherry-pick results in a hand merge,
983 * we had better say that the current user is responsible for that.
985 * An exception is when run_git_commit() is called during an
986 * interactive rebase: in that case, we will want to retain the
987 * author metadata.
989 static int run_git_commit(const char *defmsg,
990 struct replay_opts *opts,
991 unsigned int flags)
993 struct child_process cmd = CHILD_PROCESS_INIT;
995 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
996 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
998 cmd.git_cmd = 1;
1000 if (is_rebase_i(opts) &&
1001 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1002 !(!defmsg && (flags & AMEND_MSG))) &&
1003 read_env_script(&cmd.env)) {
1004 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1006 return error(_(staged_changes_advice),
1007 gpg_opt, gpg_opt);
1010 if (opts->committer_date_is_author_date)
1011 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1012 opts->ignore_date ?
1013 "" :
1014 author_date_from_env(&cmd.env));
1015 if (opts->ignore_date)
1016 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1018 strvec_push(&cmd.args, "commit");
1020 if (!(flags & VERIFY_MSG))
1021 strvec_push(&cmd.args, "-n");
1022 if ((flags & AMEND_MSG))
1023 strvec_push(&cmd.args, "--amend");
1024 if (opts->gpg_sign)
1025 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1026 else
1027 strvec_push(&cmd.args, "--no-gpg-sign");
1028 if (defmsg)
1029 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1030 else if (!(flags & EDIT_MSG))
1031 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1032 if ((flags & CLEANUP_MSG))
1033 strvec_push(&cmd.args, "--cleanup=strip");
1034 if ((flags & VERBATIM_MSG))
1035 strvec_push(&cmd.args, "--cleanup=verbatim");
1036 if ((flags & EDIT_MSG))
1037 strvec_push(&cmd.args, "-e");
1038 else if (!(flags & CLEANUP_MSG) &&
1039 !opts->signoff && !opts->record_origin &&
1040 !opts->explicit_cleanup)
1041 strvec_push(&cmd.args, "--cleanup=verbatim");
1043 if ((flags & ALLOW_EMPTY))
1044 strvec_push(&cmd.args, "--allow-empty");
1046 if (!(flags & EDIT_MSG))
1047 strvec_push(&cmd.args, "--allow-empty-message");
1049 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1050 return run_command_silent_on_success(&cmd);
1051 else
1052 return run_command(&cmd);
1055 static int rest_is_empty(const struct strbuf *sb, int start)
1057 int i, eol;
1058 const char *nl;
1060 /* Check if the rest is just whitespace and Signed-off-by's. */
1061 for (i = start; i < sb->len; i++) {
1062 nl = memchr(sb->buf + i, '\n', sb->len - i);
1063 if (nl)
1064 eol = nl - sb->buf;
1065 else
1066 eol = sb->len;
1068 if (strlen(sign_off_header) <= eol - i &&
1069 starts_with(sb->buf + i, sign_off_header)) {
1070 i = eol;
1071 continue;
1073 while (i < eol)
1074 if (!isspace(sb->buf[i++]))
1075 return 0;
1078 return 1;
1081 void cleanup_message(struct strbuf *msgbuf,
1082 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1084 if (verbose || /* Truncate the message just before the diff, if any. */
1085 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1086 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1087 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1088 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1092 * Find out if the message in the strbuf contains only whitespace and
1093 * Signed-off-by lines.
1095 int message_is_empty(const struct strbuf *sb,
1096 enum commit_msg_cleanup_mode cleanup_mode)
1098 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1099 return 0;
1100 return rest_is_empty(sb, 0);
1104 * See if the user edited the message in the editor or left what
1105 * was in the template intact
1107 int template_untouched(const struct strbuf *sb, const char *template_file,
1108 enum commit_msg_cleanup_mode cleanup_mode)
1110 struct strbuf tmpl = STRBUF_INIT;
1111 const char *start;
1113 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1114 return 0;
1116 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1117 return 0;
1119 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1120 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1121 start = sb->buf;
1122 strbuf_release(&tmpl);
1123 return rest_is_empty(sb, start - sb->buf);
1126 int update_head_with_reflog(const struct commit *old_head,
1127 const struct object_id *new_head,
1128 const char *action, const struct strbuf *msg,
1129 struct strbuf *err)
1131 struct ref_transaction *transaction;
1132 struct strbuf sb = STRBUF_INIT;
1133 const char *nl;
1134 int ret = 0;
1136 if (action) {
1137 strbuf_addstr(&sb, action);
1138 strbuf_addstr(&sb, ": ");
1141 nl = strchr(msg->buf, '\n');
1142 if (nl) {
1143 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1144 } else {
1145 strbuf_addbuf(&sb, msg);
1146 strbuf_addch(&sb, '\n');
1149 transaction = ref_transaction_begin(err);
1150 if (!transaction ||
1151 ref_transaction_update(transaction, "HEAD", new_head,
1152 old_head ? &old_head->object.oid : null_oid(),
1153 0, sb.buf, err) ||
1154 ref_transaction_commit(transaction, err)) {
1155 ret = -1;
1157 ref_transaction_free(transaction);
1158 strbuf_release(&sb);
1160 return ret;
1163 static int run_rewrite_hook(const struct object_id *oldoid,
1164 const struct object_id *newoid)
1166 struct child_process proc = CHILD_PROCESS_INIT;
1167 int code;
1168 struct strbuf sb = STRBUF_INIT;
1169 const char *hook_path = find_hook("post-rewrite");
1171 if (!hook_path)
1172 return 0;
1174 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1175 proc.in = -1;
1176 proc.stdout_to_stderr = 1;
1177 proc.trace2_hook_name = "post-rewrite";
1179 code = start_command(&proc);
1180 if (code)
1181 return code;
1182 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1183 sigchain_push(SIGPIPE, SIG_IGN);
1184 write_in_full(proc.in, sb.buf, sb.len);
1185 close(proc.in);
1186 strbuf_release(&sb);
1187 sigchain_pop(SIGPIPE);
1188 return finish_command(&proc);
1191 void commit_post_rewrite(struct repository *r,
1192 const struct commit *old_head,
1193 const struct object_id *new_head)
1195 struct notes_rewrite_cfg *cfg;
1197 cfg = init_copy_notes_for_rewrite("amend");
1198 if (cfg) {
1199 /* we are amending, so old_head is not NULL */
1200 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1201 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1203 run_rewrite_hook(&old_head->object.oid, new_head);
1206 static int run_prepare_commit_msg_hook(struct repository *r,
1207 struct strbuf *msg,
1208 const char *commit)
1210 int ret = 0;
1211 const char *name, *arg1 = NULL, *arg2 = NULL;
1213 name = git_path_commit_editmsg();
1214 if (write_message(msg->buf, msg->len, name, 0))
1215 return -1;
1217 if (commit) {
1218 arg1 = "commit";
1219 arg2 = commit;
1220 } else {
1221 arg1 = "message";
1223 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1224 arg1, arg2, NULL))
1225 ret = error(_("'prepare-commit-msg' hook failed"));
1227 return ret;
1230 static const char implicit_ident_advice_noconfig[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly. Run the\n"
1234 "following command and follow the instructions in your editor to edit\n"
1235 "your configuration file:\n"
1236 "\n"
1237 " git config --global --edit\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 " git commit --amend --reset-author\n");
1243 static const char implicit_ident_advice_config[] =
1244 N_("Your name and email address were configured automatically based\n"
1245 "on your username and hostname. Please check that they are accurate.\n"
1246 "You can suppress this message by setting them explicitly:\n"
1247 "\n"
1248 " git config --global user.name \"Your Name\"\n"
1249 " git config --global user.email you@example.com\n"
1250 "\n"
1251 "After doing this, you may fix the identity used for this commit with:\n"
1252 "\n"
1253 " git commit --amend --reset-author\n");
1255 static const char *implicit_ident_advice(void)
1257 char *user_config = interpolate_path("~/.gitconfig", 0);
1258 char *xdg_config = xdg_config_home("config");
1259 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1261 free(user_config);
1262 free(xdg_config);
1264 if (config_exists)
1265 return _(implicit_ident_advice_config);
1266 else
1267 return _(implicit_ident_advice_noconfig);
1271 void print_commit_summary(struct repository *r,
1272 const char *prefix,
1273 const struct object_id *oid,
1274 unsigned int flags)
1276 struct rev_info rev;
1277 struct commit *commit;
1278 struct strbuf format = STRBUF_INIT;
1279 const char *head;
1280 struct pretty_print_context pctx = {0};
1281 struct strbuf author_ident = STRBUF_INIT;
1282 struct strbuf committer_ident = STRBUF_INIT;
1283 struct ref_store *refs;
1285 commit = lookup_commit(r, oid);
1286 if (!commit)
1287 die(_("couldn't look up newly created commit"));
1288 if (parse_commit(commit))
1289 die(_("could not parse newly created commit"));
1291 strbuf_addstr(&format, "format:%h] %s");
1293 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1294 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1295 if (strbuf_cmp(&author_ident, &committer_ident)) {
1296 strbuf_addstr(&format, "\n Author: ");
1297 strbuf_addbuf_percentquote(&format, &author_ident);
1299 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1300 struct strbuf date = STRBUF_INIT;
1302 format_commit_message(commit, "%ad", &date, &pctx);
1303 strbuf_addstr(&format, "\n Date: ");
1304 strbuf_addbuf_percentquote(&format, &date);
1305 strbuf_release(&date);
1307 if (!committer_ident_sufficiently_given()) {
1308 strbuf_addstr(&format, "\n Committer: ");
1309 strbuf_addbuf_percentquote(&format, &committer_ident);
1310 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1311 strbuf_addch(&format, '\n');
1312 strbuf_addstr(&format, implicit_ident_advice());
1315 strbuf_release(&author_ident);
1316 strbuf_release(&committer_ident);
1318 repo_init_revisions(r, &rev, prefix);
1319 setup_revisions(0, NULL, &rev, NULL);
1321 rev.diff = 1;
1322 rev.diffopt.output_format =
1323 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1325 rev.verbose_header = 1;
1326 rev.show_root_diff = 1;
1327 get_commit_format(format.buf, &rev);
1328 rev.always_show_header = 0;
1329 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1330 diff_setup_done(&rev.diffopt);
1332 refs = get_main_ref_store(the_repository);
1333 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1334 if (!head)
1335 die(_("unable to resolve HEAD after creating commit"));
1336 if (!strcmp(head, "HEAD"))
1337 head = _("detached HEAD");
1338 else
1339 skip_prefix(head, "refs/heads/", &head);
1340 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1341 _(" (root-commit)") : "");
1343 if (!log_tree_commit(&rev, commit)) {
1344 rev.always_show_header = 1;
1345 rev.use_terminator = 1;
1346 log_tree_commit(&rev, commit);
1349 release_revisions(&rev);
1350 strbuf_release(&format);
1353 static int parse_head(struct repository *r, struct commit **head)
1355 struct commit *current_head;
1356 struct object_id oid;
1358 if (get_oid("HEAD", &oid)) {
1359 current_head = NULL;
1360 } else {
1361 current_head = lookup_commit_reference(r, &oid);
1362 if (!current_head)
1363 return error(_("could not parse HEAD"));
1364 if (!oideq(&oid, &current_head->object.oid)) {
1365 warning(_("HEAD %s is not a commit!"),
1366 oid_to_hex(&oid));
1368 if (parse_commit(current_head))
1369 return error(_("could not parse HEAD commit"));
1371 *head = current_head;
1373 return 0;
1377 * Try to commit without forking 'git commit'. In some cases we need
1378 * to run 'git commit' to display an error message
1380 * Returns:
1381 * -1 - error unable to commit
1382 * 0 - success
1383 * 1 - run 'git commit'
1385 static int try_to_commit(struct repository *r,
1386 struct strbuf *msg, const char *author,
1387 struct replay_opts *opts, unsigned int flags,
1388 struct object_id *oid)
1390 struct object_id tree;
1391 struct commit *current_head = NULL;
1392 struct commit_list *parents = NULL;
1393 struct commit_extra_header *extra = NULL;
1394 struct strbuf err = STRBUF_INIT;
1395 struct strbuf commit_msg = STRBUF_INIT;
1396 char *amend_author = NULL;
1397 const char *committer = NULL;
1398 const char *hook_commit = NULL;
1399 enum commit_msg_cleanup_mode cleanup;
1400 int res = 0;
1402 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1403 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1405 if (parse_head(r, &current_head))
1406 return -1;
1408 if (flags & AMEND_MSG) {
1409 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1410 const char *out_enc = get_commit_output_encoding();
1411 const char *message = logmsg_reencode(current_head, NULL,
1412 out_enc);
1414 if (!msg) {
1415 const char *orig_message = NULL;
1417 find_commit_subject(message, &orig_message);
1418 msg = &commit_msg;
1419 strbuf_addstr(msg, orig_message);
1420 hook_commit = "HEAD";
1422 author = amend_author = get_author(message);
1423 unuse_commit_buffer(current_head, message);
1424 if (!author) {
1425 res = error(_("unable to parse commit author"));
1426 goto out;
1428 parents = copy_commit_list(current_head->parents);
1429 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1430 } else if (current_head &&
1431 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1432 commit_list_insert(current_head, &parents);
1435 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1436 res = error(_("git write-tree failed to write a tree"));
1437 goto out;
1440 if (!(flags & ALLOW_EMPTY)) {
1441 struct commit *first_parent = current_head;
1443 if (flags & AMEND_MSG) {
1444 if (current_head->parents) {
1445 first_parent = current_head->parents->item;
1446 if (repo_parse_commit(r, first_parent)) {
1447 res = error(_("could not parse HEAD commit"));
1448 goto out;
1450 } else {
1451 first_parent = NULL;
1454 if (oideq(first_parent
1455 ? get_commit_tree_oid(first_parent)
1456 : the_hash_algo->empty_tree,
1457 &tree)) {
1458 res = 1; /* run 'git commit' to display error message */
1459 goto out;
1463 if (hook_exists("prepare-commit-msg")) {
1464 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1465 if (res)
1466 goto out;
1467 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1468 2048) < 0) {
1469 res = error_errno(_("unable to read commit message "
1470 "from '%s'"),
1471 git_path_commit_editmsg());
1472 goto out;
1474 msg = &commit_msg;
1477 if (flags & CLEANUP_MSG)
1478 cleanup = COMMIT_MSG_CLEANUP_ALL;
1479 else if (flags & VERBATIM_MSG)
1480 cleanup = COMMIT_MSG_CLEANUP_NONE;
1481 else if ((opts->signoff || opts->record_origin) &&
1482 !opts->explicit_cleanup)
1483 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1484 else
1485 cleanup = opts->default_msg_cleanup;
1487 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1488 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1489 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1490 res = 1; /* run 'git commit' to display error message */
1491 goto out;
1494 if (opts->committer_date_is_author_date) {
1495 struct ident_split id;
1496 struct strbuf date = STRBUF_INIT;
1498 if (!opts->ignore_date) {
1499 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1500 res = error(_("invalid author identity '%s'"),
1501 author);
1502 goto out;
1504 if (!id.date_begin) {
1505 res = error(_(
1506 "corrupt author: missing date information"));
1507 goto out;
1509 strbuf_addf(&date, "@%.*s %.*s",
1510 (int)(id.date_end - id.date_begin),
1511 id.date_begin,
1512 (int)(id.tz_end - id.tz_begin),
1513 id.tz_begin);
1514 } else {
1515 reset_ident_date();
1517 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1518 getenv("GIT_COMMITTER_EMAIL"),
1519 WANT_COMMITTER_IDENT,
1520 opts->ignore_date ? NULL : date.buf,
1521 IDENT_STRICT);
1522 strbuf_release(&date);
1523 } else {
1524 reset_ident_date();
1527 if (opts->ignore_date) {
1528 struct ident_split id;
1529 char *name, *email;
1531 if (split_ident_line(&id, author, strlen(author)) < 0) {
1532 error(_("invalid author identity '%s'"), author);
1533 goto out;
1535 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1536 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1537 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1538 IDENT_STRICT);
1539 free(name);
1540 free(email);
1543 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1544 author, committer, opts->gpg_sign, extra)) {
1545 res = error(_("failed to write commit object"));
1546 goto out;
1549 if (update_head_with_reflog(current_head, oid,
1550 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1551 res = error("%s", err.buf);
1552 goto out;
1555 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1556 if (flags & AMEND_MSG)
1557 commit_post_rewrite(r, current_head, oid);
1559 out:
1560 free_commit_extra_headers(extra);
1561 strbuf_release(&err);
1562 strbuf_release(&commit_msg);
1563 free(amend_author);
1565 return res;
1568 static int write_rebase_head(struct object_id *oid)
1570 if (update_ref("rebase", "REBASE_HEAD", oid,
1571 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1572 return error(_("could not update %s"), "REBASE_HEAD");
1574 return 0;
1577 static int do_commit(struct repository *r,
1578 const char *msg_file, const char *author,
1579 struct replay_opts *opts, unsigned int flags,
1580 struct object_id *oid)
1582 int res = 1;
1584 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1585 struct object_id oid;
1586 struct strbuf sb = STRBUF_INIT;
1588 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1589 return error_errno(_("unable to read commit message "
1590 "from '%s'"),
1591 msg_file);
1593 res = try_to_commit(r, msg_file ? &sb : NULL,
1594 author, opts, flags, &oid);
1595 strbuf_release(&sb);
1596 if (!res) {
1597 refs_delete_ref(get_main_ref_store(r), "",
1598 "CHERRY_PICK_HEAD", NULL, 0);
1599 unlink(git_path_merge_msg(r));
1600 if (!is_rebase_i(opts))
1601 print_commit_summary(r, NULL, &oid,
1602 SUMMARY_SHOW_AUTHOR_DATE);
1603 return res;
1606 if (res == 1) {
1607 if (is_rebase_i(opts) && oid)
1608 if (write_rebase_head(oid))
1609 return -1;
1610 return run_git_commit(msg_file, opts, flags);
1613 return res;
1616 static int is_original_commit_empty(struct commit *commit)
1618 const struct object_id *ptree_oid;
1620 if (parse_commit(commit))
1621 return error(_("could not parse commit %s"),
1622 oid_to_hex(&commit->object.oid));
1623 if (commit->parents) {
1624 struct commit *parent = commit->parents->item;
1625 if (parse_commit(parent))
1626 return error(_("could not parse parent commit %s"),
1627 oid_to_hex(&parent->object.oid));
1628 ptree_oid = get_commit_tree_oid(parent);
1629 } else {
1630 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1633 return oideq(ptree_oid, get_commit_tree_oid(commit));
1637 * Should empty commits be allowed? Return status:
1638 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1639 * 0: Halt on empty commit
1640 * 1: Allow empty commit
1641 * 2: Drop empty commit
1643 static int allow_empty(struct repository *r,
1644 struct replay_opts *opts,
1645 struct commit *commit)
1647 int index_unchanged, originally_empty;
1650 * Four cases:
1652 * (1) we do not allow empty at all and error out.
1654 * (2) we allow ones that were initially empty, and
1655 * just drop the ones that become empty
1657 * (3) we allow ones that were initially empty, but
1658 * halt for the ones that become empty;
1660 * (4) we allow both.
1662 if (!opts->allow_empty)
1663 return 0; /* let "git commit" barf as necessary */
1665 index_unchanged = is_index_unchanged(r);
1666 if (index_unchanged < 0)
1667 return index_unchanged;
1668 if (!index_unchanged)
1669 return 0; /* we do not have to say --allow-empty */
1671 if (opts->keep_redundant_commits)
1672 return 1;
1674 originally_empty = is_original_commit_empty(commit);
1675 if (originally_empty < 0)
1676 return originally_empty;
1677 if (originally_empty)
1678 return 1;
1679 else if (opts->drop_redundant_commits)
1680 return 2;
1681 else
1682 return 0;
1685 static struct {
1686 char c;
1687 const char *str;
1688 } todo_command_info[] = {
1689 { 'p', "pick" },
1690 { 0, "revert" },
1691 { 'e', "edit" },
1692 { 'r', "reword" },
1693 { 'f', "fixup" },
1694 { 's', "squash" },
1695 { 'x', "exec" },
1696 { 'b', "break" },
1697 { 'l', "label" },
1698 { 't', "reset" },
1699 { 'm', "merge" },
1700 { 0, "noop" },
1701 { 'd', "drop" },
1702 { 0, NULL }
1705 static const char *command_to_string(const enum todo_command command)
1707 if (command < TODO_COMMENT)
1708 return todo_command_info[command].str;
1709 die(_("unknown command: %d"), command);
1712 static char command_to_char(const enum todo_command command)
1714 if (command < TODO_COMMENT)
1715 return todo_command_info[command].c;
1716 return comment_line_char;
1719 static int is_noop(const enum todo_command command)
1721 return TODO_NOOP <= command;
1724 static int is_fixup(enum todo_command command)
1726 return command == TODO_FIXUP || command == TODO_SQUASH;
1729 /* Does this command create a (non-merge) commit? */
1730 static int is_pick_or_similar(enum todo_command command)
1732 switch (command) {
1733 case TODO_PICK:
1734 case TODO_REVERT:
1735 case TODO_EDIT:
1736 case TODO_REWORD:
1737 case TODO_FIXUP:
1738 case TODO_SQUASH:
1739 return 1;
1740 default:
1741 return 0;
1745 enum todo_item_flags {
1746 TODO_EDIT_MERGE_MSG = (1 << 0),
1747 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1748 TODO_EDIT_FIXUP_MSG = (1 << 2),
1751 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1752 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1753 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1754 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1755 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1757 static int is_fixup_flag(enum todo_command command, unsigned flag)
1759 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1760 (flag & TODO_EDIT_FIXUP_MSG));
1764 * Wrapper around strbuf_add_commented_lines() which avoids double
1765 * commenting commit subjects.
1767 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1769 const char *s = str;
1770 while (len > 0 && s[0] == comment_line_char) {
1771 size_t count;
1772 const char *n = memchr(s, '\n', len);
1773 if (!n)
1774 count = len;
1775 else
1776 count = n - s + 1;
1777 strbuf_add(buf, s, count);
1778 s += count;
1779 len -= count;
1781 strbuf_add_commented_lines(buf, s, len);
1784 /* Does the current fixup chain contain a squash command? */
1785 static int seen_squash(struct replay_opts *opts)
1787 return starts_with(opts->current_fixups.buf, "squash") ||
1788 strstr(opts->current_fixups.buf, "\nsquash");
1791 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1793 strbuf_setlen(buf1, 2);
1794 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1795 strbuf_addch(buf1, '\n');
1796 strbuf_setlen(buf2, 2);
1797 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1798 strbuf_addch(buf2, '\n');
1802 * Comment out any un-commented commit messages, updating the message comments
1803 * to say they will be skipped but do not comment out the empty lines that
1804 * surround commit messages and their comments.
1806 static void update_squash_message_for_fixup(struct strbuf *msg)
1808 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1809 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1810 const char *s, *start;
1811 char *orig_msg;
1812 size_t orig_msg_len;
1813 int i = 1;
1815 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1816 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1817 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1818 while (s) {
1819 const char *next;
1820 size_t off;
1821 if (skip_prefix(s, buf1.buf, &next)) {
1823 * Copy the last message, preserving the blank line
1824 * preceding the current line
1826 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1827 copy_lines(msg, start, s - start - off);
1828 if (off)
1829 strbuf_addch(msg, '\n');
1831 * The next message needs to be commented out but the
1832 * message header is already commented out so just copy
1833 * it and the blank line that follows it.
1835 strbuf_addbuf(msg, &buf2);
1836 if (*next == '\n')
1837 strbuf_addch(msg, *next++);
1838 start = s = next;
1839 copy_lines = add_commented_lines;
1840 update_comment_bufs(&buf1, &buf2, ++i);
1841 } else if (skip_prefix(s, buf2.buf, &next)) {
1842 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1843 copy_lines(msg, start, s - start - off);
1844 start = s - off;
1845 s = next;
1846 copy_lines = strbuf_add;
1847 update_comment_bufs(&buf1, &buf2, ++i);
1848 } else {
1849 s = strchr(s, '\n');
1850 if (s)
1851 s++;
1854 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1855 free(orig_msg);
1856 strbuf_release(&buf1);
1857 strbuf_release(&buf2);
1860 static int append_squash_message(struct strbuf *buf, const char *body,
1861 enum todo_command command, struct replay_opts *opts,
1862 unsigned flag)
1864 const char *fixup_msg;
1865 size_t commented_len = 0, fixup_off;
1867 * amend is non-interactive and not normally used with fixup!
1868 * or squash! commits, so only comment out those subjects when
1869 * squashing commit messages.
1871 if (starts_with(body, "amend!") ||
1872 ((command == TODO_SQUASH || seen_squash(opts)) &&
1873 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1874 commented_len = commit_subject_length(body);
1876 strbuf_addf(buf, "\n%c ", comment_line_char);
1877 strbuf_addf(buf, _(nth_commit_msg_fmt),
1878 ++opts->current_fixup_count + 1);
1879 strbuf_addstr(buf, "\n\n");
1880 strbuf_add_commented_lines(buf, body, commented_len);
1881 /* buf->buf may be reallocated so store an offset into the buffer */
1882 fixup_off = buf->len;
1883 strbuf_addstr(buf, body + commented_len);
1885 /* fixup -C after squash behaves like squash */
1886 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1888 * We're replacing the commit message so we need to
1889 * append the Signed-off-by: trailer if the user
1890 * requested '--signoff'.
1892 if (opts->signoff)
1893 append_signoff(buf, 0, 0);
1895 if ((command == TODO_FIXUP) &&
1896 (flag & TODO_REPLACE_FIXUP_MSG) &&
1897 (file_exists(rebase_path_fixup_msg()) ||
1898 !file_exists(rebase_path_squash_msg()))) {
1899 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1900 if (write_message(fixup_msg, strlen(fixup_msg),
1901 rebase_path_fixup_msg(), 0) < 0)
1902 return error(_("cannot write '%s'"),
1903 rebase_path_fixup_msg());
1904 } else {
1905 unlink(rebase_path_fixup_msg());
1907 } else {
1908 unlink(rebase_path_fixup_msg());
1911 return 0;
1914 static int update_squash_messages(struct repository *r,
1915 enum todo_command command,
1916 struct commit *commit,
1917 struct replay_opts *opts,
1918 unsigned flag)
1920 struct strbuf buf = STRBUF_INIT;
1921 int res = 0;
1922 const char *message, *body;
1923 const char *encoding = get_commit_output_encoding();
1925 if (opts->current_fixup_count > 0) {
1926 struct strbuf header = STRBUF_INIT;
1927 char *eol;
1929 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1930 return error(_("could not read '%s'"),
1931 rebase_path_squash_msg());
1933 eol = buf.buf[0] != comment_line_char ?
1934 buf.buf : strchrnul(buf.buf, '\n');
1936 strbuf_addf(&header, "%c ", comment_line_char);
1937 strbuf_addf(&header, _(combined_commit_msg_fmt),
1938 opts->current_fixup_count + 2);
1939 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1940 strbuf_release(&header);
1941 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1942 update_squash_message_for_fixup(&buf);
1943 } else {
1944 struct object_id head;
1945 struct commit *head_commit;
1946 const char *head_message, *body;
1948 if (get_oid("HEAD", &head))
1949 return error(_("need a HEAD to fixup"));
1950 if (!(head_commit = lookup_commit_reference(r, &head)))
1951 return error(_("could not read HEAD"));
1952 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1953 return error(_("could not read HEAD's commit message"));
1955 find_commit_subject(head_message, &body);
1956 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1957 rebase_path_fixup_msg(), 0) < 0) {
1958 unuse_commit_buffer(head_commit, head_message);
1959 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1961 strbuf_addf(&buf, "%c ", comment_line_char);
1962 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1963 strbuf_addf(&buf, "\n%c ", comment_line_char);
1964 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1965 _(skip_first_commit_msg_str) :
1966 _(first_commit_msg_str));
1967 strbuf_addstr(&buf, "\n\n");
1968 if (is_fixup_flag(command, flag))
1969 strbuf_add_commented_lines(&buf, body, strlen(body));
1970 else
1971 strbuf_addstr(&buf, body);
1973 unuse_commit_buffer(head_commit, head_message);
1976 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1977 return error(_("could not read commit message of %s"),
1978 oid_to_hex(&commit->object.oid));
1979 find_commit_subject(message, &body);
1981 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1982 res = append_squash_message(&buf, body, command, opts, flag);
1983 } else if (command == TODO_FIXUP) {
1984 strbuf_addf(&buf, "\n%c ", comment_line_char);
1985 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1986 ++opts->current_fixup_count + 1);
1987 strbuf_addstr(&buf, "\n\n");
1988 strbuf_add_commented_lines(&buf, body, strlen(body));
1989 } else
1990 return error(_("unknown command: %d"), command);
1991 unuse_commit_buffer(commit, message);
1993 if (!res)
1994 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1996 strbuf_release(&buf);
1998 if (!res) {
1999 strbuf_addf(&opts->current_fixups, "%s%s %s",
2000 opts->current_fixups.len ? "\n" : "",
2001 command_to_string(command),
2002 oid_to_hex(&commit->object.oid));
2003 res = write_message(opts->current_fixups.buf,
2004 opts->current_fixups.len,
2005 rebase_path_current_fixups(), 0);
2008 return res;
2011 static void flush_rewritten_pending(void)
2013 struct strbuf buf = STRBUF_INIT;
2014 struct object_id newoid;
2015 FILE *out;
2017 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2018 !get_oid("HEAD", &newoid) &&
2019 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2020 char *bol = buf.buf, *eol;
2022 while (*bol) {
2023 eol = strchrnul(bol, '\n');
2024 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2025 bol, oid_to_hex(&newoid));
2026 if (!*eol)
2027 break;
2028 bol = eol + 1;
2030 fclose(out);
2031 unlink(rebase_path_rewritten_pending());
2033 strbuf_release(&buf);
2036 static void record_in_rewritten(struct object_id *oid,
2037 enum todo_command next_command)
2039 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2041 if (!out)
2042 return;
2044 fprintf(out, "%s\n", oid_to_hex(oid));
2045 fclose(out);
2047 if (!is_fixup(next_command))
2048 flush_rewritten_pending();
2051 static int should_edit(struct replay_opts *opts) {
2052 if (opts->edit < 0)
2054 * Note that we only handle the case of non-conflicted
2055 * commits; continue_single_pick() handles the conflicted
2056 * commits itself instead of calling this function.
2058 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2059 return opts->edit;
2062 static int do_pick_commit(struct repository *r,
2063 struct todo_item *item,
2064 struct replay_opts *opts,
2065 int final_fixup, int *check_todo)
2067 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2068 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2069 struct object_id head;
2070 struct commit *base, *next, *parent;
2071 const char *base_label, *next_label;
2072 char *author = NULL;
2073 struct commit_message msg = { NULL, NULL, NULL, NULL };
2074 struct strbuf msgbuf = STRBUF_INIT;
2075 int res, unborn = 0, reword = 0, allow, drop_commit;
2076 enum todo_command command = item->command;
2077 struct commit *commit = item->commit;
2079 if (opts->no_commit) {
2081 * We do not intend to commit immediately. We just want to
2082 * merge the differences in, so let's compute the tree
2083 * that represents the "current" state for the merge machinery
2084 * to work on.
2086 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2087 return error(_("your index file is unmerged."));
2088 } else {
2089 unborn = get_oid("HEAD", &head);
2090 /* Do we want to generate a root commit? */
2091 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2092 oideq(&head, &opts->squash_onto)) {
2093 if (is_fixup(command))
2094 return error(_("cannot fixup root commit"));
2095 flags |= CREATE_ROOT_COMMIT;
2096 unborn = 1;
2097 } else if (unborn)
2098 oidcpy(&head, the_hash_algo->empty_tree);
2099 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2100 NULL, 0))
2101 return error_dirty_index(r, opts);
2103 discard_index(r->index);
2105 if (!commit->parents)
2106 parent = NULL;
2107 else if (commit->parents->next) {
2108 /* Reverting or cherry-picking a merge commit */
2109 int cnt;
2110 struct commit_list *p;
2112 if (!opts->mainline)
2113 return error(_("commit %s is a merge but no -m option was given."),
2114 oid_to_hex(&commit->object.oid));
2116 for (cnt = 1, p = commit->parents;
2117 cnt != opts->mainline && p;
2118 cnt++)
2119 p = p->next;
2120 if (cnt != opts->mainline || !p)
2121 return error(_("commit %s does not have parent %d"),
2122 oid_to_hex(&commit->object.oid), opts->mainline);
2123 parent = p->item;
2124 } else if (1 < opts->mainline)
2126 * Non-first parent explicitly specified as mainline for
2127 * non-merge commit
2129 return error(_("commit %s does not have parent %d"),
2130 oid_to_hex(&commit->object.oid), opts->mainline);
2131 else
2132 parent = commit->parents->item;
2134 if (get_message(commit, &msg) != 0)
2135 return error(_("cannot get commit message for %s"),
2136 oid_to_hex(&commit->object.oid));
2138 if (opts->allow_ff && !is_fixup(command) &&
2139 ((parent && oideq(&parent->object.oid, &head)) ||
2140 (!parent && unborn))) {
2141 if (is_rebase_i(opts))
2142 write_author_script(msg.message);
2143 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2144 opts);
2145 if (res || command != TODO_REWORD)
2146 goto leave;
2147 reword = 1;
2148 msg_file = NULL;
2149 goto fast_forward_edit;
2151 if (parent && parse_commit(parent) < 0)
2152 /* TRANSLATORS: The first %s will be a "todo" command like
2153 "revert" or "pick", the second %s a SHA1. */
2154 return error(_("%s: cannot parse parent commit %s"),
2155 command_to_string(command),
2156 oid_to_hex(&parent->object.oid));
2159 * "commit" is an existing commit. We would want to apply
2160 * the difference it introduces since its first parent "prev"
2161 * on top of the current HEAD if we are cherry-pick. Or the
2162 * reverse of it if we are revert.
2165 if (command == TODO_REVERT) {
2166 base = commit;
2167 base_label = msg.label;
2168 next = parent;
2169 next_label = msg.parent_label;
2170 strbuf_addstr(&msgbuf, "Revert \"");
2171 strbuf_addstr(&msgbuf, msg.subject);
2172 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2173 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2175 if (commit->parents && commit->parents->next) {
2176 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2177 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2179 strbuf_addstr(&msgbuf, ".\n");
2180 } else {
2181 const char *p;
2183 base = parent;
2184 base_label = msg.parent_label;
2185 next = commit;
2186 next_label = msg.label;
2188 /* Append the commit log message to msgbuf. */
2189 if (find_commit_subject(msg.message, &p))
2190 strbuf_addstr(&msgbuf, p);
2192 if (opts->record_origin) {
2193 strbuf_complete_line(&msgbuf);
2194 if (!has_conforming_footer(&msgbuf, NULL, 0))
2195 strbuf_addch(&msgbuf, '\n');
2196 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2197 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2198 strbuf_addstr(&msgbuf, ")\n");
2200 if (!is_fixup(command))
2201 author = get_author(msg.message);
2204 if (command == TODO_REWORD)
2205 reword = 1;
2206 else if (is_fixup(command)) {
2207 if (update_squash_messages(r, command, commit,
2208 opts, item->flags))
2209 return -1;
2210 flags |= AMEND_MSG;
2211 if (!final_fixup)
2212 msg_file = rebase_path_squash_msg();
2213 else if (file_exists(rebase_path_fixup_msg())) {
2214 flags |= VERBATIM_MSG;
2215 msg_file = rebase_path_fixup_msg();
2216 } else {
2217 const char *dest = git_path_squash_msg(r);
2218 unlink(dest);
2219 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2220 return error(_("could not rename '%s' to '%s'"),
2221 rebase_path_squash_msg(), dest);
2222 unlink(git_path_merge_msg(r));
2223 msg_file = dest;
2224 flags |= EDIT_MSG;
2228 if (opts->signoff && !is_fixup(command))
2229 append_signoff(&msgbuf, 0, 0);
2231 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2232 res = -1;
2233 else if (!opts->strategy ||
2234 !strcmp(opts->strategy, "recursive") ||
2235 !strcmp(opts->strategy, "ort") ||
2236 command == TODO_REVERT) {
2237 res = do_recursive_merge(r, base, next, base_label, next_label,
2238 &head, &msgbuf, opts);
2239 if (res < 0)
2240 goto leave;
2242 res |= write_message(msgbuf.buf, msgbuf.len,
2243 git_path_merge_msg(r), 0);
2244 } else {
2245 struct commit_list *common = NULL;
2246 struct commit_list *remotes = NULL;
2248 res = write_message(msgbuf.buf, msgbuf.len,
2249 git_path_merge_msg(r), 0);
2251 commit_list_insert(base, &common);
2252 commit_list_insert(next, &remotes);
2253 res |= try_merge_command(r, opts->strategy,
2254 opts->xopts_nr, (const char **)opts->xopts,
2255 common, oid_to_hex(&head), remotes);
2256 free_commit_list(common);
2257 free_commit_list(remotes);
2259 strbuf_release(&msgbuf);
2262 * If the merge was clean or if it failed due to conflict, we write
2263 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2264 * However, if the merge did not even start, then we don't want to
2265 * write it at all.
2267 if ((command == TODO_PICK || command == TODO_REWORD ||
2268 command == TODO_EDIT) && !opts->no_commit &&
2269 (res == 0 || res == 1) &&
2270 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2271 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2272 res = -1;
2273 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2274 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2275 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2276 res = -1;
2278 if (res) {
2279 error(command == TODO_REVERT
2280 ? _("could not revert %s... %s")
2281 : _("could not apply %s... %s"),
2282 short_commit_name(commit), msg.subject);
2283 print_advice(r, res == 1, opts);
2284 repo_rerere(r, opts->allow_rerere_auto);
2285 goto leave;
2288 drop_commit = 0;
2289 allow = allow_empty(r, opts, commit);
2290 if (allow < 0) {
2291 res = allow;
2292 goto leave;
2293 } else if (allow == 1) {
2294 flags |= ALLOW_EMPTY;
2295 } else if (allow == 2) {
2296 drop_commit = 1;
2297 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2298 NULL, 0);
2299 unlink(git_path_merge_msg(r));
2300 unlink(git_path_auto_merge(r));
2301 fprintf(stderr,
2302 _("dropping %s %s -- patch contents already upstream\n"),
2303 oid_to_hex(&commit->object.oid), msg.subject);
2304 } /* else allow == 0 and there's nothing special to do */
2305 if (!opts->no_commit && !drop_commit) {
2306 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2307 res = do_commit(r, msg_file, author, opts, flags,
2308 commit? &commit->object.oid : NULL);
2309 else
2310 res = error(_("unable to parse commit author"));
2311 *check_todo = !!(flags & EDIT_MSG);
2312 if (!res && reword) {
2313 fast_forward_edit:
2314 res = run_git_commit(NULL, opts, EDIT_MSG |
2315 VERIFY_MSG | AMEND_MSG |
2316 (flags & ALLOW_EMPTY));
2317 *check_todo = 1;
2322 if (!res && final_fixup) {
2323 unlink(rebase_path_fixup_msg());
2324 unlink(rebase_path_squash_msg());
2325 unlink(rebase_path_current_fixups());
2326 strbuf_reset(&opts->current_fixups);
2327 opts->current_fixup_count = 0;
2330 leave:
2331 free_message(commit, &msg);
2332 free(author);
2333 update_abort_safety_file();
2335 return res;
2338 static int prepare_revs(struct replay_opts *opts)
2341 * picking (but not reverting) ranges (but not individual revisions)
2342 * should be done in reverse
2344 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2345 opts->revs->reverse ^= 1;
2347 if (prepare_revision_walk(opts->revs))
2348 return error(_("revision walk setup failed"));
2350 return 0;
2353 static int read_and_refresh_cache(struct repository *r,
2354 struct replay_opts *opts)
2356 struct lock_file index_lock = LOCK_INIT;
2357 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2358 if (repo_read_index(r) < 0) {
2359 rollback_lock_file(&index_lock);
2360 return error(_("git %s: failed to read the index"),
2361 _(action_name(opts)));
2363 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2365 if (index_fd >= 0) {
2366 if (write_locked_index(r->index, &index_lock,
2367 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2368 return error(_("git %s: failed to refresh the index"),
2369 _(action_name(opts)));
2374 * If we are resolving merges in any way other than "ort", then
2375 * expand the sparse index.
2377 if (opts->strategy && strcmp(opts->strategy, "ort"))
2378 ensure_full_index(r->index);
2379 return 0;
2382 void todo_list_release(struct todo_list *todo_list)
2384 strbuf_release(&todo_list->buf);
2385 FREE_AND_NULL(todo_list->items);
2386 todo_list->nr = todo_list->alloc = 0;
2389 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2391 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2392 todo_list->total_nr++;
2393 return todo_list->items + todo_list->nr++;
2396 const char *todo_item_get_arg(struct todo_list *todo_list,
2397 struct todo_item *item)
2399 return todo_list->buf.buf + item->arg_offset;
2402 static int is_command(enum todo_command command, const char **bol)
2404 const char *str = todo_command_info[command].str;
2405 const char nick = todo_command_info[command].c;
2406 const char *p = *bol + 1;
2408 return skip_prefix(*bol, str, bol) ||
2409 ((nick && **bol == nick) &&
2410 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2411 (*bol = p));
2414 static int parse_insn_line(struct repository *r, struct todo_item *item,
2415 const char *buf, const char *bol, char *eol)
2417 struct object_id commit_oid;
2418 char *end_of_object_name;
2419 int i, saved, status, padding;
2421 item->flags = 0;
2423 /* left-trim */
2424 bol += strspn(bol, " \t");
2426 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2427 item->command = TODO_COMMENT;
2428 item->commit = NULL;
2429 item->arg_offset = bol - buf;
2430 item->arg_len = eol - bol;
2431 return 0;
2434 for (i = 0; i < TODO_COMMENT; i++)
2435 if (is_command(i, &bol)) {
2436 item->command = i;
2437 break;
2439 if (i >= TODO_COMMENT)
2440 return -1;
2442 /* Eat up extra spaces/ tabs before object name */
2443 padding = strspn(bol, " \t");
2444 bol += padding;
2446 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2447 if (bol != eol)
2448 return error(_("%s does not accept arguments: '%s'"),
2449 command_to_string(item->command), bol);
2450 item->commit = NULL;
2451 item->arg_offset = bol - buf;
2452 item->arg_len = eol - bol;
2453 return 0;
2456 if (!padding)
2457 return error(_("missing arguments for %s"),
2458 command_to_string(item->command));
2460 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2461 item->command == TODO_RESET) {
2462 item->commit = NULL;
2463 item->arg_offset = bol - buf;
2464 item->arg_len = (int)(eol - bol);
2465 return 0;
2468 if (item->command == TODO_FIXUP) {
2469 if (skip_prefix(bol, "-C", &bol) &&
2470 (*bol == ' ' || *bol == '\t')) {
2471 bol += strspn(bol, " \t");
2472 item->flags |= TODO_REPLACE_FIXUP_MSG;
2473 } else if (skip_prefix(bol, "-c", &bol) &&
2474 (*bol == ' ' || *bol == '\t')) {
2475 bol += strspn(bol, " \t");
2476 item->flags |= TODO_EDIT_FIXUP_MSG;
2480 if (item->command == TODO_MERGE) {
2481 if (skip_prefix(bol, "-C", &bol))
2482 bol += strspn(bol, " \t");
2483 else if (skip_prefix(bol, "-c", &bol)) {
2484 bol += strspn(bol, " \t");
2485 item->flags |= TODO_EDIT_MERGE_MSG;
2486 } else {
2487 item->flags |= TODO_EDIT_MERGE_MSG;
2488 item->commit = NULL;
2489 item->arg_offset = bol - buf;
2490 item->arg_len = (int)(eol - bol);
2491 return 0;
2495 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2496 saved = *end_of_object_name;
2497 *end_of_object_name = '\0';
2498 status = get_oid(bol, &commit_oid);
2499 if (status < 0)
2500 error(_("could not parse '%s'"), bol); /* return later */
2501 *end_of_object_name = saved;
2503 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2504 item->arg_offset = bol - buf;
2505 item->arg_len = (int)(eol - bol);
2507 if (status < 0)
2508 return status;
2510 item->commit = lookup_commit_reference(r, &commit_oid);
2511 return item->commit ? 0 : -1;
2514 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2516 const char *todo_file, *bol;
2517 struct strbuf buf = STRBUF_INIT;
2518 int ret = 0;
2520 todo_file = git_path_todo_file();
2521 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2522 if (errno == ENOENT || errno == ENOTDIR)
2523 return -1;
2524 else
2525 return error_errno("unable to open '%s'", todo_file);
2527 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2528 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2529 *action = REPLAY_PICK;
2530 else if (is_command(TODO_REVERT, &bol) &&
2531 (*bol == ' ' || *bol == '\t'))
2532 *action = REPLAY_REVERT;
2533 else
2534 ret = -1;
2536 strbuf_release(&buf);
2538 return ret;
2541 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2542 struct todo_list *todo_list)
2544 struct todo_item *item;
2545 char *p = buf, *next_p;
2546 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2548 todo_list->current = todo_list->nr = 0;
2550 for (i = 1; *p; i++, p = next_p) {
2551 char *eol = strchrnul(p, '\n');
2553 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2555 if (p != eol && eol[-1] == '\r')
2556 eol--; /* strip Carriage Return */
2558 item = append_new_todo(todo_list);
2559 item->offset_in_buf = p - todo_list->buf.buf;
2560 if (parse_insn_line(r, item, buf, p, eol)) {
2561 res = error(_("invalid line %d: %.*s"),
2562 i, (int)(eol - p), p);
2563 item->command = TODO_COMMENT + 1;
2564 item->arg_offset = p - buf;
2565 item->arg_len = (int)(eol - p);
2566 item->commit = NULL;
2569 if (fixup_okay)
2570 ; /* do nothing */
2571 else if (is_fixup(item->command))
2572 return error(_("cannot '%s' without a previous commit"),
2573 command_to_string(item->command));
2574 else if (!is_noop(item->command))
2575 fixup_okay = 1;
2578 return res;
2581 static int count_commands(struct todo_list *todo_list)
2583 int count = 0, i;
2585 for (i = 0; i < todo_list->nr; i++)
2586 if (todo_list->items[i].command != TODO_COMMENT)
2587 count++;
2589 return count;
2592 static int get_item_line_offset(struct todo_list *todo_list, int index)
2594 return index < todo_list->nr ?
2595 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2598 static const char *get_item_line(struct todo_list *todo_list, int index)
2600 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2603 static int get_item_line_length(struct todo_list *todo_list, int index)
2605 return get_item_line_offset(todo_list, index + 1)
2606 - get_item_line_offset(todo_list, index);
2609 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2611 int fd;
2612 ssize_t len;
2614 fd = open(path, O_RDONLY);
2615 if (fd < 0)
2616 return error_errno(_("could not open '%s'"), path);
2617 len = strbuf_read(sb, fd, 0);
2618 close(fd);
2619 if (len < 0)
2620 return error(_("could not read '%s'."), path);
2621 return len;
2624 static int have_finished_the_last_pick(void)
2626 struct strbuf buf = STRBUF_INIT;
2627 const char *eol;
2628 const char *todo_path = git_path_todo_file();
2629 int ret = 0;
2631 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2632 if (errno == ENOENT) {
2633 return 0;
2634 } else {
2635 error_errno("unable to open '%s'", todo_path);
2636 return 0;
2639 /* If there is only one line then we are done */
2640 eol = strchr(buf.buf, '\n');
2641 if (!eol || !eol[1])
2642 ret = 1;
2644 strbuf_release(&buf);
2646 return ret;
2649 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2651 struct replay_opts opts = REPLAY_OPTS_INIT;
2652 int need_cleanup = 0;
2654 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2655 if (!refs_delete_ref(get_main_ref_store(r), "",
2656 "CHERRY_PICK_HEAD", NULL, 0) &&
2657 verbose)
2658 warning(_("cancelling a cherry picking in progress"));
2659 opts.action = REPLAY_PICK;
2660 need_cleanup = 1;
2663 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2664 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2665 NULL, 0) &&
2666 verbose)
2667 warning(_("cancelling a revert in progress"));
2668 opts.action = REPLAY_REVERT;
2669 need_cleanup = 1;
2672 unlink(git_path_auto_merge(r));
2674 if (!need_cleanup)
2675 return;
2677 if (!have_finished_the_last_pick())
2678 return;
2680 sequencer_remove_state(&opts);
2683 static void todo_list_write_total_nr(struct todo_list *todo_list)
2685 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2687 if (f) {
2688 fprintf(f, "%d\n", todo_list->total_nr);
2689 fclose(f);
2693 static int read_populate_todo(struct repository *r,
2694 struct todo_list *todo_list,
2695 struct replay_opts *opts)
2697 const char *todo_file = get_todo_path(opts);
2698 int res;
2700 strbuf_reset(&todo_list->buf);
2701 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2702 return -1;
2704 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2705 if (res) {
2706 if (is_rebase_i(opts))
2707 return error(_("please fix this using "
2708 "'git rebase --edit-todo'."));
2709 return error(_("unusable instruction sheet: '%s'"), todo_file);
2712 if (!todo_list->nr &&
2713 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2714 return error(_("no commits parsed."));
2716 if (!is_rebase_i(opts)) {
2717 enum todo_command valid =
2718 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2719 int i;
2721 for (i = 0; i < todo_list->nr; i++)
2722 if (valid == todo_list->items[i].command)
2723 continue;
2724 else if (valid == TODO_PICK)
2725 return error(_("cannot cherry-pick during a revert."));
2726 else
2727 return error(_("cannot revert during a cherry-pick."));
2730 if (is_rebase_i(opts)) {
2731 struct todo_list done = TODO_LIST_INIT;
2733 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2734 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2735 todo_list->done_nr = count_commands(&done);
2736 else
2737 todo_list->done_nr = 0;
2739 todo_list->total_nr = todo_list->done_nr
2740 + count_commands(todo_list);
2741 todo_list_release(&done);
2743 todo_list_write_total_nr(todo_list);
2746 return 0;
2749 static int git_config_string_dup(char **dest,
2750 const char *var, const char *value)
2752 if (!value)
2753 return config_error_nonbool(var);
2754 free(*dest);
2755 *dest = xstrdup(value);
2756 return 0;
2759 static int populate_opts_cb(const char *key, const char *value, void *data)
2761 struct replay_opts *opts = data;
2762 int error_flag = 1;
2764 if (!value)
2765 error_flag = 0;
2766 else if (!strcmp(key, "options.no-commit"))
2767 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2768 else if (!strcmp(key, "options.edit"))
2769 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2770 else if (!strcmp(key, "options.allow-empty"))
2771 opts->allow_empty =
2772 git_config_bool_or_int(key, value, &error_flag);
2773 else if (!strcmp(key, "options.allow-empty-message"))
2774 opts->allow_empty_message =
2775 git_config_bool_or_int(key, value, &error_flag);
2776 else if (!strcmp(key, "options.keep-redundant-commits"))
2777 opts->keep_redundant_commits =
2778 git_config_bool_or_int(key, value, &error_flag);
2779 else if (!strcmp(key, "options.signoff"))
2780 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2781 else if (!strcmp(key, "options.record-origin"))
2782 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2783 else if (!strcmp(key, "options.allow-ff"))
2784 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2785 else if (!strcmp(key, "options.mainline"))
2786 opts->mainline = git_config_int(key, value);
2787 else if (!strcmp(key, "options.strategy"))
2788 git_config_string_dup(&opts->strategy, key, value);
2789 else if (!strcmp(key, "options.gpg-sign"))
2790 git_config_string_dup(&opts->gpg_sign, key, value);
2791 else if (!strcmp(key, "options.strategy-option")) {
2792 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2793 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2794 } else if (!strcmp(key, "options.allow-rerere-auto"))
2795 opts->allow_rerere_auto =
2796 git_config_bool_or_int(key, value, &error_flag) ?
2797 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2798 else if (!strcmp(key, "options.default-msg-cleanup")) {
2799 opts->explicit_cleanup = 1;
2800 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2801 } else
2802 return error(_("invalid key: %s"), key);
2804 if (!error_flag)
2805 return error(_("invalid value for '%s': '%s'"), key, value);
2807 return 0;
2810 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2812 int i;
2813 char *strategy_opts_string = raw_opts;
2815 if (*strategy_opts_string == ' ')
2816 strategy_opts_string++;
2818 opts->xopts_nr = split_cmdline(strategy_opts_string,
2819 (const char ***)&opts->xopts);
2820 for (i = 0; i < opts->xopts_nr; i++) {
2821 const char *arg = opts->xopts[i];
2823 skip_prefix(arg, "--", &arg);
2824 opts->xopts[i] = xstrdup(arg);
2828 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2830 strbuf_reset(buf);
2831 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2832 return;
2833 opts->strategy = strbuf_detach(buf, NULL);
2834 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2835 return;
2837 parse_strategy_opts(opts, buf->buf);
2840 static int read_populate_opts(struct replay_opts *opts)
2842 if (is_rebase_i(opts)) {
2843 struct strbuf buf = STRBUF_INIT;
2844 int ret = 0;
2846 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2847 READ_ONELINER_SKIP_IF_EMPTY)) {
2848 if (!starts_with(buf.buf, "-S"))
2849 strbuf_reset(&buf);
2850 else {
2851 free(opts->gpg_sign);
2852 opts->gpg_sign = xstrdup(buf.buf + 2);
2854 strbuf_reset(&buf);
2857 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2858 READ_ONELINER_SKIP_IF_EMPTY)) {
2859 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2860 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2861 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2862 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2863 strbuf_reset(&buf);
2866 if (file_exists(rebase_path_verbose()))
2867 opts->verbose = 1;
2869 if (file_exists(rebase_path_quiet()))
2870 opts->quiet = 1;
2872 if (file_exists(rebase_path_signoff())) {
2873 opts->allow_ff = 0;
2874 opts->signoff = 1;
2877 if (file_exists(rebase_path_cdate_is_adate())) {
2878 opts->allow_ff = 0;
2879 opts->committer_date_is_author_date = 1;
2882 if (file_exists(rebase_path_ignore_date())) {
2883 opts->allow_ff = 0;
2884 opts->ignore_date = 1;
2887 if (file_exists(rebase_path_reschedule_failed_exec()))
2888 opts->reschedule_failed_exec = 1;
2889 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2890 opts->reschedule_failed_exec = 0;
2892 if (file_exists(rebase_path_drop_redundant_commits()))
2893 opts->drop_redundant_commits = 1;
2895 if (file_exists(rebase_path_keep_redundant_commits()))
2896 opts->keep_redundant_commits = 1;
2898 read_strategy_opts(opts, &buf);
2899 strbuf_reset(&buf);
2901 if (read_oneliner(&opts->current_fixups,
2902 rebase_path_current_fixups(),
2903 READ_ONELINER_SKIP_IF_EMPTY)) {
2904 const char *p = opts->current_fixups.buf;
2905 opts->current_fixup_count = 1;
2906 while ((p = strchr(p, '\n'))) {
2907 opts->current_fixup_count++;
2908 p++;
2912 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2913 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2914 ret = error(_("unusable squash-onto"));
2915 goto done_rebase_i;
2917 opts->have_squash_onto = 1;
2920 done_rebase_i:
2921 strbuf_release(&buf);
2922 return ret;
2925 if (!file_exists(git_path_opts_file()))
2926 return 0;
2928 * The function git_parse_source(), called from git_config_from_file(),
2929 * may die() in case of a syntactically incorrect file. We do not care
2930 * about this case, though, because we wrote that file ourselves, so we
2931 * are pretty certain that it is syntactically correct.
2933 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2934 return error(_("malformed options sheet: '%s'"),
2935 git_path_opts_file());
2936 return 0;
2939 static void write_strategy_opts(struct replay_opts *opts)
2941 int i;
2942 struct strbuf buf = STRBUF_INIT;
2944 for (i = 0; i < opts->xopts_nr; ++i)
2945 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2947 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2948 strbuf_release(&buf);
2951 int write_basic_state(struct replay_opts *opts, const char *head_name,
2952 struct commit *onto, const struct object_id *orig_head)
2954 if (head_name)
2955 write_file(rebase_path_head_name(), "%s\n", head_name);
2956 if (onto)
2957 write_file(rebase_path_onto(), "%s\n",
2958 oid_to_hex(&onto->object.oid));
2959 if (orig_head)
2960 write_file(rebase_path_orig_head(), "%s\n",
2961 oid_to_hex(orig_head));
2963 if (opts->quiet)
2964 write_file(rebase_path_quiet(), "%s", "");
2965 if (opts->verbose)
2966 write_file(rebase_path_verbose(), "%s", "");
2967 if (opts->strategy)
2968 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2969 if (opts->xopts_nr > 0)
2970 write_strategy_opts(opts);
2972 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2973 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2974 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2975 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2977 if (opts->gpg_sign)
2978 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2979 if (opts->signoff)
2980 write_file(rebase_path_signoff(), "--signoff\n");
2981 if (opts->drop_redundant_commits)
2982 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2983 if (opts->keep_redundant_commits)
2984 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2985 if (opts->committer_date_is_author_date)
2986 write_file(rebase_path_cdate_is_adate(), "%s", "");
2987 if (opts->ignore_date)
2988 write_file(rebase_path_ignore_date(), "%s", "");
2989 if (opts->reschedule_failed_exec)
2990 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2991 else
2992 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2994 return 0;
2997 static int walk_revs_populate_todo(struct todo_list *todo_list,
2998 struct replay_opts *opts)
3000 enum todo_command command = opts->action == REPLAY_PICK ?
3001 TODO_PICK : TODO_REVERT;
3002 const char *command_string = todo_command_info[command].str;
3003 const char *encoding;
3004 struct commit *commit;
3006 if (prepare_revs(opts))
3007 return -1;
3009 encoding = get_log_output_encoding();
3011 while ((commit = get_revision(opts->revs))) {
3012 struct todo_item *item = append_new_todo(todo_list);
3013 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3014 const char *subject;
3015 int subject_len;
3017 item->command = command;
3018 item->commit = commit;
3019 item->arg_offset = 0;
3020 item->arg_len = 0;
3021 item->offset_in_buf = todo_list->buf.len;
3022 subject_len = find_commit_subject(commit_buffer, &subject);
3023 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3024 short_commit_name(commit), subject_len, subject);
3025 unuse_commit_buffer(commit, commit_buffer);
3028 if (!todo_list->nr)
3029 return error(_("empty commit set passed"));
3031 return 0;
3034 static int create_seq_dir(struct repository *r)
3036 enum replay_action action;
3037 const char *in_progress_error = NULL;
3038 const char *in_progress_advice = NULL;
3039 unsigned int advise_skip =
3040 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3041 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3043 if (!sequencer_get_last_command(r, &action)) {
3044 switch (action) {
3045 case REPLAY_REVERT:
3046 in_progress_error = _("revert is already in progress");
3047 in_progress_advice =
3048 _("try \"git revert (--continue | %s--abort | --quit)\"");
3049 break;
3050 case REPLAY_PICK:
3051 in_progress_error = _("cherry-pick is already in progress");
3052 in_progress_advice =
3053 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3054 break;
3055 default:
3056 BUG("unexpected action in create_seq_dir");
3059 if (in_progress_error) {
3060 error("%s", in_progress_error);
3061 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3062 advise(in_progress_advice,
3063 advise_skip ? "--skip | " : "");
3064 return -1;
3066 if (mkdir(git_path_seq_dir(), 0777) < 0)
3067 return error_errno(_("could not create sequencer directory '%s'"),
3068 git_path_seq_dir());
3070 return 0;
3073 static int save_head(const char *head)
3075 struct lock_file head_lock = LOCK_INIT;
3076 struct strbuf buf = STRBUF_INIT;
3077 int fd;
3078 ssize_t written;
3080 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3081 if (fd < 0)
3082 return error_errno(_("could not lock HEAD"));
3083 strbuf_addf(&buf, "%s\n", head);
3084 written = write_in_full(fd, buf.buf, buf.len);
3085 strbuf_release(&buf);
3086 if (written < 0) {
3087 error_errno(_("could not write to '%s'"), git_path_head_file());
3088 rollback_lock_file(&head_lock);
3089 return -1;
3091 if (commit_lock_file(&head_lock) < 0)
3092 return error(_("failed to finalize '%s'"), git_path_head_file());
3093 return 0;
3096 static int rollback_is_safe(void)
3098 struct strbuf sb = STRBUF_INIT;
3099 struct object_id expected_head, actual_head;
3101 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3102 strbuf_trim(&sb);
3103 if (get_oid_hex(sb.buf, &expected_head)) {
3104 strbuf_release(&sb);
3105 die(_("could not parse %s"), git_path_abort_safety_file());
3107 strbuf_release(&sb);
3109 else if (errno == ENOENT)
3110 oidclr(&expected_head);
3111 else
3112 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3114 if (get_oid("HEAD", &actual_head))
3115 oidclr(&actual_head);
3117 return oideq(&actual_head, &expected_head);
3120 static int reset_merge(const struct object_id *oid)
3122 int ret;
3123 struct strvec argv = STRVEC_INIT;
3125 strvec_pushl(&argv, "reset", "--merge", NULL);
3127 if (!is_null_oid(oid))
3128 strvec_push(&argv, oid_to_hex(oid));
3130 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3131 strvec_clear(&argv);
3133 return ret;
3136 static int rollback_single_pick(struct repository *r)
3138 struct object_id head_oid;
3140 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3141 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3142 return error(_("no cherry-pick or revert in progress"));
3143 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3144 return error(_("cannot resolve HEAD"));
3145 if (is_null_oid(&head_oid))
3146 return error(_("cannot abort from a branch yet to be born"));
3147 return reset_merge(&head_oid);
3150 static int skip_single_pick(void)
3152 struct object_id head;
3154 if (read_ref_full("HEAD", 0, &head, NULL))
3155 return error(_("cannot resolve HEAD"));
3156 return reset_merge(&head);
3159 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3161 FILE *f;
3162 struct object_id oid;
3163 struct strbuf buf = STRBUF_INIT;
3164 const char *p;
3166 f = fopen(git_path_head_file(), "r");
3167 if (!f && errno == ENOENT) {
3169 * There is no multiple-cherry-pick in progress.
3170 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3171 * a single-cherry-pick in progress, abort that.
3173 return rollback_single_pick(r);
3175 if (!f)
3176 return error_errno(_("cannot open '%s'"), git_path_head_file());
3177 if (strbuf_getline_lf(&buf, f)) {
3178 error(_("cannot read '%s': %s"), git_path_head_file(),
3179 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3180 fclose(f);
3181 goto fail;
3183 fclose(f);
3184 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3185 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3186 git_path_head_file());
3187 goto fail;
3189 if (is_null_oid(&oid)) {
3190 error(_("cannot abort from a branch yet to be born"));
3191 goto fail;
3194 if (!rollback_is_safe()) {
3195 /* Do not error, just do not rollback */
3196 warning(_("You seem to have moved HEAD. "
3197 "Not rewinding, check your HEAD!"));
3198 } else
3199 if (reset_merge(&oid))
3200 goto fail;
3201 strbuf_release(&buf);
3202 return sequencer_remove_state(opts);
3203 fail:
3204 strbuf_release(&buf);
3205 return -1;
3208 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3210 enum replay_action action = -1;
3211 sequencer_get_last_command(r, &action);
3214 * Check whether the subcommand requested to skip the commit is actually
3215 * in progress and that it's safe to skip the commit.
3217 * opts->action tells us which subcommand requested to skip the commit.
3218 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3219 * action is in progress and we can skip the commit.
3221 * Otherwise we check that the last instruction was related to the
3222 * particular subcommand we're trying to execute and barf if that's not
3223 * the case.
3225 * Finally we check that the rollback is "safe", i.e., has the HEAD
3226 * moved? In this case, it doesn't make sense to "reset the merge" and
3227 * "skip the commit" as the user already handled this by committing. But
3228 * we'd not want to barf here, instead give advice on how to proceed. We
3229 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3230 * it gets removed when the user commits, so if it still exists we're
3231 * sure the user can't have committed before.
3233 switch (opts->action) {
3234 case REPLAY_REVERT:
3235 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3236 if (action != REPLAY_REVERT)
3237 return error(_("no revert in progress"));
3238 if (!rollback_is_safe())
3239 goto give_advice;
3241 break;
3242 case REPLAY_PICK:
3243 if (!refs_ref_exists(get_main_ref_store(r),
3244 "CHERRY_PICK_HEAD")) {
3245 if (action != REPLAY_PICK)
3246 return error(_("no cherry-pick in progress"));
3247 if (!rollback_is_safe())
3248 goto give_advice;
3250 break;
3251 default:
3252 BUG("unexpected action in sequencer_skip");
3255 if (skip_single_pick())
3256 return error(_("failed to skip the commit"));
3257 if (!is_directory(git_path_seq_dir()))
3258 return 0;
3260 return sequencer_continue(r, opts);
3262 give_advice:
3263 error(_("there is nothing to skip"));
3265 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3266 advise(_("have you committed already?\n"
3267 "try \"git %s --continue\""),
3268 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3270 return -1;
3273 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3275 struct lock_file todo_lock = LOCK_INIT;
3276 const char *todo_path = get_todo_path(opts);
3277 int next = todo_list->current, offset, fd;
3280 * rebase -i writes "git-rebase-todo" without the currently executing
3281 * command, appending it to "done" instead.
3283 if (is_rebase_i(opts))
3284 next++;
3286 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3287 if (fd < 0)
3288 return error_errno(_("could not lock '%s'"), todo_path);
3289 offset = get_item_line_offset(todo_list, next);
3290 if (write_in_full(fd, todo_list->buf.buf + offset,
3291 todo_list->buf.len - offset) < 0)
3292 return error_errno(_("could not write to '%s'"), todo_path);
3293 if (commit_lock_file(&todo_lock) < 0)
3294 return error(_("failed to finalize '%s'"), todo_path);
3296 if (is_rebase_i(opts) && next > 0) {
3297 const char *done = rebase_path_done();
3298 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3299 int ret = 0;
3301 if (fd < 0)
3302 return 0;
3303 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3304 get_item_line_length(todo_list, next - 1))
3305 < 0)
3306 ret = error_errno(_("could not write to '%s'"), done);
3307 if (close(fd) < 0)
3308 ret = error_errno(_("failed to finalize '%s'"), done);
3309 return ret;
3311 return 0;
3314 static int save_opts(struct replay_opts *opts)
3316 const char *opts_file = git_path_opts_file();
3317 int res = 0;
3319 if (opts->no_commit)
3320 res |= git_config_set_in_file_gently(opts_file,
3321 "options.no-commit", "true");
3322 if (opts->edit >= 0)
3323 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3324 opts->edit ? "true" : "false");
3325 if (opts->allow_empty)
3326 res |= git_config_set_in_file_gently(opts_file,
3327 "options.allow-empty", "true");
3328 if (opts->allow_empty_message)
3329 res |= git_config_set_in_file_gently(opts_file,
3330 "options.allow-empty-message", "true");
3331 if (opts->keep_redundant_commits)
3332 res |= git_config_set_in_file_gently(opts_file,
3333 "options.keep-redundant-commits", "true");
3334 if (opts->signoff)
3335 res |= git_config_set_in_file_gently(opts_file,
3336 "options.signoff", "true");
3337 if (opts->record_origin)
3338 res |= git_config_set_in_file_gently(opts_file,
3339 "options.record-origin", "true");
3340 if (opts->allow_ff)
3341 res |= git_config_set_in_file_gently(opts_file,
3342 "options.allow-ff", "true");
3343 if (opts->mainline) {
3344 struct strbuf buf = STRBUF_INIT;
3345 strbuf_addf(&buf, "%d", opts->mainline);
3346 res |= git_config_set_in_file_gently(opts_file,
3347 "options.mainline", buf.buf);
3348 strbuf_release(&buf);
3350 if (opts->strategy)
3351 res |= git_config_set_in_file_gently(opts_file,
3352 "options.strategy", opts->strategy);
3353 if (opts->gpg_sign)
3354 res |= git_config_set_in_file_gently(opts_file,
3355 "options.gpg-sign", opts->gpg_sign);
3356 if (opts->xopts) {
3357 int i;
3358 for (i = 0; i < opts->xopts_nr; i++)
3359 res |= git_config_set_multivar_in_file_gently(opts_file,
3360 "options.strategy-option",
3361 opts->xopts[i], "^$", 0);
3363 if (opts->allow_rerere_auto)
3364 res |= git_config_set_in_file_gently(opts_file,
3365 "options.allow-rerere-auto",
3366 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3367 "true" : "false");
3369 if (opts->explicit_cleanup)
3370 res |= git_config_set_in_file_gently(opts_file,
3371 "options.default-msg-cleanup",
3372 describe_cleanup_mode(opts->default_msg_cleanup));
3373 return res;
3376 static int make_patch(struct repository *r,
3377 struct commit *commit,
3378 struct replay_opts *opts)
3380 struct strbuf buf = STRBUF_INIT;
3381 struct rev_info log_tree_opt;
3382 const char *subject;
3383 char hex[GIT_MAX_HEXSZ + 1];
3384 int res = 0;
3386 oid_to_hex_r(hex, &commit->object.oid);
3387 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3388 return -1;
3389 res |= write_rebase_head(&commit->object.oid);
3391 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3392 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3393 repo_init_revisions(r, &log_tree_opt, NULL);
3394 log_tree_opt.abbrev = 0;
3395 log_tree_opt.diff = 1;
3396 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3397 log_tree_opt.disable_stdin = 1;
3398 log_tree_opt.no_commit_id = 1;
3399 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3400 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3401 if (!log_tree_opt.diffopt.file)
3402 res |= error_errno(_("could not open '%s'"), buf.buf);
3403 else {
3404 res |= log_tree_commit(&log_tree_opt, commit);
3405 fclose(log_tree_opt.diffopt.file);
3407 strbuf_reset(&buf);
3409 strbuf_addf(&buf, "%s/message", get_dir(opts));
3410 if (!file_exists(buf.buf)) {
3411 const char *encoding = get_commit_output_encoding();
3412 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3413 find_commit_subject(commit_buffer, &subject);
3414 res |= write_message(subject, strlen(subject), buf.buf, 1);
3415 unuse_commit_buffer(commit, commit_buffer);
3417 strbuf_release(&buf);
3418 release_revisions(&log_tree_opt);
3420 return res;
3423 static int intend_to_amend(void)
3425 struct object_id head;
3426 char *p;
3428 if (get_oid("HEAD", &head))
3429 return error(_("cannot read HEAD"));
3431 p = oid_to_hex(&head);
3432 return write_message(p, strlen(p), rebase_path_amend(), 1);
3435 static int error_with_patch(struct repository *r,
3436 struct commit *commit,
3437 const char *subject, int subject_len,
3438 struct replay_opts *opts,
3439 int exit_code, int to_amend)
3441 if (commit) {
3442 if (make_patch(r, commit, opts))
3443 return -1;
3444 } else if (copy_file(rebase_path_message(),
3445 git_path_merge_msg(r), 0666))
3446 return error(_("unable to copy '%s' to '%s'"),
3447 git_path_merge_msg(r), rebase_path_message());
3449 if (to_amend) {
3450 if (intend_to_amend())
3451 return -1;
3453 fprintf(stderr,
3454 _("You can amend the commit now, with\n"
3455 "\n"
3456 " git commit --amend %s\n"
3457 "\n"
3458 "Once you are satisfied with your changes, run\n"
3459 "\n"
3460 " git rebase --continue\n"),
3461 gpg_sign_opt_quoted(opts));
3462 } else if (exit_code) {
3463 if (commit)
3464 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3465 short_commit_name(commit), subject_len, subject);
3466 else
3468 * We don't have the hash of the parent so
3469 * just print the line from the todo file.
3471 fprintf_ln(stderr, _("Could not merge %.*s"),
3472 subject_len, subject);
3475 return exit_code;
3478 static int error_failed_squash(struct repository *r,
3479 struct commit *commit,
3480 struct replay_opts *opts,
3481 int subject_len,
3482 const char *subject)
3484 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3485 return error(_("could not copy '%s' to '%s'"),
3486 rebase_path_squash_msg(), rebase_path_message());
3487 unlink(git_path_merge_msg(r));
3488 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3489 return error(_("could not copy '%s' to '%s'"),
3490 rebase_path_message(),
3491 git_path_merge_msg(r));
3492 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3495 static int do_exec(struct repository *r, const char *command_line)
3497 const char *child_argv[] = { NULL, NULL };
3498 int dirty, status;
3500 fprintf(stderr, _("Executing: %s\n"), command_line);
3501 child_argv[0] = command_line;
3502 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
3504 /* force re-reading of the cache */
3505 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3506 return error(_("could not read index"));
3508 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3510 if (status) {
3511 warning(_("execution failed: %s\n%s"
3512 "You can fix the problem, and then run\n"
3513 "\n"
3514 " git rebase --continue\n"
3515 "\n"),
3516 command_line,
3517 dirty ? N_("and made changes to the index and/or the "
3518 "working tree\n") : "");
3519 if (status == 127)
3520 /* command not found */
3521 status = 1;
3522 } else if (dirty) {
3523 warning(_("execution succeeded: %s\nbut "
3524 "left changes to the index and/or the working tree\n"
3525 "Commit or stash your changes, and then run\n"
3526 "\n"
3527 " git rebase --continue\n"
3528 "\n"), command_line);
3529 status = 1;
3532 return status;
3535 __attribute__((format (printf, 2, 3)))
3536 static int safe_append(const char *filename, const char *fmt, ...)
3538 va_list ap;
3539 struct lock_file lock = LOCK_INIT;
3540 int fd = hold_lock_file_for_update(&lock, filename,
3541 LOCK_REPORT_ON_ERROR);
3542 struct strbuf buf = STRBUF_INIT;
3544 if (fd < 0)
3545 return -1;
3547 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3548 error_errno(_("could not read '%s'"), filename);
3549 rollback_lock_file(&lock);
3550 return -1;
3552 strbuf_complete(&buf, '\n');
3553 va_start(ap, fmt);
3554 strbuf_vaddf(&buf, fmt, ap);
3555 va_end(ap);
3557 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3558 error_errno(_("could not write to '%s'"), filename);
3559 strbuf_release(&buf);
3560 rollback_lock_file(&lock);
3561 return -1;
3563 if (commit_lock_file(&lock) < 0) {
3564 strbuf_release(&buf);
3565 rollback_lock_file(&lock);
3566 return error(_("failed to finalize '%s'"), filename);
3569 strbuf_release(&buf);
3570 return 0;
3573 static int do_label(struct repository *r, const char *name, int len)
3575 struct ref_store *refs = get_main_ref_store(r);
3576 struct ref_transaction *transaction;
3577 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3578 struct strbuf msg = STRBUF_INIT;
3579 int ret = 0;
3580 struct object_id head_oid;
3582 if (len == 1 && *name == '#')
3583 return error(_("illegal label name: '%.*s'"), len, name);
3585 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3586 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3588 transaction = ref_store_transaction_begin(refs, &err);
3589 if (!transaction) {
3590 error("%s", err.buf);
3591 ret = -1;
3592 } else if (get_oid("HEAD", &head_oid)) {
3593 error(_("could not read HEAD"));
3594 ret = -1;
3595 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3596 NULL, 0, msg.buf, &err) < 0 ||
3597 ref_transaction_commit(transaction, &err)) {
3598 error("%s", err.buf);
3599 ret = -1;
3601 ref_transaction_free(transaction);
3602 strbuf_release(&err);
3603 strbuf_release(&msg);
3605 if (!ret)
3606 ret = safe_append(rebase_path_refs_to_delete(),
3607 "%s\n", ref_name.buf);
3608 strbuf_release(&ref_name);
3610 return ret;
3613 __attribute__((format (printf, 3, 4)))
3614 static const char *reflog_message(struct replay_opts *opts,
3615 const char *sub_action, const char *fmt, ...)
3617 va_list ap;
3618 static struct strbuf buf = STRBUF_INIT;
3619 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3621 va_start(ap, fmt);
3622 strbuf_reset(&buf);
3623 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3624 if (sub_action)
3625 strbuf_addf(&buf, " (%s)", sub_action);
3626 if (fmt) {
3627 strbuf_addstr(&buf, ": ");
3628 strbuf_vaddf(&buf, fmt, ap);
3630 va_end(ap);
3632 return buf.buf;
3635 static int do_reset(struct repository *r,
3636 const char *name, int len,
3637 struct replay_opts *opts)
3639 struct strbuf ref_name = STRBUF_INIT;
3640 struct object_id oid;
3641 struct lock_file lock = LOCK_INIT;
3642 struct tree_desc desc = { 0 };
3643 struct tree *tree;
3644 struct unpack_trees_options unpack_tree_opts = { 0 };
3645 int ret = 0;
3647 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3648 return -1;
3650 if (len == 10 && !strncmp("[new root]", name, len)) {
3651 if (!opts->have_squash_onto) {
3652 const char *hex;
3653 if (commit_tree("", 0, the_hash_algo->empty_tree,
3654 NULL, &opts->squash_onto,
3655 NULL, NULL))
3656 return error(_("writing fake root commit"));
3657 opts->have_squash_onto = 1;
3658 hex = oid_to_hex(&opts->squash_onto);
3659 if (write_message(hex, strlen(hex),
3660 rebase_path_squash_onto(), 0))
3661 return error(_("writing squash-onto"));
3663 oidcpy(&oid, &opts->squash_onto);
3664 } else {
3665 int i;
3667 /* Determine the length of the label */
3668 for (i = 0; i < len; i++)
3669 if (isspace(name[i]))
3670 break;
3671 len = i;
3673 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3674 if (get_oid(ref_name.buf, &oid) &&
3675 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3676 ret = error(_("could not read '%s'"), ref_name.buf);
3677 goto cleanup;
3681 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3682 unpack_tree_opts.head_idx = 1;
3683 unpack_tree_opts.src_index = r->index;
3684 unpack_tree_opts.dst_index = r->index;
3685 unpack_tree_opts.fn = oneway_merge;
3686 unpack_tree_opts.merge = 1;
3687 unpack_tree_opts.update = 1;
3688 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3689 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3691 if (repo_read_index_unmerged(r)) {
3692 ret = error_resolve_conflict(_(action_name(opts)));
3693 goto cleanup;
3696 if (!fill_tree_descriptor(r, &desc, &oid)) {
3697 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3698 goto cleanup;
3701 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3702 ret = -1;
3703 goto cleanup;
3706 tree = parse_tree_indirect(&oid);
3707 prime_cache_tree(r, r->index, tree);
3709 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3710 ret = error(_("could not write index"));
3712 if (!ret)
3713 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3714 len, name), "HEAD", &oid,
3715 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3716 cleanup:
3717 free((void *)desc.buffer);
3718 if (ret < 0)
3719 rollback_lock_file(&lock);
3720 strbuf_release(&ref_name);
3721 clear_unpack_trees_porcelain(&unpack_tree_opts);
3722 return ret;
3725 static struct commit *lookup_label(const char *label, int len,
3726 struct strbuf *buf)
3728 struct commit *commit;
3730 strbuf_reset(buf);
3731 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3732 commit = lookup_commit_reference_by_name(buf->buf);
3733 if (!commit) {
3734 /* fall back to non-rewritten ref or commit */
3735 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3736 commit = lookup_commit_reference_by_name(buf->buf);
3739 if (!commit)
3740 error(_("could not resolve '%s'"), buf->buf);
3742 return commit;
3745 static int do_merge(struct repository *r,
3746 struct commit *commit,
3747 const char *arg, int arg_len,
3748 int flags, int *check_todo, struct replay_opts *opts)
3750 int run_commit_flags = 0;
3751 struct strbuf ref_name = STRBUF_INIT;
3752 struct commit *head_commit, *merge_commit, *i;
3753 struct commit_list *bases, *j;
3754 struct commit_list *to_merge = NULL, **tail = &to_merge;
3755 const char *strategy = !opts->xopts_nr &&
3756 (!opts->strategy ||
3757 !strcmp(opts->strategy, "recursive") ||
3758 !strcmp(opts->strategy, "ort")) ?
3759 NULL : opts->strategy;
3760 struct merge_options o;
3761 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3762 static struct lock_file lock;
3763 const char *p;
3765 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3766 ret = -1;
3767 goto leave_merge;
3770 head_commit = lookup_commit_reference_by_name("HEAD");
3771 if (!head_commit) {
3772 ret = error(_("cannot merge without a current revision"));
3773 goto leave_merge;
3777 * For octopus merges, the arg starts with the list of revisions to be
3778 * merged. The list is optionally followed by '#' and the oneline.
3780 merge_arg_len = oneline_offset = arg_len;
3781 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3782 if (!*p)
3783 break;
3784 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3785 p += 1 + strspn(p + 1, " \t\n");
3786 oneline_offset = p - arg;
3787 break;
3789 k = strcspn(p, " \t\n");
3790 if (!k)
3791 continue;
3792 merge_commit = lookup_label(p, k, &ref_name);
3793 if (!merge_commit) {
3794 ret = error(_("unable to parse '%.*s'"), k, p);
3795 goto leave_merge;
3797 tail = &commit_list_insert(merge_commit, tail)->next;
3798 p += k;
3799 merge_arg_len = p - arg;
3802 if (!to_merge) {
3803 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3804 goto leave_merge;
3807 if (opts->have_squash_onto &&
3808 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3810 * When the user tells us to "merge" something into a
3811 * "[new root]", let's simply fast-forward to the merge head.
3813 rollback_lock_file(&lock);
3814 if (to_merge->next)
3815 ret = error(_("octopus merge cannot be executed on "
3816 "top of a [new root]"));
3817 else
3818 ret = fast_forward_to(r, &to_merge->item->object.oid,
3819 &head_commit->object.oid, 0,
3820 opts);
3821 goto leave_merge;
3825 * If HEAD is not identical to the first parent of the original merge
3826 * commit, we cannot fast-forward.
3828 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3829 oideq(&commit->parents->item->object.oid,
3830 &head_commit->object.oid);
3833 * If any merge head is different from the original one, we cannot
3834 * fast-forward.
3836 if (can_fast_forward) {
3837 struct commit_list *p = commit->parents->next;
3839 for (j = to_merge; j && p; j = j->next, p = p->next)
3840 if (!oideq(&j->item->object.oid,
3841 &p->item->object.oid)) {
3842 can_fast_forward = 0;
3843 break;
3846 * If the number of merge heads differs from the original merge
3847 * commit, we cannot fast-forward.
3849 if (j || p)
3850 can_fast_forward = 0;
3853 if (can_fast_forward) {
3854 rollback_lock_file(&lock);
3855 ret = fast_forward_to(r, &commit->object.oid,
3856 &head_commit->object.oid, 0, opts);
3857 if (flags & TODO_EDIT_MERGE_MSG)
3858 goto fast_forward_edit;
3860 goto leave_merge;
3863 if (commit) {
3864 const char *encoding = get_commit_output_encoding();
3865 const char *message = logmsg_reencode(commit, NULL, encoding);
3866 const char *body;
3867 int len;
3869 if (!message) {
3870 ret = error(_("could not get commit message of '%s'"),
3871 oid_to_hex(&commit->object.oid));
3872 goto leave_merge;
3874 write_author_script(message);
3875 find_commit_subject(message, &body);
3876 len = strlen(body);
3877 ret = write_message(body, len, git_path_merge_msg(r), 0);
3878 unuse_commit_buffer(commit, message);
3879 if (ret) {
3880 error_errno(_("could not write '%s'"),
3881 git_path_merge_msg(r));
3882 goto leave_merge;
3884 } else {
3885 struct strbuf buf = STRBUF_INIT;
3886 int len;
3888 strbuf_addf(&buf, "author %s", git_author_info(0));
3889 write_author_script(buf.buf);
3890 strbuf_reset(&buf);
3892 if (oneline_offset < arg_len) {
3893 p = arg + oneline_offset;
3894 len = arg_len - oneline_offset;
3895 } else {
3896 strbuf_addf(&buf, "Merge %s '%.*s'",
3897 to_merge->next ? "branches" : "branch",
3898 merge_arg_len, arg);
3899 p = buf.buf;
3900 len = buf.len;
3903 ret = write_message(p, len, git_path_merge_msg(r), 0);
3904 strbuf_release(&buf);
3905 if (ret) {
3906 error_errno(_("could not write '%s'"),
3907 git_path_merge_msg(r));
3908 goto leave_merge;
3912 if (strategy || to_merge->next) {
3913 /* Octopus merge */
3914 struct child_process cmd = CHILD_PROCESS_INIT;
3916 if (read_env_script(&cmd.env)) {
3917 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3919 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3920 goto leave_merge;
3923 if (opts->committer_date_is_author_date)
3924 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
3925 opts->ignore_date ?
3926 "" :
3927 author_date_from_env(&cmd.env));
3928 if (opts->ignore_date)
3929 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
3931 cmd.git_cmd = 1;
3932 strvec_push(&cmd.args, "merge");
3933 strvec_push(&cmd.args, "-s");
3934 if (!strategy)
3935 strvec_push(&cmd.args, "octopus");
3936 else {
3937 strvec_push(&cmd.args, strategy);
3938 for (k = 0; k < opts->xopts_nr; k++)
3939 strvec_pushf(&cmd.args,
3940 "-X%s", opts->xopts[k]);
3942 if (!(flags & TODO_EDIT_MERGE_MSG))
3943 strvec_push(&cmd.args, "--no-edit");
3944 else
3945 strvec_push(&cmd.args, "--edit");
3946 strvec_push(&cmd.args, "--no-ff");
3947 strvec_push(&cmd.args, "--no-log");
3948 strvec_push(&cmd.args, "--no-stat");
3949 strvec_push(&cmd.args, "-F");
3950 strvec_push(&cmd.args, git_path_merge_msg(r));
3951 if (opts->gpg_sign)
3952 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3953 else
3954 strvec_push(&cmd.args, "--no-gpg-sign");
3956 /* Add the tips to be merged */
3957 for (j = to_merge; j; j = j->next)
3958 strvec_push(&cmd.args,
3959 oid_to_hex(&j->item->object.oid));
3961 strbuf_release(&ref_name);
3962 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3963 NULL, 0);
3964 rollback_lock_file(&lock);
3966 ret = run_command(&cmd);
3968 /* force re-reading of the cache */
3969 if (!ret && (discard_index(r->index) < 0 ||
3970 repo_read_index(r) < 0))
3971 ret = error(_("could not read index"));
3972 goto leave_merge;
3975 merge_commit = to_merge->item;
3976 bases = get_merge_bases(head_commit, merge_commit);
3977 if (bases && oideq(&merge_commit->object.oid,
3978 &bases->item->object.oid)) {
3979 ret = 0;
3980 /* skip merging an ancestor of HEAD */
3981 goto leave_merge;
3984 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3985 git_path_merge_head(r), 0);
3986 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3988 bases = reverse_commit_list(bases);
3990 repo_read_index(r);
3991 init_merge_options(&o, r);
3992 o.branch1 = "HEAD";
3993 o.branch2 = ref_name.buf;
3994 o.buffer_output = 2;
3996 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
3998 * TODO: Should use merge_incore_recursive() and
3999 * merge_switch_to_result(), skipping the call to
4000 * merge_switch_to_result() when we don't actually need to
4001 * update the index and working copy immediately.
4003 ret = merge_ort_recursive(&o,
4004 head_commit, merge_commit, bases,
4005 &i);
4006 } else {
4007 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4008 &i);
4010 if (ret <= 0)
4011 fputs(o.obuf.buf, stdout);
4012 strbuf_release(&o.obuf);
4013 if (ret < 0) {
4014 error(_("could not even attempt to merge '%.*s'"),
4015 merge_arg_len, arg);
4016 goto leave_merge;
4019 * The return value of merge_recursive() is 1 on clean, and 0 on
4020 * unclean merge.
4022 * Let's reverse that, so that do_merge() returns 0 upon success and
4023 * 1 upon failed merge (keeping the return value -1 for the cases where
4024 * we will want to reschedule the `merge` command).
4026 ret = !ret;
4028 if (r->index->cache_changed &&
4029 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4030 ret = error(_("merge: Unable to write new index file"));
4031 goto leave_merge;
4034 rollback_lock_file(&lock);
4035 if (ret)
4036 repo_rerere(r, opts->allow_rerere_auto);
4037 else
4039 * In case of problems, we now want to return a positive
4040 * value (a negative one would indicate that the `merge`
4041 * command needs to be rescheduled).
4043 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4044 run_commit_flags);
4046 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4047 fast_forward_edit:
4048 *check_todo = 1;
4049 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4050 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4054 leave_merge:
4055 strbuf_release(&ref_name);
4056 rollback_lock_file(&lock);
4057 free_commit_list(to_merge);
4058 return ret;
4061 static int is_final_fixup(struct todo_list *todo_list)
4063 int i = todo_list->current;
4065 if (!is_fixup(todo_list->items[i].command))
4066 return 0;
4068 while (++i < todo_list->nr)
4069 if (is_fixup(todo_list->items[i].command))
4070 return 0;
4071 else if (!is_noop(todo_list->items[i].command))
4072 break;
4073 return 1;
4076 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4078 int i;
4080 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4081 if (!is_noop(todo_list->items[i].command))
4082 return todo_list->items[i].command;
4084 return -1;
4087 void create_autostash(struct repository *r, const char *path)
4089 struct strbuf buf = STRBUF_INIT;
4090 struct lock_file lock_file = LOCK_INIT;
4091 int fd;
4093 fd = repo_hold_locked_index(r, &lock_file, 0);
4094 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4095 if (0 <= fd)
4096 repo_update_index_if_able(r, &lock_file);
4097 rollback_lock_file(&lock_file);
4099 if (has_unstaged_changes(r, 1) ||
4100 has_uncommitted_changes(r, 1)) {
4101 struct child_process stash = CHILD_PROCESS_INIT;
4102 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4103 struct object_id oid;
4105 strvec_pushl(&stash.args,
4106 "stash", "create", "autostash", NULL);
4107 stash.git_cmd = 1;
4108 stash.no_stdin = 1;
4109 strbuf_reset(&buf);
4110 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4111 die(_("Cannot autostash"));
4112 strbuf_trim_trailing_newline(&buf);
4113 if (get_oid(buf.buf, &oid))
4114 die(_("Unexpected stash response: '%s'"),
4115 buf.buf);
4116 strbuf_reset(&buf);
4117 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4119 if (safe_create_leading_directories_const(path))
4120 die(_("Could not create directory for '%s'"),
4121 path);
4122 write_file(path, "%s", oid_to_hex(&oid));
4123 printf(_("Created autostash: %s\n"), buf.buf);
4124 if (reset_head(r, &ropts) < 0)
4125 die(_("could not reset --hard"));
4126 if (discard_index(r->index) < 0 ||
4127 repo_read_index(r) < 0)
4128 die(_("could not read index"));
4130 strbuf_release(&buf);
4133 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4135 struct child_process child = CHILD_PROCESS_INIT;
4136 int ret = 0;
4138 if (attempt_apply) {
4139 child.git_cmd = 1;
4140 child.no_stdout = 1;
4141 child.no_stderr = 1;
4142 strvec_push(&child.args, "stash");
4143 strvec_push(&child.args, "apply");
4144 strvec_push(&child.args, stash_oid);
4145 ret = run_command(&child);
4148 if (attempt_apply && !ret)
4149 fprintf(stderr, _("Applied autostash.\n"));
4150 else {
4151 struct child_process store = CHILD_PROCESS_INIT;
4153 store.git_cmd = 1;
4154 strvec_push(&store.args, "stash");
4155 strvec_push(&store.args, "store");
4156 strvec_push(&store.args, "-m");
4157 strvec_push(&store.args, "autostash");
4158 strvec_push(&store.args, "-q");
4159 strvec_push(&store.args, stash_oid);
4160 if (run_command(&store))
4161 ret = error(_("cannot store %s"), stash_oid);
4162 else
4163 fprintf(stderr,
4164 _("%s\n"
4165 "Your changes are safe in the stash.\n"
4166 "You can run \"git stash pop\" or"
4167 " \"git stash drop\" at any time.\n"),
4168 attempt_apply ?
4169 _("Applying autostash resulted in conflicts.") :
4170 _("Autostash exists; creating a new stash entry."));
4173 return ret;
4176 static int apply_save_autostash(const char *path, int attempt_apply)
4178 struct strbuf stash_oid = STRBUF_INIT;
4179 int ret = 0;
4181 if (!read_oneliner(&stash_oid, path,
4182 READ_ONELINER_SKIP_IF_EMPTY)) {
4183 strbuf_release(&stash_oid);
4184 return 0;
4186 strbuf_trim(&stash_oid);
4188 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4190 unlink(path);
4191 strbuf_release(&stash_oid);
4192 return ret;
4195 int save_autostash(const char *path)
4197 return apply_save_autostash(path, 0);
4200 int apply_autostash(const char *path)
4202 return apply_save_autostash(path, 1);
4205 int apply_autostash_oid(const char *stash_oid)
4207 return apply_save_autostash_oid(stash_oid, 1);
4210 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4211 const char *onto_name, const struct object_id *onto,
4212 const struct object_id *orig_head)
4214 struct reset_head_opts ropts = {
4215 .oid = onto,
4216 .orig_head = orig_head,
4217 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4218 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4219 .head_msg = reflog_message(opts, "start", "checkout %s",
4220 onto_name),
4221 .default_reflog_action = "rebase"
4223 if (reset_head(r, &ropts)) {
4224 apply_autostash(rebase_path_autostash());
4225 sequencer_remove_state(opts);
4226 return error(_("could not detach HEAD"));
4229 return 0;
4232 static int stopped_at_head(struct repository *r)
4234 struct object_id head;
4235 struct commit *commit;
4236 struct commit_message message;
4238 if (get_oid("HEAD", &head) ||
4239 !(commit = lookup_commit(r, &head)) ||
4240 parse_commit(commit) || get_message(commit, &message))
4241 fprintf(stderr, _("Stopped at HEAD\n"));
4242 else {
4243 fprintf(stderr, _("Stopped at %s\n"), message.label);
4244 free_message(commit, &message);
4246 return 0;
4250 static int reread_todo_if_changed(struct repository *r,
4251 struct todo_list *todo_list,
4252 struct replay_opts *opts)
4254 int offset;
4255 struct strbuf buf = STRBUF_INIT;
4257 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4258 return -1;
4259 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4260 if (buf.len != todo_list->buf.len - offset ||
4261 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4262 /* Reread the todo file if it has changed. */
4263 todo_list_release(todo_list);
4264 if (read_populate_todo(r, todo_list, opts))
4265 return -1; /* message was printed */
4266 /* `current` will be incremented on return */
4267 todo_list->current = -1;
4269 strbuf_release(&buf);
4271 return 0;
4274 static const char rescheduled_advice[] =
4275 N_("Could not execute the todo command\n"
4276 "\n"
4277 " %.*s"
4278 "\n"
4279 "It has been rescheduled; To edit the command before continuing, please\n"
4280 "edit the todo list first:\n"
4281 "\n"
4282 " git rebase --edit-todo\n"
4283 " git rebase --continue\n");
4285 static int pick_commits(struct repository *r,
4286 struct todo_list *todo_list,
4287 struct replay_opts *opts)
4289 int res = 0, reschedule = 0;
4290 char *prev_reflog_action;
4292 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4293 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4294 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4295 if (opts->allow_ff)
4296 assert(!(opts->signoff || opts->no_commit ||
4297 opts->record_origin || should_edit(opts) ||
4298 opts->committer_date_is_author_date ||
4299 opts->ignore_date));
4300 if (read_and_refresh_cache(r, opts))
4301 return -1;
4303 while (todo_list->current < todo_list->nr) {
4304 struct todo_item *item = todo_list->items + todo_list->current;
4305 const char *arg = todo_item_get_arg(todo_list, item);
4306 int check_todo = 0;
4308 if (save_todo(todo_list, opts))
4309 return -1;
4310 if (is_rebase_i(opts)) {
4311 if (item->command != TODO_COMMENT) {
4312 FILE *f = fopen(rebase_path_msgnum(), "w");
4314 todo_list->done_nr++;
4316 if (f) {
4317 fprintf(f, "%d\n", todo_list->done_nr);
4318 fclose(f);
4320 if (!opts->quiet)
4321 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4322 todo_list->done_nr,
4323 todo_list->total_nr,
4324 opts->verbose ? "\n" : "\r");
4326 unlink(rebase_path_message());
4327 unlink(rebase_path_author_script());
4328 unlink(rebase_path_stopped_sha());
4329 unlink(rebase_path_amend());
4330 unlink(git_path_merge_head(r));
4331 unlink(git_path_auto_merge(r));
4332 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4334 if (item->command == TODO_BREAK) {
4335 if (!opts->verbose)
4336 term_clear_line();
4337 return stopped_at_head(r);
4340 if (item->command <= TODO_SQUASH) {
4341 if (is_rebase_i(opts))
4342 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4343 command_to_string(item->command), NULL),
4345 res = do_pick_commit(r, item, opts,
4346 is_final_fixup(todo_list),
4347 &check_todo);
4348 if (is_rebase_i(opts))
4349 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4350 if (is_rebase_i(opts) && res < 0) {
4351 /* Reschedule */
4352 advise(_(rescheduled_advice),
4353 get_item_line_length(todo_list,
4354 todo_list->current),
4355 get_item_line(todo_list,
4356 todo_list->current));
4357 todo_list->current--;
4358 if (save_todo(todo_list, opts))
4359 return -1;
4361 if (item->command == TODO_EDIT) {
4362 struct commit *commit = item->commit;
4363 if (!res) {
4364 if (!opts->verbose)
4365 term_clear_line();
4366 fprintf(stderr,
4367 _("Stopped at %s... %.*s\n"),
4368 short_commit_name(commit),
4369 item->arg_len, arg);
4371 return error_with_patch(r, commit,
4372 arg, item->arg_len, opts, res, !res);
4374 if (is_rebase_i(opts) && !res)
4375 record_in_rewritten(&item->commit->object.oid,
4376 peek_command(todo_list, 1));
4377 if (res && is_fixup(item->command)) {
4378 if (res == 1)
4379 intend_to_amend();
4380 return error_failed_squash(r, item->commit, opts,
4381 item->arg_len, arg);
4382 } else if (res && is_rebase_i(opts) && item->commit) {
4383 int to_amend = 0;
4384 struct object_id oid;
4387 * If we are rewording and have either
4388 * fast-forwarded already, or are about to
4389 * create a new root commit, we want to amend,
4390 * otherwise we do not.
4392 if (item->command == TODO_REWORD &&
4393 !get_oid("HEAD", &oid) &&
4394 (oideq(&item->commit->object.oid, &oid) ||
4395 (opts->have_squash_onto &&
4396 oideq(&opts->squash_onto, &oid))))
4397 to_amend = 1;
4399 return res | error_with_patch(r, item->commit,
4400 arg, item->arg_len, opts,
4401 res, to_amend);
4403 } else if (item->command == TODO_EXEC) {
4404 char *end_of_arg = (char *)(arg + item->arg_len);
4405 int saved = *end_of_arg;
4407 if (!opts->verbose)
4408 term_clear_line();
4409 *end_of_arg = '\0';
4410 res = do_exec(r, arg);
4411 *end_of_arg = saved;
4413 if (res) {
4414 if (opts->reschedule_failed_exec)
4415 reschedule = 1;
4417 check_todo = 1;
4418 } else if (item->command == TODO_LABEL) {
4419 if ((res = do_label(r, arg, item->arg_len)))
4420 reschedule = 1;
4421 } else if (item->command == TODO_RESET) {
4422 if ((res = do_reset(r, arg, item->arg_len, opts)))
4423 reschedule = 1;
4424 } else if (item->command == TODO_MERGE) {
4425 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4426 item->flags, &check_todo, opts)) < 0)
4427 reschedule = 1;
4428 else if (item->commit)
4429 record_in_rewritten(&item->commit->object.oid,
4430 peek_command(todo_list, 1));
4431 if (res > 0)
4432 /* failed with merge conflicts */
4433 return error_with_patch(r, item->commit,
4434 arg, item->arg_len,
4435 opts, res, 0);
4436 } else if (!is_noop(item->command))
4437 return error(_("unknown command %d"), item->command);
4439 if (reschedule) {
4440 advise(_(rescheduled_advice),
4441 get_item_line_length(todo_list,
4442 todo_list->current),
4443 get_item_line(todo_list, todo_list->current));
4444 todo_list->current--;
4445 if (save_todo(todo_list, opts))
4446 return -1;
4447 if (item->commit)
4448 return error_with_patch(r,
4449 item->commit,
4450 arg, item->arg_len,
4451 opts, res, 0);
4452 } else if (is_rebase_i(opts) && check_todo && !res &&
4453 reread_todo_if_changed(r, todo_list, opts)) {
4454 return -1;
4457 todo_list->current++;
4458 if (res)
4459 return res;
4462 if (is_rebase_i(opts)) {
4463 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4464 struct stat st;
4466 /* Stopped in the middle, as planned? */
4467 if (todo_list->current < todo_list->nr)
4468 return 0;
4470 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4471 starts_with(head_ref.buf, "refs/")) {
4472 const char *msg;
4473 struct object_id head, orig;
4474 int res;
4476 if (get_oid("HEAD", &head)) {
4477 res = error(_("cannot read HEAD"));
4478 cleanup_head_ref:
4479 strbuf_release(&head_ref);
4480 strbuf_release(&buf);
4481 return res;
4483 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4484 get_oid_hex(buf.buf, &orig)) {
4485 res = error(_("could not read orig-head"));
4486 goto cleanup_head_ref;
4488 strbuf_reset(&buf);
4489 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4490 res = error(_("could not read 'onto'"));
4491 goto cleanup_head_ref;
4493 msg = reflog_message(opts, "finish", "%s onto %s",
4494 head_ref.buf, buf.buf);
4495 if (update_ref(msg, head_ref.buf, &head, &orig,
4496 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4497 res = error(_("could not update %s"),
4498 head_ref.buf);
4499 goto cleanup_head_ref;
4501 msg = reflog_message(opts, "finish", "returning to %s",
4502 head_ref.buf);
4503 if (create_symref("HEAD", head_ref.buf, msg)) {
4504 res = error(_("could not update HEAD to %s"),
4505 head_ref.buf);
4506 goto cleanup_head_ref;
4508 strbuf_reset(&buf);
4511 if (opts->verbose) {
4512 struct rev_info log_tree_opt;
4513 struct object_id orig, head;
4515 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4516 repo_init_revisions(r, &log_tree_opt, NULL);
4517 log_tree_opt.diff = 1;
4518 log_tree_opt.diffopt.output_format =
4519 DIFF_FORMAT_DIFFSTAT;
4520 log_tree_opt.disable_stdin = 1;
4522 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4523 !get_oid(buf.buf, &orig) &&
4524 !get_oid("HEAD", &head)) {
4525 diff_tree_oid(&orig, &head, "",
4526 &log_tree_opt.diffopt);
4527 log_tree_diff_flush(&log_tree_opt);
4529 release_revisions(&log_tree_opt);
4531 flush_rewritten_pending();
4532 if (!stat(rebase_path_rewritten_list(), &st) &&
4533 st.st_size > 0) {
4534 struct child_process child = CHILD_PROCESS_INIT;
4535 const char *post_rewrite_hook =
4536 find_hook("post-rewrite");
4538 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4539 child.git_cmd = 1;
4540 strvec_push(&child.args, "notes");
4541 strvec_push(&child.args, "copy");
4542 strvec_push(&child.args, "--for-rewrite=rebase");
4543 /* we don't care if this copying failed */
4544 run_command(&child);
4546 if (post_rewrite_hook) {
4547 struct child_process hook = CHILD_PROCESS_INIT;
4549 hook.in = open(rebase_path_rewritten_list(),
4550 O_RDONLY);
4551 hook.stdout_to_stderr = 1;
4552 hook.trace2_hook_name = "post-rewrite";
4553 strvec_push(&hook.args, post_rewrite_hook);
4554 strvec_push(&hook.args, "rebase");
4555 /* we don't care if this hook failed */
4556 run_command(&hook);
4559 apply_autostash(rebase_path_autostash());
4561 if (!opts->quiet) {
4562 if (!opts->verbose)
4563 term_clear_line();
4564 fprintf(stderr,
4565 _("Successfully rebased and updated %s.\n"),
4566 head_ref.buf);
4569 strbuf_release(&buf);
4570 strbuf_release(&head_ref);
4574 * Sequence of picks finished successfully; cleanup by
4575 * removing the .git/sequencer directory
4577 return sequencer_remove_state(opts);
4580 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4582 struct strvec argv = STRVEC_INIT;
4583 int ret;
4585 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4586 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4587 return error(_("no cherry-pick or revert in progress"));
4589 strvec_push(&argv, "commit");
4592 * continue_single_pick() handles the case of recovering from a
4593 * conflict. should_edit() doesn't handle that case; for a conflict,
4594 * we want to edit if the user asked for it, or if they didn't specify
4595 * and stdin is a tty.
4597 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4599 * Include --cleanup=strip as well because we don't want the
4600 * "# Conflicts:" messages.
4602 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4604 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4605 strvec_clear(&argv);
4606 return ret;
4609 static int commit_staged_changes(struct repository *r,
4610 struct replay_opts *opts,
4611 struct todo_list *todo_list)
4613 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4614 unsigned int final_fixup = 0, is_clean;
4616 if (has_unstaged_changes(r, 1))
4617 return error(_("cannot rebase: You have unstaged changes."));
4619 is_clean = !has_uncommitted_changes(r, 0);
4621 if (file_exists(rebase_path_amend())) {
4622 struct strbuf rev = STRBUF_INIT;
4623 struct object_id head, to_amend;
4625 if (get_oid("HEAD", &head))
4626 return error(_("cannot amend non-existing commit"));
4627 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4628 return error(_("invalid file: '%s'"), rebase_path_amend());
4629 if (get_oid_hex(rev.buf, &to_amend))
4630 return error(_("invalid contents: '%s'"),
4631 rebase_path_amend());
4632 if (!is_clean && !oideq(&head, &to_amend))
4633 return error(_("\nYou have uncommitted changes in your "
4634 "working tree. Please, commit them\n"
4635 "first and then run 'git rebase "
4636 "--continue' again."));
4638 * When skipping a failed fixup/squash, we need to edit the
4639 * commit message, the current fixup list and count, and if it
4640 * was the last fixup/squash in the chain, we need to clean up
4641 * the commit message and if there was a squash, let the user
4642 * edit it.
4644 if (!is_clean || !opts->current_fixup_count)
4645 ; /* this is not the final fixup */
4646 else if (!oideq(&head, &to_amend) ||
4647 !file_exists(rebase_path_stopped_sha())) {
4648 /* was a final fixup or squash done manually? */
4649 if (!is_fixup(peek_command(todo_list, 0))) {
4650 unlink(rebase_path_fixup_msg());
4651 unlink(rebase_path_squash_msg());
4652 unlink(rebase_path_current_fixups());
4653 strbuf_reset(&opts->current_fixups);
4654 opts->current_fixup_count = 0;
4656 } else {
4657 /* we are in a fixup/squash chain */
4658 const char *p = opts->current_fixups.buf;
4659 int len = opts->current_fixups.len;
4661 opts->current_fixup_count--;
4662 if (!len)
4663 BUG("Incorrect current_fixups:\n%s", p);
4664 while (len && p[len - 1] != '\n')
4665 len--;
4666 strbuf_setlen(&opts->current_fixups, len);
4667 if (write_message(p, len, rebase_path_current_fixups(),
4668 0) < 0)
4669 return error(_("could not write file: '%s'"),
4670 rebase_path_current_fixups());
4673 * If a fixup/squash in a fixup/squash chain failed, the
4674 * commit message is already correct, no need to commit
4675 * it again.
4677 * Only if it is the final command in the fixup/squash
4678 * chain, and only if the chain is longer than a single
4679 * fixup/squash command (which was just skipped), do we
4680 * actually need to re-commit with a cleaned up commit
4681 * message.
4683 if (opts->current_fixup_count > 0 &&
4684 !is_fixup(peek_command(todo_list, 0))) {
4685 final_fixup = 1;
4687 * If there was not a single "squash" in the
4688 * chain, we only need to clean up the commit
4689 * message, no need to bother the user with
4690 * opening the commit message in the editor.
4692 if (!starts_with(p, "squash ") &&
4693 !strstr(p, "\nsquash "))
4694 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4695 } else if (is_fixup(peek_command(todo_list, 0))) {
4697 * We need to update the squash message to skip
4698 * the latest commit message.
4700 struct commit *commit;
4701 const char *path = rebase_path_squash_msg();
4702 const char *encoding = get_commit_output_encoding();
4704 if (parse_head(r, &commit) ||
4705 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4706 write_message(p, strlen(p), path, 0)) {
4707 unuse_commit_buffer(commit, p);
4708 return error(_("could not write file: "
4709 "'%s'"), path);
4711 unuse_commit_buffer(commit, p);
4715 strbuf_release(&rev);
4716 flags |= AMEND_MSG;
4719 if (is_clean) {
4720 if (refs_ref_exists(get_main_ref_store(r),
4721 "CHERRY_PICK_HEAD") &&
4722 refs_delete_ref(get_main_ref_store(r), "",
4723 "CHERRY_PICK_HEAD", NULL, 0))
4724 return error(_("could not remove CHERRY_PICK_HEAD"));
4725 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4726 return error_errno(_("could not remove '%s'"),
4727 git_path_merge_msg(r));
4728 if (!final_fixup)
4729 return 0;
4732 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4733 opts, flags))
4734 return error(_("could not commit staged changes."));
4735 unlink(rebase_path_amend());
4736 unlink(git_path_merge_head(r));
4737 unlink(git_path_auto_merge(r));
4738 if (final_fixup) {
4739 unlink(rebase_path_fixup_msg());
4740 unlink(rebase_path_squash_msg());
4742 if (opts->current_fixup_count > 0) {
4744 * Whether final fixup or not, we just cleaned up the commit
4745 * message...
4747 unlink(rebase_path_current_fixups());
4748 strbuf_reset(&opts->current_fixups);
4749 opts->current_fixup_count = 0;
4751 return 0;
4754 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4756 struct todo_list todo_list = TODO_LIST_INIT;
4757 int res;
4759 if (read_and_refresh_cache(r, opts))
4760 return -1;
4762 if (read_populate_opts(opts))
4763 return -1;
4764 if (is_rebase_i(opts)) {
4765 if ((res = read_populate_todo(r, &todo_list, opts)))
4766 goto release_todo_list;
4768 if (file_exists(rebase_path_dropped())) {
4769 if ((res = todo_list_check_against_backup(r, &todo_list)))
4770 goto release_todo_list;
4772 unlink(rebase_path_dropped());
4775 if (commit_staged_changes(r, opts, &todo_list)) {
4776 res = -1;
4777 goto release_todo_list;
4779 } else if (!file_exists(get_todo_path(opts)))
4780 return continue_single_pick(r, opts);
4781 else if ((res = read_populate_todo(r, &todo_list, opts)))
4782 goto release_todo_list;
4784 if (!is_rebase_i(opts)) {
4785 /* Verify that the conflict has been resolved */
4786 if (refs_ref_exists(get_main_ref_store(r),
4787 "CHERRY_PICK_HEAD") ||
4788 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4789 res = continue_single_pick(r, opts);
4790 if (res)
4791 goto release_todo_list;
4793 if (index_differs_from(r, "HEAD", NULL, 0)) {
4794 res = error_dirty_index(r, opts);
4795 goto release_todo_list;
4797 todo_list.current++;
4798 } else if (file_exists(rebase_path_stopped_sha())) {
4799 struct strbuf buf = STRBUF_INIT;
4800 struct object_id oid;
4802 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4803 READ_ONELINER_SKIP_IF_EMPTY) &&
4804 !get_oid_hex(buf.buf, &oid))
4805 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4806 strbuf_release(&buf);
4809 res = pick_commits(r, &todo_list, opts);
4810 release_todo_list:
4811 todo_list_release(&todo_list);
4812 return res;
4815 static int single_pick(struct repository *r,
4816 struct commit *cmit,
4817 struct replay_opts *opts)
4819 int check_todo;
4820 struct todo_item item;
4822 item.command = opts->action == REPLAY_PICK ?
4823 TODO_PICK : TODO_REVERT;
4824 item.commit = cmit;
4826 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4827 return do_pick_commit(r, &item, opts, 0, &check_todo);
4830 int sequencer_pick_revisions(struct repository *r,
4831 struct replay_opts *opts)
4833 struct todo_list todo_list = TODO_LIST_INIT;
4834 struct object_id oid;
4835 int i, res;
4837 assert(opts->revs);
4838 if (read_and_refresh_cache(r, opts))
4839 return -1;
4841 for (i = 0; i < opts->revs->pending.nr; i++) {
4842 struct object_id oid;
4843 const char *name = opts->revs->pending.objects[i].name;
4845 /* This happens when using --stdin. */
4846 if (!strlen(name))
4847 continue;
4849 if (!get_oid(name, &oid)) {
4850 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4851 enum object_type type = oid_object_info(r,
4852 &oid,
4853 NULL);
4854 return error(_("%s: can't cherry-pick a %s"),
4855 name, type_name(type));
4857 } else
4858 return error(_("%s: bad revision"), name);
4862 * If we were called as "git cherry-pick <commit>", just
4863 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4864 * REVERT_HEAD, and don't touch the sequencer state.
4865 * This means it is possible to cherry-pick in the middle
4866 * of a cherry-pick sequence.
4868 if (opts->revs->cmdline.nr == 1 &&
4869 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4870 opts->revs->no_walk &&
4871 !opts->revs->cmdline.rev->flags) {
4872 struct commit *cmit;
4873 if (prepare_revision_walk(opts->revs))
4874 return error(_("revision walk setup failed"));
4875 cmit = get_revision(opts->revs);
4876 if (!cmit)
4877 return error(_("empty commit set passed"));
4878 if (get_revision(opts->revs))
4879 BUG("unexpected extra commit from walk");
4880 return single_pick(r, cmit, opts);
4884 * Start a new cherry-pick/ revert sequence; but
4885 * first, make sure that an existing one isn't in
4886 * progress
4889 if (walk_revs_populate_todo(&todo_list, opts) ||
4890 create_seq_dir(r) < 0)
4891 return -1;
4892 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4893 return error(_("can't revert as initial commit"));
4894 if (save_head(oid_to_hex(&oid)))
4895 return -1;
4896 if (save_opts(opts))
4897 return -1;
4898 update_abort_safety_file();
4899 res = pick_commits(r, &todo_list, opts);
4900 todo_list_release(&todo_list);
4901 return res;
4904 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4906 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4907 struct strbuf sob = STRBUF_INIT;
4908 int has_footer;
4910 strbuf_addstr(&sob, sign_off_header);
4911 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4912 strbuf_addch(&sob, '\n');
4914 if (!ignore_footer)
4915 strbuf_complete_line(msgbuf);
4918 * If the whole message buffer is equal to the sob, pretend that we
4919 * found a conforming footer with a matching sob
4921 if (msgbuf->len - ignore_footer == sob.len &&
4922 !strncmp(msgbuf->buf, sob.buf, sob.len))
4923 has_footer = 3;
4924 else
4925 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4927 if (!has_footer) {
4928 const char *append_newlines = NULL;
4929 size_t len = msgbuf->len - ignore_footer;
4931 if (!len) {
4933 * The buffer is completely empty. Leave foom for
4934 * the title and body to be filled in by the user.
4936 append_newlines = "\n\n";
4937 } else if (len == 1) {
4939 * Buffer contains a single newline. Add another
4940 * so that we leave room for the title and body.
4942 append_newlines = "\n";
4943 } else if (msgbuf->buf[len - 2] != '\n') {
4945 * Buffer ends with a single newline. Add another
4946 * so that there is an empty line between the message
4947 * body and the sob.
4949 append_newlines = "\n";
4950 } /* else, the buffer already ends with two newlines. */
4952 if (append_newlines)
4953 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4954 append_newlines, strlen(append_newlines));
4957 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4958 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4959 sob.buf, sob.len);
4961 strbuf_release(&sob);
4964 struct labels_entry {
4965 struct hashmap_entry entry;
4966 char label[FLEX_ARRAY];
4969 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4970 const struct hashmap_entry *entry_or_key, const void *key)
4972 const struct labels_entry *a, *b;
4974 a = container_of(eptr, const struct labels_entry, entry);
4975 b = container_of(entry_or_key, const struct labels_entry, entry);
4977 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4980 struct string_entry {
4981 struct oidmap_entry entry;
4982 char string[FLEX_ARRAY];
4985 struct label_state {
4986 struct oidmap commit2label;
4987 struct hashmap labels;
4988 struct strbuf buf;
4991 static const char *label_oid(struct object_id *oid, const char *label,
4992 struct label_state *state)
4994 struct labels_entry *labels_entry;
4995 struct string_entry *string_entry;
4996 struct object_id dummy;
4997 int i;
4999 string_entry = oidmap_get(&state->commit2label, oid);
5000 if (string_entry)
5001 return string_entry->string;
5004 * For "uninteresting" commits, i.e. commits that are not to be
5005 * rebased, and which can therefore not be labeled, we use a unique
5006 * abbreviation of the commit name. This is slightly more complicated
5007 * than calling find_unique_abbrev() because we also need to make
5008 * sure that the abbreviation does not conflict with any other
5009 * label.
5011 * We disallow "interesting" commits to be labeled by a string that
5012 * is a valid full-length hash, to ensure that we always can find an
5013 * abbreviation for any uninteresting commit's names that does not
5014 * clash with any other label.
5016 strbuf_reset(&state->buf);
5017 if (!label) {
5018 char *p;
5020 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5021 label = p = state->buf.buf;
5023 find_unique_abbrev_r(p, oid, default_abbrev);
5026 * We may need to extend the abbreviated hash so that there is
5027 * no conflicting label.
5029 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5030 size_t i = strlen(p) + 1;
5032 oid_to_hex_r(p, oid);
5033 for (; i < the_hash_algo->hexsz; i++) {
5034 char save = p[i];
5035 p[i] = '\0';
5036 if (!hashmap_get_from_hash(&state->labels,
5037 strihash(p), p))
5038 break;
5039 p[i] = save;
5042 } else {
5043 struct strbuf *buf = &state->buf;
5046 * Sanitize labels by replacing non-alpha-numeric characters
5047 * (including white-space ones) by dashes, as they might be
5048 * illegal in file names (and hence in ref names).
5050 * Note that we retain non-ASCII UTF-8 characters (identified
5051 * via the most significant bit). They should be all acceptable
5052 * in file names. We do not validate the UTF-8 here, that's not
5053 * the job of this function.
5055 for (; *label; label++)
5056 if ((*label & 0x80) || isalnum(*label))
5057 strbuf_addch(buf, *label);
5058 /* avoid leading dash and double-dashes */
5059 else if (buf->len && buf->buf[buf->len - 1] != '-')
5060 strbuf_addch(buf, '-');
5061 if (!buf->len) {
5062 strbuf_addstr(buf, "rev-");
5063 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5065 label = buf->buf;
5067 if ((buf->len == the_hash_algo->hexsz &&
5068 !get_oid_hex(label, &dummy)) ||
5069 (buf->len == 1 && *label == '#') ||
5070 hashmap_get_from_hash(&state->labels,
5071 strihash(label), label)) {
5073 * If the label already exists, or if the label is a
5074 * valid full OID, or the label is a '#' (which we use
5075 * as a separator between merge heads and oneline), we
5076 * append a dash and a number to make it unique.
5078 size_t len = buf->len;
5080 for (i = 2; ; i++) {
5081 strbuf_setlen(buf, len);
5082 strbuf_addf(buf, "-%d", i);
5083 if (!hashmap_get_from_hash(&state->labels,
5084 strihash(buf->buf),
5085 buf->buf))
5086 break;
5089 label = buf->buf;
5093 FLEX_ALLOC_STR(labels_entry, label, label);
5094 hashmap_entry_init(&labels_entry->entry, strihash(label));
5095 hashmap_add(&state->labels, &labels_entry->entry);
5097 FLEX_ALLOC_STR(string_entry, string, label);
5098 oidcpy(&string_entry->entry.oid, oid);
5099 oidmap_put(&state->commit2label, string_entry);
5101 return string_entry->string;
5104 static int make_script_with_merges(struct pretty_print_context *pp,
5105 struct rev_info *revs, struct strbuf *out,
5106 unsigned flags)
5108 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5109 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5110 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5111 int skipped_commit = 0;
5112 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5113 struct strbuf label = STRBUF_INIT;
5114 struct commit_list *commits = NULL, **tail = &commits, *iter;
5115 struct commit_list *tips = NULL, **tips_tail = &tips;
5116 struct commit *commit;
5117 struct oidmap commit2todo = OIDMAP_INIT;
5118 struct string_entry *entry;
5119 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5120 shown = OIDSET_INIT;
5121 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5123 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5124 const char *cmd_pick = abbr ? "p" : "pick",
5125 *cmd_label = abbr ? "l" : "label",
5126 *cmd_reset = abbr ? "t" : "reset",
5127 *cmd_merge = abbr ? "m" : "merge";
5129 oidmap_init(&commit2todo, 0);
5130 oidmap_init(&state.commit2label, 0);
5131 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5132 strbuf_init(&state.buf, 32);
5134 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5135 struct labels_entry *onto_label_entry;
5136 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5137 FLEX_ALLOC_STR(entry, string, "onto");
5138 oidcpy(&entry->entry.oid, oid);
5139 oidmap_put(&state.commit2label, entry);
5141 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5142 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5143 hashmap_add(&state.labels, &onto_label_entry->entry);
5147 * First phase:
5148 * - get onelines for all commits
5149 * - gather all branch tips (i.e. 2nd or later parents of merges)
5150 * - label all branch tips
5152 while ((commit = get_revision(revs))) {
5153 struct commit_list *to_merge;
5154 const char *p1, *p2;
5155 struct object_id *oid;
5156 int is_empty;
5158 tail = &commit_list_insert(commit, tail)->next;
5159 oidset_insert(&interesting, &commit->object.oid);
5161 is_empty = is_original_commit_empty(commit);
5162 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5163 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5164 warning(_("skipped previously applied commit %s"),
5165 short_commit_name(commit));
5166 skipped_commit = 1;
5167 continue;
5169 if (is_empty && !keep_empty)
5170 continue;
5172 strbuf_reset(&oneline);
5173 pretty_print_commit(pp, commit, &oneline);
5175 to_merge = commit->parents ? commit->parents->next : NULL;
5176 if (!to_merge) {
5177 /* non-merge commit: easy case */
5178 strbuf_reset(&buf);
5179 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5180 oid_to_hex(&commit->object.oid),
5181 oneline.buf);
5182 if (is_empty)
5183 strbuf_addf(&buf, " %c empty",
5184 comment_line_char);
5186 FLEX_ALLOC_STR(entry, string, buf.buf);
5187 oidcpy(&entry->entry.oid, &commit->object.oid);
5188 oidmap_put(&commit2todo, entry);
5190 continue;
5193 /* Create a label */
5194 strbuf_reset(&label);
5195 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5196 (p1 = strchr(p1, '\'')) &&
5197 (p2 = strchr(++p1, '\'')))
5198 strbuf_add(&label, p1, p2 - p1);
5199 else if (skip_prefix(oneline.buf, "Merge pull request ",
5200 &p1) &&
5201 (p1 = strstr(p1, " from ")))
5202 strbuf_addstr(&label, p1 + strlen(" from "));
5203 else
5204 strbuf_addbuf(&label, &oneline);
5206 strbuf_reset(&buf);
5207 strbuf_addf(&buf, "%s -C %s",
5208 cmd_merge, oid_to_hex(&commit->object.oid));
5210 /* label the tips of merged branches */
5211 for (; to_merge; to_merge = to_merge->next) {
5212 oid = &to_merge->item->object.oid;
5213 strbuf_addch(&buf, ' ');
5215 if (!oidset_contains(&interesting, oid)) {
5216 strbuf_addstr(&buf, label_oid(oid, NULL,
5217 &state));
5218 continue;
5221 tips_tail = &commit_list_insert(to_merge->item,
5222 tips_tail)->next;
5224 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5226 strbuf_addf(&buf, " # %s", oneline.buf);
5228 FLEX_ALLOC_STR(entry, string, buf.buf);
5229 oidcpy(&entry->entry.oid, &commit->object.oid);
5230 oidmap_put(&commit2todo, entry);
5232 if (skipped_commit)
5233 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5234 _("use --reapply-cherry-picks to include skipped commits"));
5237 * Second phase:
5238 * - label branch points
5239 * - add HEAD to the branch tips
5241 for (iter = commits; iter; iter = iter->next) {
5242 struct commit_list *parent = iter->item->parents;
5243 for (; parent; parent = parent->next) {
5244 struct object_id *oid = &parent->item->object.oid;
5245 if (!oidset_contains(&interesting, oid))
5246 continue;
5247 if (oidset_insert(&child_seen, oid))
5248 label_oid(oid, "branch-point", &state);
5251 /* Add HEAD as implicit "tip of branch" */
5252 if (!iter->next)
5253 tips_tail = &commit_list_insert(iter->item,
5254 tips_tail)->next;
5258 * Third phase: output the todo list. This is a bit tricky, as we
5259 * want to avoid jumping back and forth between revisions. To
5260 * accomplish that goal, we walk backwards from the branch tips,
5261 * gathering commits not yet shown, reversing the list on the fly,
5262 * then outputting that list (labeling revisions as needed).
5264 strbuf_addf(out, "%s onto\n", cmd_label);
5265 for (iter = tips; iter; iter = iter->next) {
5266 struct commit_list *list = NULL, *iter2;
5268 commit = iter->item;
5269 if (oidset_contains(&shown, &commit->object.oid))
5270 continue;
5271 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5273 if (entry)
5274 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5275 else
5276 strbuf_addch(out, '\n');
5278 while (oidset_contains(&interesting, &commit->object.oid) &&
5279 !oidset_contains(&shown, &commit->object.oid)) {
5280 commit_list_insert(commit, &list);
5281 if (!commit->parents) {
5282 commit = NULL;
5283 break;
5285 commit = commit->parents->item;
5288 if (!commit)
5289 strbuf_addf(out, "%s %s\n", cmd_reset,
5290 rebase_cousins || root_with_onto ?
5291 "onto" : "[new root]");
5292 else {
5293 const char *to = NULL;
5295 entry = oidmap_get(&state.commit2label,
5296 &commit->object.oid);
5297 if (entry)
5298 to = entry->string;
5299 else if (!rebase_cousins)
5300 to = label_oid(&commit->object.oid, NULL,
5301 &state);
5303 if (!to || !strcmp(to, "onto"))
5304 strbuf_addf(out, "%s onto\n", cmd_reset);
5305 else {
5306 strbuf_reset(&oneline);
5307 pretty_print_commit(pp, commit, &oneline);
5308 strbuf_addf(out, "%s %s # %s\n",
5309 cmd_reset, to, oneline.buf);
5313 for (iter2 = list; iter2; iter2 = iter2->next) {
5314 struct object_id *oid = &iter2->item->object.oid;
5315 entry = oidmap_get(&commit2todo, oid);
5316 /* only show if not already upstream */
5317 if (entry)
5318 strbuf_addf(out, "%s\n", entry->string);
5319 entry = oidmap_get(&state.commit2label, oid);
5320 if (entry)
5321 strbuf_addf(out, "%s %s\n",
5322 cmd_label, entry->string);
5323 oidset_insert(&shown, oid);
5326 free_commit_list(list);
5329 free_commit_list(commits);
5330 free_commit_list(tips);
5332 strbuf_release(&label);
5333 strbuf_release(&oneline);
5334 strbuf_release(&buf);
5336 oidmap_free(&commit2todo, 1);
5337 oidmap_free(&state.commit2label, 1);
5338 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5339 strbuf_release(&state.buf);
5341 return 0;
5344 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5345 const char **argv, unsigned flags)
5347 char *format = NULL;
5348 struct pretty_print_context pp = {0};
5349 struct rev_info revs;
5350 struct commit *commit;
5351 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5352 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5353 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5354 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5355 int skipped_commit = 0;
5356 int ret = 0;
5358 repo_init_revisions(r, &revs, NULL);
5359 revs.verbose_header = 1;
5360 if (!rebase_merges)
5361 revs.max_parents = 1;
5362 revs.cherry_mark = !reapply_cherry_picks;
5363 revs.limited = 1;
5364 revs.reverse = 1;
5365 revs.right_only = 1;
5366 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5367 revs.topo_order = 1;
5369 revs.pretty_given = 1;
5370 git_config_get_string("rebase.instructionFormat", &format);
5371 if (!format || !*format) {
5372 free(format);
5373 format = xstrdup("%s");
5375 get_commit_format(format, &revs);
5376 free(format);
5377 pp.fmt = revs.commit_format;
5378 pp.output_encoding = get_log_output_encoding();
5380 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5381 ret = error(_("make_script: unhandled options"));
5382 goto cleanup;
5385 if (prepare_revision_walk(&revs) < 0) {
5386 ret = error(_("make_script: error preparing revisions"));
5387 goto cleanup;
5390 if (rebase_merges) {
5391 ret = make_script_with_merges(&pp, &revs, out, flags);
5392 goto cleanup;
5395 while ((commit = get_revision(&revs))) {
5396 int is_empty = is_original_commit_empty(commit);
5398 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5399 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5400 warning(_("skipped previously applied commit %s"),
5401 short_commit_name(commit));
5402 skipped_commit = 1;
5403 continue;
5405 if (is_empty && !keep_empty)
5406 continue;
5407 strbuf_addf(out, "%s %s ", insn,
5408 oid_to_hex(&commit->object.oid));
5409 pretty_print_commit(&pp, commit, out);
5410 if (is_empty)
5411 strbuf_addf(out, " %c empty", comment_line_char);
5412 strbuf_addch(out, '\n');
5414 if (skipped_commit)
5415 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5416 _("use --reapply-cherry-picks to include skipped commits"));
5417 cleanup:
5418 release_revisions(&revs);
5419 return ret;
5423 * Add commands after pick and (series of) squash/fixup commands
5424 * in the todo list.
5426 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5427 struct string_list *commands)
5429 struct strbuf *buf = &todo_list->buf;
5430 size_t base_offset = buf->len;
5431 int i, insert, nr = 0, alloc = 0;
5432 struct todo_item *items = NULL, *base_items = NULL;
5434 CALLOC_ARRAY(base_items, commands->nr);
5435 for (i = 0; i < commands->nr; i++) {
5436 size_t command_len = strlen(commands->items[i].string);
5438 strbuf_addstr(buf, commands->items[i].string);
5439 strbuf_addch(buf, '\n');
5441 base_items[i].command = TODO_EXEC;
5442 base_items[i].offset_in_buf = base_offset;
5443 base_items[i].arg_offset = base_offset + strlen("exec ");
5444 base_items[i].arg_len = command_len - strlen("exec ");
5446 base_offset += command_len + 1;
5450 * Insert <commands> after every pick. Here, fixup/squash chains
5451 * are considered part of the pick, so we insert the commands *after*
5452 * those chains if there are any.
5454 * As we insert the exec commands immediately after rearranging
5455 * any fixups and before the user edits the list, a fixup chain
5456 * can never contain comments (any comments are empty picks that
5457 * have been commented out because the user did not specify
5458 * --keep-empty). So, it is safe to insert an exec command
5459 * without looking at the command following a comment.
5461 insert = 0;
5462 for (i = 0; i < todo_list->nr; i++) {
5463 enum todo_command command = todo_list->items[i].command;
5464 if (insert && !is_fixup(command)) {
5465 ALLOC_GROW(items, nr + commands->nr, alloc);
5466 COPY_ARRAY(items + nr, base_items, commands->nr);
5467 nr += commands->nr;
5469 insert = 0;
5472 ALLOC_GROW(items, nr + 1, alloc);
5473 items[nr++] = todo_list->items[i];
5475 if (command == TODO_PICK || command == TODO_MERGE)
5476 insert = 1;
5479 /* insert or append final <commands> */
5480 if (insert) {
5481 ALLOC_GROW(items, nr + commands->nr, alloc);
5482 COPY_ARRAY(items + nr, base_items, commands->nr);
5483 nr += commands->nr;
5486 free(base_items);
5487 FREE_AND_NULL(todo_list->items);
5488 todo_list->items = items;
5489 todo_list->nr = nr;
5490 todo_list->alloc = alloc;
5493 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5494 struct strbuf *buf, int num, unsigned flags)
5496 struct todo_item *item;
5497 int i, max = todo_list->nr;
5499 if (num > 0 && num < max)
5500 max = num;
5502 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5503 char cmd;
5505 /* if the item is not a command write it and continue */
5506 if (item->command >= TODO_COMMENT) {
5507 strbuf_addf(buf, "%.*s\n", item->arg_len,
5508 todo_item_get_arg(todo_list, item));
5509 continue;
5512 /* add command to the buffer */
5513 cmd = command_to_char(item->command);
5514 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5515 strbuf_addch(buf, cmd);
5516 else
5517 strbuf_addstr(buf, command_to_string(item->command));
5519 /* add commit id */
5520 if (item->commit) {
5521 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5522 short_commit_name(item->commit) :
5523 oid_to_hex(&item->commit->object.oid);
5525 if (item->command == TODO_FIXUP) {
5526 if (item->flags & TODO_EDIT_FIXUP_MSG)
5527 strbuf_addstr(buf, " -c");
5528 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5529 strbuf_addstr(buf, " -C");
5533 if (item->command == TODO_MERGE) {
5534 if (item->flags & TODO_EDIT_MERGE_MSG)
5535 strbuf_addstr(buf, " -c");
5536 else
5537 strbuf_addstr(buf, " -C");
5540 strbuf_addf(buf, " %s", oid);
5543 /* add all the rest */
5544 if (!item->arg_len)
5545 strbuf_addch(buf, '\n');
5546 else
5547 strbuf_addf(buf, " %.*s\n", item->arg_len,
5548 todo_item_get_arg(todo_list, item));
5552 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5553 const char *file, const char *shortrevisions,
5554 const char *shortonto, int num, unsigned flags)
5556 int res;
5557 struct strbuf buf = STRBUF_INIT;
5559 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5560 if (flags & TODO_LIST_APPEND_TODO_HELP)
5561 append_todo_help(count_commands(todo_list),
5562 shortrevisions, shortonto, &buf);
5564 res = write_message(buf.buf, buf.len, file, 0);
5565 strbuf_release(&buf);
5567 return res;
5570 /* skip picking commits whose parents are unchanged */
5571 static int skip_unnecessary_picks(struct repository *r,
5572 struct todo_list *todo_list,
5573 struct object_id *base_oid)
5575 struct object_id *parent_oid;
5576 int i;
5578 for (i = 0; i < todo_list->nr; i++) {
5579 struct todo_item *item = todo_list->items + i;
5581 if (item->command >= TODO_NOOP)
5582 continue;
5583 if (item->command != TODO_PICK)
5584 break;
5585 if (parse_commit(item->commit)) {
5586 return error(_("could not parse commit '%s'"),
5587 oid_to_hex(&item->commit->object.oid));
5589 if (!item->commit->parents)
5590 break; /* root commit */
5591 if (item->commit->parents->next)
5592 break; /* merge commit */
5593 parent_oid = &item->commit->parents->item->object.oid;
5594 if (!oideq(parent_oid, base_oid))
5595 break;
5596 oidcpy(base_oid, &item->commit->object.oid);
5598 if (i > 0) {
5599 const char *done_path = rebase_path_done();
5601 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5602 error_errno(_("could not write to '%s'"), done_path);
5603 return -1;
5606 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5607 todo_list->nr -= i;
5608 todo_list->current = 0;
5609 todo_list->done_nr += i;
5611 if (is_fixup(peek_command(todo_list, 0)))
5612 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5615 return 0;
5618 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5619 const char *shortrevisions, const char *onto_name,
5620 struct commit *onto, const struct object_id *orig_head,
5621 struct string_list *commands, unsigned autosquash,
5622 struct todo_list *todo_list)
5624 char shortonto[GIT_MAX_HEXSZ + 1];
5625 const char *todo_file = rebase_path_todo();
5626 struct todo_list new_todo = TODO_LIST_INIT;
5627 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5628 struct object_id oid = onto->object.oid;
5629 int res;
5631 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5633 if (buf->len == 0) {
5634 struct todo_item *item = append_new_todo(todo_list);
5635 item->command = TODO_NOOP;
5636 item->commit = NULL;
5637 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5640 if (autosquash && todo_list_rearrange_squash(todo_list))
5641 return -1;
5643 if (commands->nr)
5644 todo_list_add_exec_commands(todo_list, commands);
5646 if (count_commands(todo_list) == 0) {
5647 apply_autostash(rebase_path_autostash());
5648 sequencer_remove_state(opts);
5650 return error(_("nothing to do"));
5653 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5654 shortonto, flags);
5655 if (res == -1)
5656 return -1;
5657 else if (res == -2) {
5658 apply_autostash(rebase_path_autostash());
5659 sequencer_remove_state(opts);
5661 return -1;
5662 } else if (res == -3) {
5663 apply_autostash(rebase_path_autostash());
5664 sequencer_remove_state(opts);
5665 todo_list_release(&new_todo);
5667 return error(_("nothing to do"));
5668 } else if (res == -4) {
5669 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5670 todo_list_release(&new_todo);
5672 return -1;
5675 /* Expand the commit IDs */
5676 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5677 strbuf_swap(&new_todo.buf, &buf2);
5678 strbuf_release(&buf2);
5679 new_todo.total_nr -= new_todo.nr;
5680 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5681 BUG("invalid todo list after expanding IDs:\n%s",
5682 new_todo.buf.buf);
5684 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5685 todo_list_release(&new_todo);
5686 return error(_("could not skip unnecessary pick commands"));
5689 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5690 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5691 todo_list_release(&new_todo);
5692 return error_errno(_("could not write '%s'"), todo_file);
5695 res = -1;
5697 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5698 goto cleanup;
5700 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5701 goto cleanup;
5703 todo_list_write_total_nr(&new_todo);
5704 res = pick_commits(r, &new_todo, opts);
5706 cleanup:
5707 todo_list_release(&new_todo);
5709 return res;
5712 struct subject2item_entry {
5713 struct hashmap_entry entry;
5714 int i;
5715 char subject[FLEX_ARRAY];
5718 static int subject2item_cmp(const void *fndata,
5719 const struct hashmap_entry *eptr,
5720 const struct hashmap_entry *entry_or_key,
5721 const void *key)
5723 const struct subject2item_entry *a, *b;
5725 a = container_of(eptr, const struct subject2item_entry, entry);
5726 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5728 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5731 define_commit_slab(commit_todo_item, struct todo_item *);
5733 static int skip_fixupish(const char *subject, const char **p) {
5734 return skip_prefix(subject, "fixup! ", p) ||
5735 skip_prefix(subject, "amend! ", p) ||
5736 skip_prefix(subject, "squash! ", p);
5740 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5741 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5742 * after the former, and change "pick" to "fixup"/"squash".
5744 * Note that if the config has specified a custom instruction format, each log
5745 * message will have to be retrieved from the commit (as the oneline in the
5746 * script cannot be trusted) in order to normalize the autosquash arrangement.
5748 int todo_list_rearrange_squash(struct todo_list *todo_list)
5750 struct hashmap subject2item;
5751 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5752 char **subjects;
5753 struct commit_todo_item commit_todo;
5754 struct todo_item *items = NULL;
5756 init_commit_todo_item(&commit_todo);
5758 * The hashmap maps onelines to the respective todo list index.
5760 * If any items need to be rearranged, the next[i] value will indicate
5761 * which item was moved directly after the i'th.
5763 * In that case, last[i] will indicate the index of the latest item to
5764 * be moved to appear after the i'th.
5766 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5767 ALLOC_ARRAY(next, todo_list->nr);
5768 ALLOC_ARRAY(tail, todo_list->nr);
5769 ALLOC_ARRAY(subjects, todo_list->nr);
5770 for (i = 0; i < todo_list->nr; i++) {
5771 struct strbuf buf = STRBUF_INIT;
5772 struct todo_item *item = todo_list->items + i;
5773 const char *commit_buffer, *subject, *p;
5774 size_t subject_len;
5775 int i2 = -1;
5776 struct subject2item_entry *entry;
5778 next[i] = tail[i] = -1;
5779 if (!item->commit || item->command == TODO_DROP) {
5780 subjects[i] = NULL;
5781 continue;
5784 if (is_fixup(item->command)) {
5785 clear_commit_todo_item(&commit_todo);
5786 return error(_("the script was already rearranged."));
5789 *commit_todo_item_at(&commit_todo, item->commit) = item;
5791 parse_commit(item->commit);
5792 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5793 find_commit_subject(commit_buffer, &subject);
5794 format_subject(&buf, subject, " ");
5795 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5796 unuse_commit_buffer(item->commit, commit_buffer);
5797 if (skip_fixupish(subject, &p)) {
5798 struct commit *commit2;
5800 for (;;) {
5801 while (isspace(*p))
5802 p++;
5803 if (!skip_fixupish(p, &p))
5804 break;
5807 entry = hashmap_get_entry_from_hash(&subject2item,
5808 strhash(p), p,
5809 struct subject2item_entry,
5810 entry);
5811 if (entry)
5812 /* found by title */
5813 i2 = entry->i;
5814 else if (!strchr(p, ' ') &&
5815 (commit2 =
5816 lookup_commit_reference_by_name(p)) &&
5817 *commit_todo_item_at(&commit_todo, commit2))
5818 /* found by commit name */
5819 i2 = *commit_todo_item_at(&commit_todo, commit2)
5820 - todo_list->items;
5821 else {
5822 /* copy can be a prefix of the commit subject */
5823 for (i2 = 0; i2 < i; i2++)
5824 if (subjects[i2] &&
5825 starts_with(subjects[i2], p))
5826 break;
5827 if (i2 == i)
5828 i2 = -1;
5831 if (i2 >= 0) {
5832 rearranged = 1;
5833 if (starts_with(subject, "fixup!")) {
5834 todo_list->items[i].command = TODO_FIXUP;
5835 } else if (starts_with(subject, "amend!")) {
5836 todo_list->items[i].command = TODO_FIXUP;
5837 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5838 } else {
5839 todo_list->items[i].command = TODO_SQUASH;
5841 if (tail[i2] < 0) {
5842 next[i] = next[i2];
5843 next[i2] = i;
5844 } else {
5845 next[i] = next[tail[i2]];
5846 next[tail[i2]] = i;
5848 tail[i2] = i;
5849 } else if (!hashmap_get_from_hash(&subject2item,
5850 strhash(subject), subject)) {
5851 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5852 entry->i = i;
5853 hashmap_entry_init(&entry->entry,
5854 strhash(entry->subject));
5855 hashmap_put(&subject2item, &entry->entry);
5859 if (rearranged) {
5860 for (i = 0; i < todo_list->nr; i++) {
5861 enum todo_command command = todo_list->items[i].command;
5862 int cur = i;
5865 * Initially, all commands are 'pick's. If it is a
5866 * fixup or a squash now, we have rearranged it.
5868 if (is_fixup(command))
5869 continue;
5871 while (cur >= 0) {
5872 ALLOC_GROW(items, nr + 1, alloc);
5873 items[nr++] = todo_list->items[cur];
5874 cur = next[cur];
5878 FREE_AND_NULL(todo_list->items);
5879 todo_list->items = items;
5880 todo_list->nr = nr;
5881 todo_list->alloc = alloc;
5884 free(next);
5885 free(tail);
5886 for (i = 0; i < todo_list->nr; i++)
5887 free(subjects[i]);
5888 free(subjects);
5889 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5891 clear_commit_todo_item(&commit_todo);
5893 return 0;
5896 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5898 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5899 struct object_id cherry_pick_head, rebase_head;
5901 if (file_exists(git_path_seq_dir()))
5902 *whence = FROM_CHERRY_PICK_MULTI;
5903 if (file_exists(rebase_path()) &&
5904 !get_oid("REBASE_HEAD", &rebase_head) &&
5905 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5906 oideq(&rebase_head, &cherry_pick_head))
5907 *whence = FROM_REBASE_PICK;
5908 else
5909 *whence = FROM_CHERRY_PICK_SINGLE;
5911 return 1;
5914 return 0;