Merge branch 'ds/mergies-with-sparse-index'
[alt-git.git] / sequencer.c
blob614d56f5e211eea24a165bc94fb9f00c72c9adcb
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 "exec-cmd.h"
12 #include "utf8.h"
13 #include "cache-tree.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "rerere.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
19 #include "refs.h"
20 #include "strvec.h"
21 #include "quote.h"
22 #include "trailer.h"
23 #include "log-tree.h"
24 #include "wt-status.h"
25 #include "hashmap.h"
26 #include "notes-utils.h"
27 #include "sigchain.h"
28 #include "unpack-trees.h"
29 #include "worktree.h"
30 #include "oidmap.h"
31 #include "oidset.h"
32 #include "commit-slab.h"
33 #include "alias.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
36 #include "reset.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
67 * actions.
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
72 * for the prompt).
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 * being rebased.
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
151 * command-line.
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
169 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
171 static int git_sequencer_config(const char *k, const char *v, void *cb)
173 struct replay_opts *opts = cb;
174 int status;
176 if (!strcmp(k, "commit.cleanup")) {
177 const char *s;
179 status = git_config_string(&s, k, v);
180 if (status)
181 return status;
183 if (!strcmp(s, "verbatim")) {
184 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
185 opts->explicit_cleanup = 1;
186 } else if (!strcmp(s, "whitespace")) {
187 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
188 opts->explicit_cleanup = 1;
189 } else if (!strcmp(s, "strip")) {
190 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
191 opts->explicit_cleanup = 1;
192 } else if (!strcmp(s, "scissors")) {
193 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
194 opts->explicit_cleanup = 1;
195 } else {
196 warning(_("invalid commit message cleanup mode '%s'"),
200 free((char *)s);
201 return status;
204 if (!strcmp(k, "commit.gpgsign")) {
205 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
206 return 0;
209 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
210 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
211 if (ret == 0) {
213 * pull.twohead is allowed to be multi-valued; we only
214 * care about the first value.
216 char *tmp = strchr(opts->default_strategy, ' ');
217 if (tmp)
218 *tmp = '\0';
220 return ret;
223 status = git_gpg_config(k, v, NULL);
224 if (status)
225 return status;
227 return git_diff_basic_config(k, v, NULL);
230 void sequencer_init_config(struct replay_opts *opts)
232 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
233 git_config(git_sequencer_config, opts);
236 static inline int is_rebase_i(const struct replay_opts *opts)
238 return opts->action == REPLAY_INTERACTIVE_REBASE;
241 static const char *get_dir(const struct replay_opts *opts)
243 if (is_rebase_i(opts))
244 return rebase_path();
245 return git_path_seq_dir();
248 static const char *get_todo_path(const struct replay_opts *opts)
250 if (is_rebase_i(opts))
251 return rebase_path_todo();
252 return git_path_todo_file();
256 * Returns 0 for non-conforming footer
257 * Returns 1 for conforming footer
258 * Returns 2 when sob exists within conforming footer
259 * Returns 3 when sob exists within conforming footer as last entry
261 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
262 size_t ignore_footer)
264 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
265 struct trailer_info info;
266 size_t i;
267 int found_sob = 0, found_sob_last = 0;
268 char saved_char;
270 opts.no_divider = 1;
272 if (ignore_footer) {
273 saved_char = sb->buf[sb->len - ignore_footer];
274 sb->buf[sb->len - ignore_footer] = '\0';
277 trailer_info_get(&info, sb->buf, &opts);
279 if (ignore_footer)
280 sb->buf[sb->len - ignore_footer] = saved_char;
282 if (info.trailer_start == info.trailer_end)
283 return 0;
285 for (i = 0; i < info.trailer_nr; i++)
286 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
287 found_sob = 1;
288 if (i == info.trailer_nr - 1)
289 found_sob_last = 1;
292 trailer_info_release(&info);
294 if (found_sob_last)
295 return 3;
296 if (found_sob)
297 return 2;
298 return 1;
301 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
303 static struct strbuf buf = STRBUF_INIT;
305 strbuf_reset(&buf);
306 if (opts->gpg_sign)
307 sq_quotef(&buf, "-S%s", opts->gpg_sign);
308 return buf.buf;
311 int sequencer_remove_state(struct replay_opts *opts)
313 struct strbuf buf = STRBUF_INIT;
314 int i, ret = 0;
316 if (is_rebase_i(opts) &&
317 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
318 char *p = buf.buf;
319 while (*p) {
320 char *eol = strchr(p, '\n');
321 if (eol)
322 *eol = '\0';
323 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
324 warning(_("could not delete '%s'"), p);
325 ret = -1;
327 if (!eol)
328 break;
329 p = eol + 1;
333 free(opts->gpg_sign);
334 free(opts->default_strategy);
335 free(opts->strategy);
336 for (i = 0; i < opts->xopts_nr; i++)
337 free(opts->xopts[i]);
338 free(opts->xopts);
339 strbuf_release(&opts->current_fixups);
341 strbuf_reset(&buf);
342 strbuf_addstr(&buf, get_dir(opts));
343 if (remove_dir_recursively(&buf, 0))
344 ret = error(_("could not remove '%s'"), buf.buf);
345 strbuf_release(&buf);
347 return ret;
350 static const char *action_name(const struct replay_opts *opts)
352 switch (opts->action) {
353 case REPLAY_REVERT:
354 return N_("revert");
355 case REPLAY_PICK:
356 return N_("cherry-pick");
357 case REPLAY_INTERACTIVE_REBASE:
358 return N_("rebase");
360 die(_("unknown action: %d"), opts->action);
363 struct commit_message {
364 char *parent_label;
365 char *label;
366 char *subject;
367 const char *message;
370 static const char *short_commit_name(struct commit *commit)
372 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
375 static int get_message(struct commit *commit, struct commit_message *out)
377 const char *abbrev, *subject;
378 int subject_len;
380 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
381 abbrev = short_commit_name(commit);
383 subject_len = find_commit_subject(out->message, &subject);
385 out->subject = xmemdupz(subject, subject_len);
386 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
387 out->parent_label = xstrfmt("parent of %s", out->label);
389 return 0;
392 static void free_message(struct commit *commit, struct commit_message *msg)
394 free(msg->parent_label);
395 free(msg->label);
396 free(msg->subject);
397 unuse_commit_buffer(commit, msg->message);
400 static void print_advice(struct repository *r, int show_hint,
401 struct replay_opts *opts)
403 char *msg = getenv("GIT_CHERRY_PICK_HELP");
405 if (msg) {
406 advise("%s\n", msg);
408 * A conflict has occurred but the porcelain
409 * (typically rebase --interactive) wants to take care
410 * of the commit itself so remove CHERRY_PICK_HEAD
412 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
413 NULL, 0);
414 return;
417 if (show_hint) {
418 if (opts->no_commit)
419 advise(_("after resolving the conflicts, mark the corrected paths\n"
420 "with 'git add <paths>' or 'git rm <paths>'"));
421 else if (opts->action == REPLAY_PICK)
422 advise(_("After resolving the conflicts, mark them with\n"
423 "\"git add/rm <pathspec>\", then run\n"
424 "\"git cherry-pick --continue\".\n"
425 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
426 "To abort and get back to the state before \"git cherry-pick\",\n"
427 "run \"git cherry-pick --abort\"."));
428 else if (opts->action == REPLAY_REVERT)
429 advise(_("After resolving the conflicts, mark them with\n"
430 "\"git add/rm <pathspec>\", then run\n"
431 "\"git revert --continue\".\n"
432 "You can instead skip this commit with \"git revert --skip\".\n"
433 "To abort and get back to the state before \"git revert\",\n"
434 "run \"git revert --abort\"."));
435 else
436 BUG("unexpected pick action in print_advice()");
440 static int write_message(const void *buf, size_t len, const char *filename,
441 int append_eol)
443 struct lock_file msg_file = LOCK_INIT;
445 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
446 if (msg_fd < 0)
447 return error_errno(_("could not lock '%s'"), filename);
448 if (write_in_full(msg_fd, buf, len) < 0) {
449 error_errno(_("could not write to '%s'"), filename);
450 rollback_lock_file(&msg_file);
451 return -1;
453 if (append_eol && write(msg_fd, "\n", 1) < 0) {
454 error_errno(_("could not write eol to '%s'"), filename);
455 rollback_lock_file(&msg_file);
456 return -1;
458 if (commit_lock_file(&msg_file) < 0)
459 return error(_("failed to finalize '%s'"), filename);
461 return 0;
464 int read_oneliner(struct strbuf *buf,
465 const char *path, unsigned flags)
467 int orig_len = buf->len;
469 if (strbuf_read_file(buf, path, 0) < 0) {
470 if ((flags & READ_ONELINER_WARN_MISSING) ||
471 (errno != ENOENT && errno != ENOTDIR))
472 warning_errno(_("could not read '%s'"), path);
473 return 0;
476 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
477 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
478 --buf->len;
479 buf->buf[buf->len] = '\0';
482 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
483 return 0;
485 return 1;
488 static struct tree *empty_tree(struct repository *r)
490 return lookup_tree(r, the_hash_algo->empty_tree);
493 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
495 if (repo_read_index_unmerged(repo))
496 return error_resolve_conflict(_(action_name(opts)));
498 error(_("your local changes would be overwritten by %s."),
499 _(action_name(opts)));
501 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
502 advise(_("commit your changes or stash them to proceed."));
503 return -1;
506 static void update_abort_safety_file(void)
508 struct object_id head;
510 /* Do nothing on a single-pick */
511 if (!file_exists(git_path_seq_dir()))
512 return;
514 if (!get_oid("HEAD", &head))
515 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
516 else
517 write_file(git_path_abort_safety_file(), "%s", "");
520 static int fast_forward_to(struct repository *r,
521 const struct object_id *to,
522 const struct object_id *from,
523 int unborn,
524 struct replay_opts *opts)
526 struct ref_transaction *transaction;
527 struct strbuf sb = STRBUF_INIT;
528 struct strbuf err = STRBUF_INIT;
530 repo_read_index(r);
531 if (checkout_fast_forward(r, from, to, 1))
532 return -1; /* the callee should have complained already */
534 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
536 transaction = ref_transaction_begin(&err);
537 if (!transaction ||
538 ref_transaction_update(transaction, "HEAD",
539 to, unborn && !is_rebase_i(opts) ?
540 null_oid() : from,
541 0, sb.buf, &err) ||
542 ref_transaction_commit(transaction, &err)) {
543 ref_transaction_free(transaction);
544 error("%s", err.buf);
545 strbuf_release(&sb);
546 strbuf_release(&err);
547 return -1;
550 strbuf_release(&sb);
551 strbuf_release(&err);
552 ref_transaction_free(transaction);
553 update_abort_safety_file();
554 return 0;
557 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
558 int use_editor)
560 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
561 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
562 COMMIT_MSG_CLEANUP_SPACE;
563 else if (!strcmp(cleanup_arg, "verbatim"))
564 return COMMIT_MSG_CLEANUP_NONE;
565 else if (!strcmp(cleanup_arg, "whitespace"))
566 return COMMIT_MSG_CLEANUP_SPACE;
567 else if (!strcmp(cleanup_arg, "strip"))
568 return COMMIT_MSG_CLEANUP_ALL;
569 else if (!strcmp(cleanup_arg, "scissors"))
570 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
571 COMMIT_MSG_CLEANUP_SPACE;
572 else
573 die(_("Invalid cleanup mode %s"), cleanup_arg);
577 * NB using int rather than enum cleanup_mode to stop clang's
578 * -Wtautological-constant-out-of-range-compare complaining that the comparison
579 * is always true.
581 static const char *describe_cleanup_mode(int cleanup_mode)
583 static const char *modes[] = { "whitespace",
584 "verbatim",
585 "scissors",
586 "strip" };
588 if (cleanup_mode < ARRAY_SIZE(modes))
589 return modes[cleanup_mode];
591 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
594 void append_conflicts_hint(struct index_state *istate,
595 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
597 int i;
599 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
600 strbuf_addch(msgbuf, '\n');
601 wt_status_append_cut_line(msgbuf);
602 strbuf_addch(msgbuf, comment_line_char);
605 strbuf_addch(msgbuf, '\n');
606 strbuf_commented_addf(msgbuf, "Conflicts:\n");
607 for (i = 0; i < istate->cache_nr;) {
608 const struct cache_entry *ce = istate->cache[i++];
609 if (ce_stage(ce)) {
610 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
611 while (i < istate->cache_nr &&
612 !strcmp(ce->name, istate->cache[i]->name))
613 i++;
618 static int do_recursive_merge(struct repository *r,
619 struct commit *base, struct commit *next,
620 const char *base_label, const char *next_label,
621 struct object_id *head, struct strbuf *msgbuf,
622 struct replay_opts *opts)
624 struct merge_options o;
625 struct merge_result result;
626 struct tree *next_tree, *base_tree, *head_tree;
627 int clean, show_output;
628 int i;
629 struct lock_file index_lock = LOCK_INIT;
631 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
632 return -1;
634 repo_read_index(r);
636 init_merge_options(&o, r);
637 o.ancestor = base ? base_label : "(empty tree)";
638 o.branch1 = "HEAD";
639 o.branch2 = next ? next_label : "(empty tree)";
640 if (is_rebase_i(opts))
641 o.buffer_output = 2;
642 o.show_rename_progress = 1;
644 head_tree = parse_tree_indirect(head);
645 next_tree = next ? get_commit_tree(next) : empty_tree(r);
646 base_tree = base ? get_commit_tree(base) : empty_tree(r);
648 for (i = 0; i < opts->xopts_nr; i++)
649 parse_merge_opt(&o, opts->xopts[i]);
651 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
652 memset(&result, 0, sizeof(result));
653 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
654 &result);
655 show_output = !is_rebase_i(opts) || !result.clean;
657 * TODO: merge_switch_to_result will update index/working tree;
658 * we only really want to do that if !result.clean || this is
659 * the final patch to be picked. But determining this is the
660 * final patch would take some work, and "head_tree" would need
661 * to be replace with the tree the index matched before we
662 * started doing any picks.
664 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
665 clean = result.clean;
666 } else {
667 ensure_full_index(r->index);
668 clean = merge_trees(&o, head_tree, next_tree, base_tree);
669 if (is_rebase_i(opts) && clean <= 0)
670 fputs(o.obuf.buf, stdout);
671 strbuf_release(&o.obuf);
673 if (clean < 0) {
674 rollback_lock_file(&index_lock);
675 return clean;
678 if (write_locked_index(r->index, &index_lock,
679 COMMIT_LOCK | SKIP_IF_UNCHANGED))
681 * TRANSLATORS: %s will be "revert", "cherry-pick" or
682 * "rebase".
684 return error(_("%s: Unable to write new index file"),
685 _(action_name(opts)));
687 if (!clean)
688 append_conflicts_hint(r->index, msgbuf,
689 opts->default_msg_cleanup);
691 return !clean;
694 static struct object_id *get_cache_tree_oid(struct index_state *istate)
696 if (!cache_tree_fully_valid(istate->cache_tree))
697 if (cache_tree_update(istate, 0)) {
698 error(_("unable to update cache tree"));
699 return NULL;
702 return &istate->cache_tree->oid;
705 static int is_index_unchanged(struct repository *r)
707 struct object_id head_oid, *cache_tree_oid;
708 struct commit *head_commit;
709 struct index_state *istate = r->index;
711 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
712 return error(_("could not resolve HEAD commit"));
714 head_commit = lookup_commit(r, &head_oid);
717 * If head_commit is NULL, check_commit, called from
718 * lookup_commit, would have indicated that head_commit is not
719 * a commit object already. parse_commit() will return failure
720 * without further complaints in such a case. Otherwise, if
721 * the commit is invalid, parse_commit() will complain. So
722 * there is nothing for us to say here. Just return failure.
724 if (parse_commit(head_commit))
725 return -1;
727 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
728 return -1;
730 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
733 static int write_author_script(const char *message)
735 struct strbuf buf = STRBUF_INIT;
736 const char *eol;
737 int res;
739 for (;;)
740 if (!*message || starts_with(message, "\n")) {
741 missing_author:
742 /* Missing 'author' line? */
743 unlink(rebase_path_author_script());
744 return 0;
745 } else if (skip_prefix(message, "author ", &message))
746 break;
747 else if ((eol = strchr(message, '\n')))
748 message = eol + 1;
749 else
750 goto missing_author;
752 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
753 while (*message && *message != '\n' && *message != '\r')
754 if (skip_prefix(message, " <", &message))
755 break;
756 else if (*message != '\'')
757 strbuf_addch(&buf, *(message++));
758 else
759 strbuf_addf(&buf, "'\\%c'", *(message++));
760 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
761 while (*message && *message != '\n' && *message != '\r')
762 if (skip_prefix(message, "> ", &message))
763 break;
764 else if (*message != '\'')
765 strbuf_addch(&buf, *(message++));
766 else
767 strbuf_addf(&buf, "'\\%c'", *(message++));
768 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
769 while (*message && *message != '\n' && *message != '\r')
770 if (*message != '\'')
771 strbuf_addch(&buf, *(message++));
772 else
773 strbuf_addf(&buf, "'\\%c'", *(message++));
774 strbuf_addch(&buf, '\'');
775 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
776 strbuf_release(&buf);
777 return res;
781 * Take a series of KEY='VALUE' lines where VALUE part is
782 * sq-quoted, and append <KEY, VALUE> at the end of the string list
784 static int parse_key_value_squoted(char *buf, struct string_list *list)
786 while (*buf) {
787 struct string_list_item *item;
788 char *np;
789 char *cp = strchr(buf, '=');
790 if (!cp) {
791 np = strchrnul(buf, '\n');
792 return error(_("no key present in '%.*s'"),
793 (int) (np - buf), buf);
795 np = strchrnul(cp, '\n');
796 *cp++ = '\0';
797 item = string_list_append(list, buf);
799 buf = np + (*np == '\n');
800 *np = '\0';
801 cp = sq_dequote(cp);
802 if (!cp)
803 return error(_("unable to dequote value of '%s'"),
804 item->string);
805 item->util = xstrdup(cp);
807 return 0;
811 * Reads and parses the state directory's "author-script" file, and sets name,
812 * email and date accordingly.
813 * Returns 0 on success, -1 if the file could not be parsed.
815 * The author script is of the format:
817 * GIT_AUTHOR_NAME='$author_name'
818 * GIT_AUTHOR_EMAIL='$author_email'
819 * GIT_AUTHOR_DATE='$author_date'
821 * where $author_name, $author_email and $author_date are quoted. We are strict
822 * with our parsing, as the file was meant to be eval'd in the now-removed
823 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
824 * from what this function expects, it is better to bail out than to do
825 * something that the user does not expect.
827 int read_author_script(const char *path, char **name, char **email, char **date,
828 int allow_missing)
830 struct strbuf buf = STRBUF_INIT;
831 struct string_list kv = STRING_LIST_INIT_DUP;
832 int retval = -1; /* assume failure */
833 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
835 if (strbuf_read_file(&buf, path, 256) <= 0) {
836 strbuf_release(&buf);
837 if (errno == ENOENT && allow_missing)
838 return 0;
839 else
840 return error_errno(_("could not open '%s' for reading"),
841 path);
844 if (parse_key_value_squoted(buf.buf, &kv))
845 goto finish;
847 for (i = 0; i < kv.nr; i++) {
848 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
849 if (name_i != -2)
850 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
851 else
852 name_i = i;
853 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
854 if (email_i != -2)
855 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
856 else
857 email_i = i;
858 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
859 if (date_i != -2)
860 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
861 else
862 date_i = i;
863 } else {
864 err = error(_("unknown variable '%s'"),
865 kv.items[i].string);
868 if (name_i == -2)
869 error(_("missing 'GIT_AUTHOR_NAME'"));
870 if (email_i == -2)
871 error(_("missing 'GIT_AUTHOR_EMAIL'"));
872 if (date_i == -2)
873 error(_("missing 'GIT_AUTHOR_DATE'"));
874 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
875 goto finish;
876 *name = kv.items[name_i].util;
877 *email = kv.items[email_i].util;
878 *date = kv.items[date_i].util;
879 retval = 0;
880 finish:
881 string_list_clear(&kv, !!retval);
882 strbuf_release(&buf);
883 return retval;
887 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
888 * file with shell quoting into struct strvec. Returns -1 on
889 * error, 0 otherwise.
891 static int read_env_script(struct strvec *env)
893 char *name, *email, *date;
895 if (read_author_script(rebase_path_author_script(),
896 &name, &email, &date, 0))
897 return -1;
899 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
900 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
901 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
902 free(name);
903 free(email);
904 free(date);
906 return 0;
909 static char *get_author(const char *message)
911 size_t len;
912 const char *a;
914 a = find_commit_header(message, "author", &len);
915 if (a)
916 return xmemdupz(a, len);
918 return NULL;
921 static const char *author_date_from_env_array(const struct strvec *env)
923 int i;
924 const char *date;
926 for (i = 0; i < env->nr; i++)
927 if (skip_prefix(env->v[i],
928 "GIT_AUTHOR_DATE=", &date))
929 return date;
931 * If GIT_AUTHOR_DATE is missing we should have already errored out when
932 * reading the script
934 BUG("GIT_AUTHOR_DATE missing from author script");
937 static const char staged_changes_advice[] =
938 N_("you have staged changes in your working tree\n"
939 "If these changes are meant to be squashed into the previous commit, run:\n"
940 "\n"
941 " git commit --amend %s\n"
942 "\n"
943 "If they are meant to go into a new commit, run:\n"
944 "\n"
945 " git commit %s\n"
946 "\n"
947 "In both cases, once you're done, continue with:\n"
948 "\n"
949 " git rebase --continue\n");
951 #define ALLOW_EMPTY (1<<0)
952 #define EDIT_MSG (1<<1)
953 #define AMEND_MSG (1<<2)
954 #define CLEANUP_MSG (1<<3)
955 #define VERIFY_MSG (1<<4)
956 #define CREATE_ROOT_COMMIT (1<<5)
957 #define VERBATIM_MSG (1<<6)
959 static int run_command_silent_on_success(struct child_process *cmd)
961 struct strbuf buf = STRBUF_INIT;
962 int rc;
964 cmd->stdout_to_stderr = 1;
965 rc = pipe_command(cmd,
966 NULL, 0,
967 NULL, 0,
968 &buf, 0);
970 if (rc)
971 fputs(buf.buf, stderr);
972 strbuf_release(&buf);
973 return rc;
977 * If we are cherry-pick, and if the merge did not result in
978 * hand-editing, we will hit this commit and inherit the original
979 * author date and name.
981 * If we are revert, or if our cherry-pick results in a hand merge,
982 * we had better say that the current user is responsible for that.
984 * An exception is when run_git_commit() is called during an
985 * interactive rebase: in that case, we will want to retain the
986 * author metadata.
988 static int run_git_commit(const char *defmsg,
989 struct replay_opts *opts,
990 unsigned int flags)
992 struct child_process cmd = CHILD_PROCESS_INIT;
994 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
995 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
997 cmd.git_cmd = 1;
999 if (is_rebase_i(opts) && !(!defmsg && (flags & AMEND_MSG)) &&
1000 read_env_script(&cmd.env_array)) {
1001 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1003 return error(_(staged_changes_advice),
1004 gpg_opt, gpg_opt);
1007 if (opts->committer_date_is_author_date)
1008 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1009 opts->ignore_date ?
1010 "" :
1011 author_date_from_env_array(&cmd.env_array));
1012 if (opts->ignore_date)
1013 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1015 strvec_push(&cmd.args, "commit");
1017 if (!(flags & VERIFY_MSG))
1018 strvec_push(&cmd.args, "-n");
1019 if ((flags & AMEND_MSG))
1020 strvec_push(&cmd.args, "--amend");
1021 if (opts->gpg_sign)
1022 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1023 else
1024 strvec_push(&cmd.args, "--no-gpg-sign");
1025 if (defmsg)
1026 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1027 else if (!(flags & EDIT_MSG))
1028 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1029 if ((flags & CLEANUP_MSG))
1030 strvec_push(&cmd.args, "--cleanup=strip");
1031 if ((flags & VERBATIM_MSG))
1032 strvec_push(&cmd.args, "--cleanup=verbatim");
1033 if ((flags & EDIT_MSG))
1034 strvec_push(&cmd.args, "-e");
1035 else if (!(flags & CLEANUP_MSG) &&
1036 !opts->signoff && !opts->record_origin &&
1037 !opts->explicit_cleanup)
1038 strvec_push(&cmd.args, "--cleanup=verbatim");
1040 if ((flags & ALLOW_EMPTY))
1041 strvec_push(&cmd.args, "--allow-empty");
1043 if (!(flags & EDIT_MSG))
1044 strvec_push(&cmd.args, "--allow-empty-message");
1046 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1047 return run_command_silent_on_success(&cmd);
1048 else
1049 return run_command(&cmd);
1052 static int rest_is_empty(const struct strbuf *sb, int start)
1054 int i, eol;
1055 const char *nl;
1057 /* Check if the rest is just whitespace and Signed-off-by's. */
1058 for (i = start; i < sb->len; i++) {
1059 nl = memchr(sb->buf + i, '\n', sb->len - i);
1060 if (nl)
1061 eol = nl - sb->buf;
1062 else
1063 eol = sb->len;
1065 if (strlen(sign_off_header) <= eol - i &&
1066 starts_with(sb->buf + i, sign_off_header)) {
1067 i = eol;
1068 continue;
1070 while (i < eol)
1071 if (!isspace(sb->buf[i++]))
1072 return 0;
1075 return 1;
1078 void cleanup_message(struct strbuf *msgbuf,
1079 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1081 if (verbose || /* Truncate the message just before the diff, if any. */
1082 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1083 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1084 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1085 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1089 * Find out if the message in the strbuf contains only whitespace and
1090 * Signed-off-by lines.
1092 int message_is_empty(const struct strbuf *sb,
1093 enum commit_msg_cleanup_mode cleanup_mode)
1095 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1096 return 0;
1097 return rest_is_empty(sb, 0);
1101 * See if the user edited the message in the editor or left what
1102 * was in the template intact
1104 int template_untouched(const struct strbuf *sb, const char *template_file,
1105 enum commit_msg_cleanup_mode cleanup_mode)
1107 struct strbuf tmpl = STRBUF_INIT;
1108 const char *start;
1110 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1111 return 0;
1113 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1114 return 0;
1116 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1117 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1118 start = sb->buf;
1119 strbuf_release(&tmpl);
1120 return rest_is_empty(sb, start - sb->buf);
1123 int update_head_with_reflog(const struct commit *old_head,
1124 const struct object_id *new_head,
1125 const char *action, const struct strbuf *msg,
1126 struct strbuf *err)
1128 struct ref_transaction *transaction;
1129 struct strbuf sb = STRBUF_INIT;
1130 const char *nl;
1131 int ret = 0;
1133 if (action) {
1134 strbuf_addstr(&sb, action);
1135 strbuf_addstr(&sb, ": ");
1138 nl = strchr(msg->buf, '\n');
1139 if (nl) {
1140 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1141 } else {
1142 strbuf_addbuf(&sb, msg);
1143 strbuf_addch(&sb, '\n');
1146 transaction = ref_transaction_begin(err);
1147 if (!transaction ||
1148 ref_transaction_update(transaction, "HEAD", new_head,
1149 old_head ? &old_head->object.oid : null_oid(),
1150 0, sb.buf, err) ||
1151 ref_transaction_commit(transaction, err)) {
1152 ret = -1;
1154 ref_transaction_free(transaction);
1155 strbuf_release(&sb);
1157 return ret;
1160 static int run_rewrite_hook(const struct object_id *oldoid,
1161 const struct object_id *newoid)
1163 struct child_process proc = CHILD_PROCESS_INIT;
1164 const char *argv[3];
1165 int code;
1166 struct strbuf sb = STRBUF_INIT;
1168 argv[0] = find_hook("post-rewrite");
1169 if (!argv[0])
1170 return 0;
1172 argv[1] = "amend";
1173 argv[2] = NULL;
1175 proc.argv = argv;
1176 proc.in = -1;
1177 proc.stdout_to_stderr = 1;
1178 proc.trace2_hook_name = "post-rewrite";
1180 code = start_command(&proc);
1181 if (code)
1182 return code;
1183 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1184 sigchain_push(SIGPIPE, SIG_IGN);
1185 write_in_full(proc.in, sb.buf, sb.len);
1186 close(proc.in);
1187 strbuf_release(&sb);
1188 sigchain_pop(SIGPIPE);
1189 return finish_command(&proc);
1192 void commit_post_rewrite(struct repository *r,
1193 const struct commit *old_head,
1194 const struct object_id *new_head)
1196 struct notes_rewrite_cfg *cfg;
1198 cfg = init_copy_notes_for_rewrite("amend");
1199 if (cfg) {
1200 /* we are amending, so old_head is not NULL */
1201 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1202 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1204 run_rewrite_hook(&old_head->object.oid, new_head);
1207 static int run_prepare_commit_msg_hook(struct repository *r,
1208 struct strbuf *msg,
1209 const char *commit)
1211 int ret = 0;
1212 const char *name, *arg1 = NULL, *arg2 = NULL;
1214 name = git_path_commit_editmsg();
1215 if (write_message(msg->buf, msg->len, name, 0))
1216 return -1;
1218 if (commit) {
1219 arg1 = "commit";
1220 arg2 = commit;
1221 } else {
1222 arg1 = "message";
1224 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1225 arg1, arg2, NULL))
1226 ret = error(_("'prepare-commit-msg' hook failed"));
1228 return ret;
1231 static const char implicit_ident_advice_noconfig[] =
1232 N_("Your name and email address were configured automatically based\n"
1233 "on your username and hostname. Please check that they are accurate.\n"
1234 "You can suppress this message by setting them explicitly. Run the\n"
1235 "following command and follow the instructions in your editor to edit\n"
1236 "your configuration file:\n"
1237 "\n"
1238 " git config --global --edit\n"
1239 "\n"
1240 "After doing this, you may fix the identity used for this commit with:\n"
1241 "\n"
1242 " git commit --amend --reset-author\n");
1244 static const char implicit_ident_advice_config[] =
1245 N_("Your name and email address were configured automatically based\n"
1246 "on your username and hostname. Please check that they are accurate.\n"
1247 "You can suppress this message by setting them explicitly:\n"
1248 "\n"
1249 " git config --global user.name \"Your Name\"\n"
1250 " git config --global user.email you@example.com\n"
1251 "\n"
1252 "After doing this, you may fix the identity used for this commit with:\n"
1253 "\n"
1254 " git commit --amend --reset-author\n");
1256 static const char *implicit_ident_advice(void)
1258 char *user_config = interpolate_path("~/.gitconfig", 0);
1259 char *xdg_config = xdg_config_home("config");
1260 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1262 free(user_config);
1263 free(xdg_config);
1265 if (config_exists)
1266 return _(implicit_ident_advice_config);
1267 else
1268 return _(implicit_ident_advice_noconfig);
1272 void print_commit_summary(struct repository *r,
1273 const char *prefix,
1274 const struct object_id *oid,
1275 unsigned int flags)
1277 struct rev_info rev;
1278 struct commit *commit;
1279 struct strbuf format = STRBUF_INIT;
1280 const char *head;
1281 struct pretty_print_context pctx = {0};
1282 struct strbuf author_ident = STRBUF_INIT;
1283 struct strbuf committer_ident = STRBUF_INIT;
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 rev.diffopt.break_opt = 0;
1331 diff_setup_done(&rev.diffopt);
1333 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1334 if (!head)
1335 die_errno(_("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 strbuf_release(&format);
1352 static int parse_head(struct repository *r, struct commit **head)
1354 struct commit *current_head;
1355 struct object_id oid;
1357 if (get_oid("HEAD", &oid)) {
1358 current_head = NULL;
1359 } else {
1360 current_head = lookup_commit_reference(r, &oid);
1361 if (!current_head)
1362 return error(_("could not parse HEAD"));
1363 if (!oideq(&oid, &current_head->object.oid)) {
1364 warning(_("HEAD %s is not a commit!"),
1365 oid_to_hex(&oid));
1367 if (parse_commit(current_head))
1368 return error(_("could not parse HEAD commit"));
1370 *head = current_head;
1372 return 0;
1376 * Try to commit without forking 'git commit'. In some cases we need
1377 * to run 'git commit' to display an error message
1379 * Returns:
1380 * -1 - error unable to commit
1381 * 0 - success
1382 * 1 - run 'git commit'
1384 static int try_to_commit(struct repository *r,
1385 struct strbuf *msg, const char *author,
1386 struct replay_opts *opts, unsigned int flags,
1387 struct object_id *oid)
1389 struct object_id tree;
1390 struct commit *current_head = NULL;
1391 struct commit_list *parents = NULL;
1392 struct commit_extra_header *extra = NULL;
1393 struct strbuf err = STRBUF_INIT;
1394 struct strbuf commit_msg = STRBUF_INIT;
1395 char *amend_author = NULL;
1396 const char *committer = NULL;
1397 const char *hook_commit = NULL;
1398 enum commit_msg_cleanup_mode cleanup;
1399 int res = 0;
1401 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1402 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1404 if (parse_head(r, &current_head))
1405 return -1;
1407 if (flags & AMEND_MSG) {
1408 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1409 const char *out_enc = get_commit_output_encoding();
1410 const char *message = logmsg_reencode(current_head, NULL,
1411 out_enc);
1413 if (!msg) {
1414 const char *orig_message = NULL;
1416 find_commit_subject(message, &orig_message);
1417 msg = &commit_msg;
1418 strbuf_addstr(msg, orig_message);
1419 hook_commit = "HEAD";
1421 author = amend_author = get_author(message);
1422 unuse_commit_buffer(current_head, message);
1423 if (!author) {
1424 res = error(_("unable to parse commit author"));
1425 goto out;
1427 parents = copy_commit_list(current_head->parents);
1428 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1429 } else if (current_head &&
1430 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1431 commit_list_insert(current_head, &parents);
1434 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1435 res = error(_("git write-tree failed to write a tree"));
1436 goto out;
1439 if (!(flags & ALLOW_EMPTY)) {
1440 struct commit *first_parent = current_head;
1442 if (flags & AMEND_MSG) {
1443 if (current_head->parents) {
1444 first_parent = current_head->parents->item;
1445 if (repo_parse_commit(r, first_parent)) {
1446 res = error(_("could not parse HEAD commit"));
1447 goto out;
1449 } else {
1450 first_parent = NULL;
1453 if (oideq(first_parent
1454 ? get_commit_tree_oid(first_parent)
1455 : the_hash_algo->empty_tree,
1456 &tree)) {
1457 res = 1; /* run 'git commit' to display error message */
1458 goto out;
1462 if (find_hook("prepare-commit-msg")) {
1463 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1464 if (res)
1465 goto out;
1466 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1467 2048) < 0) {
1468 res = error_errno(_("unable to read commit message "
1469 "from '%s'"),
1470 git_path_commit_editmsg());
1471 goto out;
1473 msg = &commit_msg;
1476 if (flags & CLEANUP_MSG)
1477 cleanup = COMMIT_MSG_CLEANUP_ALL;
1478 else if (flags & VERBATIM_MSG)
1479 cleanup = COMMIT_MSG_CLEANUP_NONE;
1480 else if ((opts->signoff || opts->record_origin) &&
1481 !opts->explicit_cleanup)
1482 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1483 else
1484 cleanup = opts->default_msg_cleanup;
1486 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1487 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1488 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1489 res = 1; /* run 'git commit' to display error message */
1490 goto out;
1493 if (opts->committer_date_is_author_date) {
1494 struct ident_split id;
1495 struct strbuf date = STRBUF_INIT;
1497 if (!opts->ignore_date) {
1498 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1499 res = error(_("invalid author identity '%s'"),
1500 author);
1501 goto out;
1503 if (!id.date_begin) {
1504 res = error(_(
1505 "corrupt author: missing date information"));
1506 goto out;
1508 strbuf_addf(&date, "@%.*s %.*s",
1509 (int)(id.date_end - id.date_begin),
1510 id.date_begin,
1511 (int)(id.tz_end - id.tz_begin),
1512 id.tz_begin);
1513 } else {
1514 reset_ident_date();
1516 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1517 getenv("GIT_COMMITTER_EMAIL"),
1518 WANT_COMMITTER_IDENT,
1519 opts->ignore_date ? NULL : date.buf,
1520 IDENT_STRICT);
1521 strbuf_release(&date);
1522 } else {
1523 reset_ident_date();
1526 if (opts->ignore_date) {
1527 struct ident_split id;
1528 char *name, *email;
1530 if (split_ident_line(&id, author, strlen(author)) < 0) {
1531 error(_("invalid author identity '%s'"), author);
1532 goto out;
1534 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1535 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1536 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1537 IDENT_STRICT);
1538 free(name);
1539 free(email);
1542 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1543 author, committer, opts->gpg_sign, extra)) {
1544 res = error(_("failed to write commit object"));
1545 goto out;
1548 if (update_head_with_reflog(current_head, oid,
1549 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1550 res = error("%s", err.buf);
1551 goto out;
1554 run_commit_hook(0, r->index_file, "post-commit", NULL);
1555 if (flags & AMEND_MSG)
1556 commit_post_rewrite(r, current_head, oid);
1558 out:
1559 free_commit_extra_headers(extra);
1560 strbuf_release(&err);
1561 strbuf_release(&commit_msg);
1562 free(amend_author);
1564 return res;
1567 static int write_rebase_head(struct object_id *oid)
1569 if (update_ref("rebase", "REBASE_HEAD", oid,
1570 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1571 return error(_("could not update %s"), "REBASE_HEAD");
1573 return 0;
1576 static int do_commit(struct repository *r,
1577 const char *msg_file, const char *author,
1578 struct replay_opts *opts, unsigned int flags,
1579 struct object_id *oid)
1581 int res = 1;
1583 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1584 struct object_id oid;
1585 struct strbuf sb = STRBUF_INIT;
1587 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1588 return error_errno(_("unable to read commit message "
1589 "from '%s'"),
1590 msg_file);
1592 res = try_to_commit(r, msg_file ? &sb : NULL,
1593 author, opts, flags, &oid);
1594 strbuf_release(&sb);
1595 if (!res) {
1596 refs_delete_ref(get_main_ref_store(r), "",
1597 "CHERRY_PICK_HEAD", NULL, 0);
1598 unlink(git_path_merge_msg(r));
1599 if (!is_rebase_i(opts))
1600 print_commit_summary(r, NULL, &oid,
1601 SUMMARY_SHOW_AUTHOR_DATE);
1602 return res;
1605 if (res == 1) {
1606 if (is_rebase_i(opts) && oid)
1607 if (write_rebase_head(oid))
1608 return -1;
1609 return run_git_commit(msg_file, opts, flags);
1612 return res;
1615 static int is_original_commit_empty(struct commit *commit)
1617 const struct object_id *ptree_oid;
1619 if (parse_commit(commit))
1620 return error(_("could not parse commit %s"),
1621 oid_to_hex(&commit->object.oid));
1622 if (commit->parents) {
1623 struct commit *parent = commit->parents->item;
1624 if (parse_commit(parent))
1625 return error(_("could not parse parent commit %s"),
1626 oid_to_hex(&parent->object.oid));
1627 ptree_oid = get_commit_tree_oid(parent);
1628 } else {
1629 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1632 return oideq(ptree_oid, get_commit_tree_oid(commit));
1636 * Should empty commits be allowed? Return status:
1637 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1638 * 0: Halt on empty commit
1639 * 1: Allow empty commit
1640 * 2: Drop empty commit
1642 static int allow_empty(struct repository *r,
1643 struct replay_opts *opts,
1644 struct commit *commit)
1646 int index_unchanged, originally_empty;
1649 * Four cases:
1651 * (1) we do not allow empty at all and error out.
1653 * (2) we allow ones that were initially empty, and
1654 * just drop the ones that become empty
1656 * (3) we allow ones that were initially empty, but
1657 * halt for the ones that become empty;
1659 * (4) we allow both.
1661 if (!opts->allow_empty)
1662 return 0; /* let "git commit" barf as necessary */
1664 index_unchanged = is_index_unchanged(r);
1665 if (index_unchanged < 0)
1666 return index_unchanged;
1667 if (!index_unchanged)
1668 return 0; /* we do not have to say --allow-empty */
1670 if (opts->keep_redundant_commits)
1671 return 1;
1673 originally_empty = is_original_commit_empty(commit);
1674 if (originally_empty < 0)
1675 return originally_empty;
1676 if (originally_empty)
1677 return 1;
1678 else if (opts->drop_redundant_commits)
1679 return 2;
1680 else
1681 return 0;
1684 static struct {
1685 char c;
1686 const char *str;
1687 } todo_command_info[] = {
1688 { 'p', "pick" },
1689 { 0, "revert" },
1690 { 'e', "edit" },
1691 { 'r', "reword" },
1692 { 'f', "fixup" },
1693 { 's', "squash" },
1694 { 'x', "exec" },
1695 { 'b', "break" },
1696 { 'l', "label" },
1697 { 't', "reset" },
1698 { 'm', "merge" },
1699 { 0, "noop" },
1700 { 'd', "drop" },
1701 { 0, NULL }
1704 static const char *command_to_string(const enum todo_command command)
1706 if (command < TODO_COMMENT)
1707 return todo_command_info[command].str;
1708 die(_("unknown command: %d"), command);
1711 static char command_to_char(const enum todo_command command)
1713 if (command < TODO_COMMENT)
1714 return todo_command_info[command].c;
1715 return comment_line_char;
1718 static int is_noop(const enum todo_command command)
1720 return TODO_NOOP <= command;
1723 static int is_fixup(enum todo_command command)
1725 return command == TODO_FIXUP || command == TODO_SQUASH;
1728 /* Does this command create a (non-merge) commit? */
1729 static int is_pick_or_similar(enum todo_command command)
1731 switch (command) {
1732 case TODO_PICK:
1733 case TODO_REVERT:
1734 case TODO_EDIT:
1735 case TODO_REWORD:
1736 case TODO_FIXUP:
1737 case TODO_SQUASH:
1738 return 1;
1739 default:
1740 return 0;
1744 enum todo_item_flags {
1745 TODO_EDIT_MERGE_MSG = (1 << 0),
1746 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1747 TODO_EDIT_FIXUP_MSG = (1 << 2),
1750 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1751 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1752 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1753 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1754 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1756 static int is_fixup_flag(enum todo_command command, unsigned flag)
1758 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1759 (flag & TODO_EDIT_FIXUP_MSG));
1763 * Wrapper around strbuf_add_commented_lines() which avoids double
1764 * commenting commit subjects.
1766 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1768 const char *s = str;
1769 while (len > 0 && s[0] == comment_line_char) {
1770 size_t count;
1771 const char *n = memchr(s, '\n', len);
1772 if (!n)
1773 count = len;
1774 else
1775 count = n - s + 1;
1776 strbuf_add(buf, s, count);
1777 s += count;
1778 len -= count;
1780 strbuf_add_commented_lines(buf, s, len);
1783 /* Does the current fixup chain contain a squash command? */
1784 static int seen_squash(struct replay_opts *opts)
1786 return starts_with(opts->current_fixups.buf, "squash") ||
1787 strstr(opts->current_fixups.buf, "\nsquash");
1790 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1792 strbuf_setlen(buf1, 2);
1793 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1794 strbuf_addch(buf1, '\n');
1795 strbuf_setlen(buf2, 2);
1796 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1797 strbuf_addch(buf2, '\n');
1801 * Comment out any un-commented commit messages, updating the message comments
1802 * to say they will be skipped but do not comment out the empty lines that
1803 * surround commit messages and their comments.
1805 static void update_squash_message_for_fixup(struct strbuf *msg)
1807 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1808 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1809 const char *s, *start;
1810 char *orig_msg;
1811 size_t orig_msg_len;
1812 int i = 1;
1814 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1815 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1816 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1817 while (s) {
1818 const char *next;
1819 size_t off;
1820 if (skip_prefix(s, buf1.buf, &next)) {
1822 * Copy the last message, preserving the blank line
1823 * preceding the current line
1825 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1826 copy_lines(msg, start, s - start - off);
1827 if (off)
1828 strbuf_addch(msg, '\n');
1830 * The next message needs to be commented out but the
1831 * message header is already commented out so just copy
1832 * it and the blank line that follows it.
1834 strbuf_addbuf(msg, &buf2);
1835 if (*next == '\n')
1836 strbuf_addch(msg, *next++);
1837 start = s = next;
1838 copy_lines = add_commented_lines;
1839 update_comment_bufs(&buf1, &buf2, ++i);
1840 } else if (skip_prefix(s, buf2.buf, &next)) {
1841 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1842 copy_lines(msg, start, s - start - off);
1843 start = s - off;
1844 s = next;
1845 copy_lines = strbuf_add;
1846 update_comment_bufs(&buf1, &buf2, ++i);
1847 } else {
1848 s = strchr(s, '\n');
1849 if (s)
1850 s++;
1853 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1854 free(orig_msg);
1855 strbuf_release(&buf1);
1856 strbuf_release(&buf2);
1859 static int append_squash_message(struct strbuf *buf, const char *body,
1860 enum todo_command command, struct replay_opts *opts,
1861 unsigned flag)
1863 const char *fixup_msg;
1864 size_t commented_len = 0, fixup_off;
1866 * amend is non-interactive and not normally used with fixup!
1867 * or squash! commits, so only comment out those subjects when
1868 * squashing commit messages.
1870 if (starts_with(body, "amend!") ||
1871 ((command == TODO_SQUASH || seen_squash(opts)) &&
1872 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1873 commented_len = commit_subject_length(body);
1875 strbuf_addf(buf, "\n%c ", comment_line_char);
1876 strbuf_addf(buf, _(nth_commit_msg_fmt),
1877 ++opts->current_fixup_count + 1);
1878 strbuf_addstr(buf, "\n\n");
1879 strbuf_add_commented_lines(buf, body, commented_len);
1880 /* buf->buf may be reallocated so store an offset into the buffer */
1881 fixup_off = buf->len;
1882 strbuf_addstr(buf, body + commented_len);
1884 /* fixup -C after squash behaves like squash */
1885 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1887 * We're replacing the commit message so we need to
1888 * append the Signed-off-by: trailer if the user
1889 * requested '--signoff'.
1891 if (opts->signoff)
1892 append_signoff(buf, 0, 0);
1894 if ((command == TODO_FIXUP) &&
1895 (flag & TODO_REPLACE_FIXUP_MSG) &&
1896 (file_exists(rebase_path_fixup_msg()) ||
1897 !file_exists(rebase_path_squash_msg()))) {
1898 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1899 if (write_message(fixup_msg, strlen(fixup_msg),
1900 rebase_path_fixup_msg(), 0) < 0)
1901 return error(_("cannot write '%s'"),
1902 rebase_path_fixup_msg());
1903 } else {
1904 unlink(rebase_path_fixup_msg());
1906 } else {
1907 unlink(rebase_path_fixup_msg());
1910 return 0;
1913 static int update_squash_messages(struct repository *r,
1914 enum todo_command command,
1915 struct commit *commit,
1916 struct replay_opts *opts,
1917 unsigned flag)
1919 struct strbuf buf = STRBUF_INIT;
1920 int res = 0;
1921 const char *message, *body;
1922 const char *encoding = get_commit_output_encoding();
1924 if (opts->current_fixup_count > 0) {
1925 struct strbuf header = STRBUF_INIT;
1926 char *eol;
1928 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1929 return error(_("could not read '%s'"),
1930 rebase_path_squash_msg());
1932 eol = buf.buf[0] != comment_line_char ?
1933 buf.buf : strchrnul(buf.buf, '\n');
1935 strbuf_addf(&header, "%c ", comment_line_char);
1936 strbuf_addf(&header, _(combined_commit_msg_fmt),
1937 opts->current_fixup_count + 2);
1938 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1939 strbuf_release(&header);
1940 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1941 update_squash_message_for_fixup(&buf);
1942 } else {
1943 struct object_id head;
1944 struct commit *head_commit;
1945 const char *head_message, *body;
1947 if (get_oid("HEAD", &head))
1948 return error(_("need a HEAD to fixup"));
1949 if (!(head_commit = lookup_commit_reference(r, &head)))
1950 return error(_("could not read HEAD"));
1951 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1952 return error(_("could not read HEAD's commit message"));
1954 find_commit_subject(head_message, &body);
1955 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1956 rebase_path_fixup_msg(), 0) < 0) {
1957 unuse_commit_buffer(head_commit, head_message);
1958 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1960 strbuf_addf(&buf, "%c ", comment_line_char);
1961 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1962 strbuf_addf(&buf, "\n%c ", comment_line_char);
1963 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1964 _(skip_first_commit_msg_str) :
1965 _(first_commit_msg_str));
1966 strbuf_addstr(&buf, "\n\n");
1967 if (is_fixup_flag(command, flag))
1968 strbuf_add_commented_lines(&buf, body, strlen(body));
1969 else
1970 strbuf_addstr(&buf, body);
1972 unuse_commit_buffer(head_commit, head_message);
1975 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1976 return error(_("could not read commit message of %s"),
1977 oid_to_hex(&commit->object.oid));
1978 find_commit_subject(message, &body);
1980 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1981 res = append_squash_message(&buf, body, command, opts, flag);
1982 } else if (command == TODO_FIXUP) {
1983 strbuf_addf(&buf, "\n%c ", comment_line_char);
1984 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1985 ++opts->current_fixup_count + 1);
1986 strbuf_addstr(&buf, "\n\n");
1987 strbuf_add_commented_lines(&buf, body, strlen(body));
1988 } else
1989 return error(_("unknown command: %d"), command);
1990 unuse_commit_buffer(commit, message);
1992 if (!res)
1993 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1995 strbuf_release(&buf);
1997 if (!res) {
1998 strbuf_addf(&opts->current_fixups, "%s%s %s",
1999 opts->current_fixups.len ? "\n" : "",
2000 command_to_string(command),
2001 oid_to_hex(&commit->object.oid));
2002 res = write_message(opts->current_fixups.buf,
2003 opts->current_fixups.len,
2004 rebase_path_current_fixups(), 0);
2007 return res;
2010 static void flush_rewritten_pending(void)
2012 struct strbuf buf = STRBUF_INIT;
2013 struct object_id newoid;
2014 FILE *out;
2016 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2017 !get_oid("HEAD", &newoid) &&
2018 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2019 char *bol = buf.buf, *eol;
2021 while (*bol) {
2022 eol = strchrnul(bol, '\n');
2023 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2024 bol, oid_to_hex(&newoid));
2025 if (!*eol)
2026 break;
2027 bol = eol + 1;
2029 fclose(out);
2030 unlink(rebase_path_rewritten_pending());
2032 strbuf_release(&buf);
2035 static void record_in_rewritten(struct object_id *oid,
2036 enum todo_command next_command)
2038 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2040 if (!out)
2041 return;
2043 fprintf(out, "%s\n", oid_to_hex(oid));
2044 fclose(out);
2046 if (!is_fixup(next_command))
2047 flush_rewritten_pending();
2050 static int should_edit(struct replay_opts *opts) {
2051 if (opts->edit < 0)
2053 * Note that we only handle the case of non-conflicted
2054 * commits; continue_single_pick() handles the conflicted
2055 * commits itself instead of calling this function.
2057 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2058 return opts->edit;
2061 static int do_pick_commit(struct repository *r,
2062 struct todo_item *item,
2063 struct replay_opts *opts,
2064 int final_fixup, int *check_todo)
2066 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2067 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2068 struct object_id head;
2069 struct commit *base, *next, *parent;
2070 const char *base_label, *next_label;
2071 char *author = NULL;
2072 struct commit_message msg = { NULL, NULL, NULL, NULL };
2073 struct strbuf msgbuf = STRBUF_INIT;
2074 int res, unborn = 0, reword = 0, allow, drop_commit;
2075 enum todo_command command = item->command;
2076 struct commit *commit = item->commit;
2078 if (opts->no_commit) {
2080 * We do not intend to commit immediately. We just want to
2081 * merge the differences in, so let's compute the tree
2082 * that represents the "current" state for the merge machinery
2083 * to work on.
2085 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2086 return error(_("your index file is unmerged."));
2087 } else {
2088 unborn = get_oid("HEAD", &head);
2089 /* Do we want to generate a root commit? */
2090 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2091 oideq(&head, &opts->squash_onto)) {
2092 if (is_fixup(command))
2093 return error(_("cannot fixup root commit"));
2094 flags |= CREATE_ROOT_COMMIT;
2095 unborn = 1;
2096 } else if (unborn)
2097 oidcpy(&head, the_hash_algo->empty_tree);
2098 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2099 NULL, 0))
2100 return error_dirty_index(r, opts);
2102 discard_index(r->index);
2104 if (!commit->parents)
2105 parent = NULL;
2106 else if (commit->parents->next) {
2107 /* Reverting or cherry-picking a merge commit */
2108 int cnt;
2109 struct commit_list *p;
2111 if (!opts->mainline)
2112 return error(_("commit %s is a merge but no -m option was given."),
2113 oid_to_hex(&commit->object.oid));
2115 for (cnt = 1, p = commit->parents;
2116 cnt != opts->mainline && p;
2117 cnt++)
2118 p = p->next;
2119 if (cnt != opts->mainline || !p)
2120 return error(_("commit %s does not have parent %d"),
2121 oid_to_hex(&commit->object.oid), opts->mainline);
2122 parent = p->item;
2123 } else if (1 < opts->mainline)
2125 * Non-first parent explicitly specified as mainline for
2126 * non-merge commit
2128 return error(_("commit %s does not have parent %d"),
2129 oid_to_hex(&commit->object.oid), opts->mainline);
2130 else
2131 parent = commit->parents->item;
2133 if (get_message(commit, &msg) != 0)
2134 return error(_("cannot get commit message for %s"),
2135 oid_to_hex(&commit->object.oid));
2137 if (opts->allow_ff && !is_fixup(command) &&
2138 ((parent && oideq(&parent->object.oid, &head)) ||
2139 (!parent && unborn))) {
2140 if (is_rebase_i(opts))
2141 write_author_script(msg.message);
2142 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2143 opts);
2144 if (res || command != TODO_REWORD)
2145 goto leave;
2146 reword = 1;
2147 msg_file = NULL;
2148 goto fast_forward_edit;
2150 if (parent && parse_commit(parent) < 0)
2151 /* TRANSLATORS: The first %s will be a "todo" command like
2152 "revert" or "pick", the second %s a SHA1. */
2153 return error(_("%s: cannot parse parent commit %s"),
2154 command_to_string(command),
2155 oid_to_hex(&parent->object.oid));
2158 * "commit" is an existing commit. We would want to apply
2159 * the difference it introduces since its first parent "prev"
2160 * on top of the current HEAD if we are cherry-pick. Or the
2161 * reverse of it if we are revert.
2164 if (command == TODO_REVERT) {
2165 base = commit;
2166 base_label = msg.label;
2167 next = parent;
2168 next_label = msg.parent_label;
2169 strbuf_addstr(&msgbuf, "Revert \"");
2170 strbuf_addstr(&msgbuf, msg.subject);
2171 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2172 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2174 if (commit->parents && commit->parents->next) {
2175 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2176 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2178 strbuf_addstr(&msgbuf, ".\n");
2179 } else {
2180 const char *p;
2182 base = parent;
2183 base_label = msg.parent_label;
2184 next = commit;
2185 next_label = msg.label;
2187 /* Append the commit log message to msgbuf. */
2188 if (find_commit_subject(msg.message, &p))
2189 strbuf_addstr(&msgbuf, p);
2191 if (opts->record_origin) {
2192 strbuf_complete_line(&msgbuf);
2193 if (!has_conforming_footer(&msgbuf, NULL, 0))
2194 strbuf_addch(&msgbuf, '\n');
2195 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2196 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2197 strbuf_addstr(&msgbuf, ")\n");
2199 if (!is_fixup(command))
2200 author = get_author(msg.message);
2203 if (command == TODO_REWORD)
2204 reword = 1;
2205 else if (is_fixup(command)) {
2206 if (update_squash_messages(r, command, commit,
2207 opts, item->flags))
2208 return -1;
2209 flags |= AMEND_MSG;
2210 if (!final_fixup)
2211 msg_file = rebase_path_squash_msg();
2212 else if (file_exists(rebase_path_fixup_msg())) {
2213 flags |= VERBATIM_MSG;
2214 msg_file = rebase_path_fixup_msg();
2215 } else {
2216 const char *dest = git_path_squash_msg(r);
2217 unlink(dest);
2218 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2219 return error(_("could not rename '%s' to '%s'"),
2220 rebase_path_squash_msg(), dest);
2221 unlink(git_path_merge_msg(r));
2222 msg_file = dest;
2223 flags |= EDIT_MSG;
2227 if (opts->signoff && !is_fixup(command))
2228 append_signoff(&msgbuf, 0, 0);
2230 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2231 res = -1;
2232 else if (!opts->strategy ||
2233 !strcmp(opts->strategy, "recursive") ||
2234 !strcmp(opts->strategy, "ort") ||
2235 command == TODO_REVERT) {
2236 res = do_recursive_merge(r, base, next, base_label, next_label,
2237 &head, &msgbuf, opts);
2238 if (res < 0)
2239 goto leave;
2241 res |= write_message(msgbuf.buf, msgbuf.len,
2242 git_path_merge_msg(r), 0);
2243 } else {
2244 struct commit_list *common = NULL;
2245 struct commit_list *remotes = NULL;
2247 res = write_message(msgbuf.buf, msgbuf.len,
2248 git_path_merge_msg(r), 0);
2250 commit_list_insert(base, &common);
2251 commit_list_insert(next, &remotes);
2252 res |= try_merge_command(r, opts->strategy,
2253 opts->xopts_nr, (const char **)opts->xopts,
2254 common, oid_to_hex(&head), remotes);
2255 free_commit_list(common);
2256 free_commit_list(remotes);
2258 strbuf_release(&msgbuf);
2261 * If the merge was clean or if it failed due to conflict, we write
2262 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2263 * However, if the merge did not even start, then we don't want to
2264 * write it at all.
2266 if ((command == TODO_PICK || command == TODO_REWORD ||
2267 command == TODO_EDIT) && !opts->no_commit &&
2268 (res == 0 || res == 1) &&
2269 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2270 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2271 res = -1;
2272 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2273 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2274 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2275 res = -1;
2277 if (res) {
2278 error(command == TODO_REVERT
2279 ? _("could not revert %s... %s")
2280 : _("could not apply %s... %s"),
2281 short_commit_name(commit), msg.subject);
2282 print_advice(r, res == 1, opts);
2283 repo_rerere(r, opts->allow_rerere_auto);
2284 goto leave;
2287 drop_commit = 0;
2288 allow = allow_empty(r, opts, commit);
2289 if (allow < 0) {
2290 res = allow;
2291 goto leave;
2292 } else if (allow == 1) {
2293 flags |= ALLOW_EMPTY;
2294 } else if (allow == 2) {
2295 drop_commit = 1;
2296 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2297 NULL, 0);
2298 unlink(git_path_merge_msg(r));
2299 unlink(git_path_auto_merge(r));
2300 fprintf(stderr,
2301 _("dropping %s %s -- patch contents already upstream\n"),
2302 oid_to_hex(&commit->object.oid), msg.subject);
2303 } /* else allow == 0 and there's nothing special to do */
2304 if (!opts->no_commit && !drop_commit) {
2305 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2306 res = do_commit(r, msg_file, author, opts, flags,
2307 commit? &commit->object.oid : NULL);
2308 else
2309 res = error(_("unable to parse commit author"));
2310 *check_todo = !!(flags & EDIT_MSG);
2311 if (!res && reword) {
2312 fast_forward_edit:
2313 res = run_git_commit(NULL, opts, EDIT_MSG |
2314 VERIFY_MSG | AMEND_MSG |
2315 (flags & ALLOW_EMPTY));
2316 *check_todo = 1;
2321 if (!res && final_fixup) {
2322 unlink(rebase_path_fixup_msg());
2323 unlink(rebase_path_squash_msg());
2324 unlink(rebase_path_current_fixups());
2325 strbuf_reset(&opts->current_fixups);
2326 opts->current_fixup_count = 0;
2329 leave:
2330 free_message(commit, &msg);
2331 free(author);
2332 update_abort_safety_file();
2334 return res;
2337 static int prepare_revs(struct replay_opts *opts)
2340 * picking (but not reverting) ranges (but not individual revisions)
2341 * should be done in reverse
2343 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2344 opts->revs->reverse ^= 1;
2346 if (prepare_revision_walk(opts->revs))
2347 return error(_("revision walk setup failed"));
2349 return 0;
2352 static int read_and_refresh_cache(struct repository *r,
2353 struct replay_opts *opts)
2355 struct lock_file index_lock = LOCK_INIT;
2356 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2357 if (repo_read_index(r) < 0) {
2358 rollback_lock_file(&index_lock);
2359 return error(_("git %s: failed to read the index"),
2360 _(action_name(opts)));
2362 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2364 if (index_fd >= 0) {
2365 if (write_locked_index(r->index, &index_lock,
2366 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2367 return error(_("git %s: failed to refresh the index"),
2368 _(action_name(opts)));
2373 * If we are resolving merges in any way other than "ort", then
2374 * expand the sparse index.
2376 if (opts->strategy && strcmp(opts->strategy, "ort"))
2377 ensure_full_index(r->index);
2378 return 0;
2381 void todo_list_release(struct todo_list *todo_list)
2383 strbuf_release(&todo_list->buf);
2384 FREE_AND_NULL(todo_list->items);
2385 todo_list->nr = todo_list->alloc = 0;
2388 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2390 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2391 todo_list->total_nr++;
2392 return todo_list->items + todo_list->nr++;
2395 const char *todo_item_get_arg(struct todo_list *todo_list,
2396 struct todo_item *item)
2398 return todo_list->buf.buf + item->arg_offset;
2401 static int is_command(enum todo_command command, const char **bol)
2403 const char *str = todo_command_info[command].str;
2404 const char nick = todo_command_info[command].c;
2405 const char *p = *bol + 1;
2407 return skip_prefix(*bol, str, bol) ||
2408 ((nick && **bol == nick) &&
2409 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2410 (*bol = p));
2413 static int parse_insn_line(struct repository *r, struct todo_item *item,
2414 const char *buf, const char *bol, char *eol)
2416 struct object_id commit_oid;
2417 char *end_of_object_name;
2418 int i, saved, status, padding;
2420 item->flags = 0;
2422 /* left-trim */
2423 bol += strspn(bol, " \t");
2425 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2426 item->command = TODO_COMMENT;
2427 item->commit = NULL;
2428 item->arg_offset = bol - buf;
2429 item->arg_len = eol - bol;
2430 return 0;
2433 for (i = 0; i < TODO_COMMENT; i++)
2434 if (is_command(i, &bol)) {
2435 item->command = i;
2436 break;
2438 if (i >= TODO_COMMENT)
2439 return -1;
2441 /* Eat up extra spaces/ tabs before object name */
2442 padding = strspn(bol, " \t");
2443 bol += padding;
2445 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2446 if (bol != eol)
2447 return error(_("%s does not accept arguments: '%s'"),
2448 command_to_string(item->command), bol);
2449 item->commit = NULL;
2450 item->arg_offset = bol - buf;
2451 item->arg_len = eol - bol;
2452 return 0;
2455 if (!padding)
2456 return error(_("missing arguments for %s"),
2457 command_to_string(item->command));
2459 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2460 item->command == TODO_RESET) {
2461 item->commit = NULL;
2462 item->arg_offset = bol - buf;
2463 item->arg_len = (int)(eol - bol);
2464 return 0;
2467 if (item->command == TODO_FIXUP) {
2468 if (skip_prefix(bol, "-C", &bol) &&
2469 (*bol == ' ' || *bol == '\t')) {
2470 bol += strspn(bol, " \t");
2471 item->flags |= TODO_REPLACE_FIXUP_MSG;
2472 } else if (skip_prefix(bol, "-c", &bol) &&
2473 (*bol == ' ' || *bol == '\t')) {
2474 bol += strspn(bol, " \t");
2475 item->flags |= TODO_EDIT_FIXUP_MSG;
2479 if (item->command == TODO_MERGE) {
2480 if (skip_prefix(bol, "-C", &bol))
2481 bol += strspn(bol, " \t");
2482 else if (skip_prefix(bol, "-c", &bol)) {
2483 bol += strspn(bol, " \t");
2484 item->flags |= TODO_EDIT_MERGE_MSG;
2485 } else {
2486 item->flags |= TODO_EDIT_MERGE_MSG;
2487 item->commit = NULL;
2488 item->arg_offset = bol - buf;
2489 item->arg_len = (int)(eol - bol);
2490 return 0;
2494 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2495 saved = *end_of_object_name;
2496 *end_of_object_name = '\0';
2497 status = get_oid(bol, &commit_oid);
2498 if (status < 0)
2499 error(_("could not parse '%s'"), bol); /* return later */
2500 *end_of_object_name = saved;
2502 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2503 item->arg_offset = bol - buf;
2504 item->arg_len = (int)(eol - bol);
2506 if (status < 0)
2507 return status;
2509 item->commit = lookup_commit_reference(r, &commit_oid);
2510 return item->commit ? 0 : -1;
2513 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2515 const char *todo_file, *bol;
2516 struct strbuf buf = STRBUF_INIT;
2517 int ret = 0;
2519 todo_file = git_path_todo_file();
2520 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2521 if (errno == ENOENT || errno == ENOTDIR)
2522 return -1;
2523 else
2524 return error_errno("unable to open '%s'", todo_file);
2526 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2527 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2528 *action = REPLAY_PICK;
2529 else if (is_command(TODO_REVERT, &bol) &&
2530 (*bol == ' ' || *bol == '\t'))
2531 *action = REPLAY_REVERT;
2532 else
2533 ret = -1;
2535 strbuf_release(&buf);
2537 return ret;
2540 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2541 struct todo_list *todo_list)
2543 struct todo_item *item;
2544 char *p = buf, *next_p;
2545 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2547 todo_list->current = todo_list->nr = 0;
2549 for (i = 1; *p; i++, p = next_p) {
2550 char *eol = strchrnul(p, '\n');
2552 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2554 if (p != eol && eol[-1] == '\r')
2555 eol--; /* strip Carriage Return */
2557 item = append_new_todo(todo_list);
2558 item->offset_in_buf = p - todo_list->buf.buf;
2559 if (parse_insn_line(r, item, buf, p, eol)) {
2560 res = error(_("invalid line %d: %.*s"),
2561 i, (int)(eol - p), p);
2562 item->command = TODO_COMMENT + 1;
2563 item->arg_offset = p - buf;
2564 item->arg_len = (int)(eol - p);
2565 item->commit = NULL;
2568 if (fixup_okay)
2569 ; /* do nothing */
2570 else if (is_fixup(item->command))
2571 return error(_("cannot '%s' without a previous commit"),
2572 command_to_string(item->command));
2573 else if (!is_noop(item->command))
2574 fixup_okay = 1;
2577 return res;
2580 static int count_commands(struct todo_list *todo_list)
2582 int count = 0, i;
2584 for (i = 0; i < todo_list->nr; i++)
2585 if (todo_list->items[i].command != TODO_COMMENT)
2586 count++;
2588 return count;
2591 static int get_item_line_offset(struct todo_list *todo_list, int index)
2593 return index < todo_list->nr ?
2594 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2597 static const char *get_item_line(struct todo_list *todo_list, int index)
2599 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2602 static int get_item_line_length(struct todo_list *todo_list, int index)
2604 return get_item_line_offset(todo_list, index + 1)
2605 - get_item_line_offset(todo_list, index);
2608 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2610 int fd;
2611 ssize_t len;
2613 fd = open(path, O_RDONLY);
2614 if (fd < 0)
2615 return error_errno(_("could not open '%s'"), path);
2616 len = strbuf_read(sb, fd, 0);
2617 close(fd);
2618 if (len < 0)
2619 return error(_("could not read '%s'."), path);
2620 return len;
2623 static int have_finished_the_last_pick(void)
2625 struct strbuf buf = STRBUF_INIT;
2626 const char *eol;
2627 const char *todo_path = git_path_todo_file();
2628 int ret = 0;
2630 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2631 if (errno == ENOENT) {
2632 return 0;
2633 } else {
2634 error_errno("unable to open '%s'", todo_path);
2635 return 0;
2638 /* If there is only one line then we are done */
2639 eol = strchr(buf.buf, '\n');
2640 if (!eol || !eol[1])
2641 ret = 1;
2643 strbuf_release(&buf);
2645 return ret;
2648 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2650 struct replay_opts opts = REPLAY_OPTS_INIT;
2651 int need_cleanup = 0;
2653 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2654 if (!refs_delete_ref(get_main_ref_store(r), "",
2655 "CHERRY_PICK_HEAD", NULL, 0) &&
2656 verbose)
2657 warning(_("cancelling a cherry picking in progress"));
2658 opts.action = REPLAY_PICK;
2659 need_cleanup = 1;
2662 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2663 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2664 NULL, 0) &&
2665 verbose)
2666 warning(_("cancelling a revert in progress"));
2667 opts.action = REPLAY_REVERT;
2668 need_cleanup = 1;
2671 unlink(git_path_auto_merge(r));
2673 if (!need_cleanup)
2674 return;
2676 if (!have_finished_the_last_pick())
2677 return;
2679 sequencer_remove_state(&opts);
2682 static void todo_list_write_total_nr(struct todo_list *todo_list)
2684 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2686 if (f) {
2687 fprintf(f, "%d\n", todo_list->total_nr);
2688 fclose(f);
2692 static int read_populate_todo(struct repository *r,
2693 struct todo_list *todo_list,
2694 struct replay_opts *opts)
2696 struct stat st;
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 = stat(todo_file, &st);
2705 if (res)
2706 return error(_("could not stat '%s'"), todo_file);
2707 fill_stat_data(&todo_list->stat, &st);
2709 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2710 if (res) {
2711 if (is_rebase_i(opts))
2712 return error(_("please fix this using "
2713 "'git rebase --edit-todo'."));
2714 return error(_("unusable instruction sheet: '%s'"), todo_file);
2717 if (!todo_list->nr &&
2718 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2719 return error(_("no commits parsed."));
2721 if (!is_rebase_i(opts)) {
2722 enum todo_command valid =
2723 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2724 int i;
2726 for (i = 0; i < todo_list->nr; i++)
2727 if (valid == todo_list->items[i].command)
2728 continue;
2729 else if (valid == TODO_PICK)
2730 return error(_("cannot cherry-pick during a revert."));
2731 else
2732 return error(_("cannot revert during a cherry-pick."));
2735 if (is_rebase_i(opts)) {
2736 struct todo_list done = TODO_LIST_INIT;
2738 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2739 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2740 todo_list->done_nr = count_commands(&done);
2741 else
2742 todo_list->done_nr = 0;
2744 todo_list->total_nr = todo_list->done_nr
2745 + count_commands(todo_list);
2746 todo_list_release(&done);
2748 todo_list_write_total_nr(todo_list);
2751 return 0;
2754 static int git_config_string_dup(char **dest,
2755 const char *var, const char *value)
2757 if (!value)
2758 return config_error_nonbool(var);
2759 free(*dest);
2760 *dest = xstrdup(value);
2761 return 0;
2764 static int populate_opts_cb(const char *key, const char *value, void *data)
2766 struct replay_opts *opts = data;
2767 int error_flag = 1;
2769 if (!value)
2770 error_flag = 0;
2771 else if (!strcmp(key, "options.no-commit"))
2772 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2773 else if (!strcmp(key, "options.edit"))
2774 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2775 else if (!strcmp(key, "options.allow-empty"))
2776 opts->allow_empty =
2777 git_config_bool_or_int(key, value, &error_flag);
2778 else if (!strcmp(key, "options.allow-empty-message"))
2779 opts->allow_empty_message =
2780 git_config_bool_or_int(key, value, &error_flag);
2781 else if (!strcmp(key, "options.keep-redundant-commits"))
2782 opts->keep_redundant_commits =
2783 git_config_bool_or_int(key, value, &error_flag);
2784 else if (!strcmp(key, "options.signoff"))
2785 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2786 else if (!strcmp(key, "options.record-origin"))
2787 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2788 else if (!strcmp(key, "options.allow-ff"))
2789 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2790 else if (!strcmp(key, "options.mainline"))
2791 opts->mainline = git_config_int(key, value);
2792 else if (!strcmp(key, "options.strategy"))
2793 git_config_string_dup(&opts->strategy, key, value);
2794 else if (!strcmp(key, "options.gpg-sign"))
2795 git_config_string_dup(&opts->gpg_sign, key, value);
2796 else if (!strcmp(key, "options.strategy-option")) {
2797 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2798 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2799 } else if (!strcmp(key, "options.allow-rerere-auto"))
2800 opts->allow_rerere_auto =
2801 git_config_bool_or_int(key, value, &error_flag) ?
2802 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2803 else if (!strcmp(key, "options.default-msg-cleanup")) {
2804 opts->explicit_cleanup = 1;
2805 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2806 } else
2807 return error(_("invalid key: %s"), key);
2809 if (!error_flag)
2810 return error(_("invalid value for %s: %s"), key, value);
2812 return 0;
2815 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2817 int i;
2818 char *strategy_opts_string = raw_opts;
2820 if (*strategy_opts_string == ' ')
2821 strategy_opts_string++;
2823 opts->xopts_nr = split_cmdline(strategy_opts_string,
2824 (const char ***)&opts->xopts);
2825 for (i = 0; i < opts->xopts_nr; i++) {
2826 const char *arg = opts->xopts[i];
2828 skip_prefix(arg, "--", &arg);
2829 opts->xopts[i] = xstrdup(arg);
2833 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2835 strbuf_reset(buf);
2836 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2837 return;
2838 opts->strategy = strbuf_detach(buf, NULL);
2839 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2840 return;
2842 parse_strategy_opts(opts, buf->buf);
2845 static int read_populate_opts(struct replay_opts *opts)
2847 if (is_rebase_i(opts)) {
2848 struct strbuf buf = STRBUF_INIT;
2849 int ret = 0;
2851 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2852 READ_ONELINER_SKIP_IF_EMPTY)) {
2853 if (!starts_with(buf.buf, "-S"))
2854 strbuf_reset(&buf);
2855 else {
2856 free(opts->gpg_sign);
2857 opts->gpg_sign = xstrdup(buf.buf + 2);
2859 strbuf_reset(&buf);
2862 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2863 READ_ONELINER_SKIP_IF_EMPTY)) {
2864 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2865 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2866 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2867 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2868 strbuf_reset(&buf);
2871 if (file_exists(rebase_path_verbose()))
2872 opts->verbose = 1;
2874 if (file_exists(rebase_path_quiet()))
2875 opts->quiet = 1;
2877 if (file_exists(rebase_path_signoff())) {
2878 opts->allow_ff = 0;
2879 opts->signoff = 1;
2882 if (file_exists(rebase_path_cdate_is_adate())) {
2883 opts->allow_ff = 0;
2884 opts->committer_date_is_author_date = 1;
2887 if (file_exists(rebase_path_ignore_date())) {
2888 opts->allow_ff = 0;
2889 opts->ignore_date = 1;
2892 if (file_exists(rebase_path_reschedule_failed_exec()))
2893 opts->reschedule_failed_exec = 1;
2894 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2895 opts->reschedule_failed_exec = 0;
2897 if (file_exists(rebase_path_drop_redundant_commits()))
2898 opts->drop_redundant_commits = 1;
2900 if (file_exists(rebase_path_keep_redundant_commits()))
2901 opts->keep_redundant_commits = 1;
2903 read_strategy_opts(opts, &buf);
2904 strbuf_reset(&buf);
2906 if (read_oneliner(&opts->current_fixups,
2907 rebase_path_current_fixups(),
2908 READ_ONELINER_SKIP_IF_EMPTY)) {
2909 const char *p = opts->current_fixups.buf;
2910 opts->current_fixup_count = 1;
2911 while ((p = strchr(p, '\n'))) {
2912 opts->current_fixup_count++;
2913 p++;
2917 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2918 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2919 ret = error(_("unusable squash-onto"));
2920 goto done_rebase_i;
2922 opts->have_squash_onto = 1;
2925 done_rebase_i:
2926 strbuf_release(&buf);
2927 return ret;
2930 if (!file_exists(git_path_opts_file()))
2931 return 0;
2933 * The function git_parse_source(), called from git_config_from_file(),
2934 * may die() in case of a syntactically incorrect file. We do not care
2935 * about this case, though, because we wrote that file ourselves, so we
2936 * are pretty certain that it is syntactically correct.
2938 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2939 return error(_("malformed options sheet: '%s'"),
2940 git_path_opts_file());
2941 return 0;
2944 static void write_strategy_opts(struct replay_opts *opts)
2946 int i;
2947 struct strbuf buf = STRBUF_INIT;
2949 for (i = 0; i < opts->xopts_nr; ++i)
2950 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2952 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2953 strbuf_release(&buf);
2956 int write_basic_state(struct replay_opts *opts, const char *head_name,
2957 struct commit *onto, const struct object_id *orig_head)
2959 if (head_name)
2960 write_file(rebase_path_head_name(), "%s\n", head_name);
2961 if (onto)
2962 write_file(rebase_path_onto(), "%s\n",
2963 oid_to_hex(&onto->object.oid));
2964 if (orig_head)
2965 write_file(rebase_path_orig_head(), "%s\n",
2966 oid_to_hex(orig_head));
2968 if (opts->quiet)
2969 write_file(rebase_path_quiet(), "%s", "");
2970 if (opts->verbose)
2971 write_file(rebase_path_verbose(), "%s", "");
2972 if (opts->strategy)
2973 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2974 if (opts->xopts_nr > 0)
2975 write_strategy_opts(opts);
2977 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2978 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2979 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2980 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2982 if (opts->gpg_sign)
2983 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2984 if (opts->signoff)
2985 write_file(rebase_path_signoff(), "--signoff\n");
2986 if (opts->drop_redundant_commits)
2987 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2988 if (opts->keep_redundant_commits)
2989 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2990 if (opts->committer_date_is_author_date)
2991 write_file(rebase_path_cdate_is_adate(), "%s", "");
2992 if (opts->ignore_date)
2993 write_file(rebase_path_ignore_date(), "%s", "");
2994 if (opts->reschedule_failed_exec)
2995 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2996 else
2997 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2999 return 0;
3002 static int walk_revs_populate_todo(struct todo_list *todo_list,
3003 struct replay_opts *opts)
3005 enum todo_command command = opts->action == REPLAY_PICK ?
3006 TODO_PICK : TODO_REVERT;
3007 const char *command_string = todo_command_info[command].str;
3008 const char *encoding;
3009 struct commit *commit;
3011 if (prepare_revs(opts))
3012 return -1;
3014 encoding = get_log_output_encoding();
3016 while ((commit = get_revision(opts->revs))) {
3017 struct todo_item *item = append_new_todo(todo_list);
3018 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3019 const char *subject;
3020 int subject_len;
3022 item->command = command;
3023 item->commit = commit;
3024 item->arg_offset = 0;
3025 item->arg_len = 0;
3026 item->offset_in_buf = todo_list->buf.len;
3027 subject_len = find_commit_subject(commit_buffer, &subject);
3028 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3029 short_commit_name(commit), subject_len, subject);
3030 unuse_commit_buffer(commit, commit_buffer);
3033 if (!todo_list->nr)
3034 return error(_("empty commit set passed"));
3036 return 0;
3039 static int create_seq_dir(struct repository *r)
3041 enum replay_action action;
3042 const char *in_progress_error = NULL;
3043 const char *in_progress_advice = NULL;
3044 unsigned int advise_skip =
3045 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3046 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3048 if (!sequencer_get_last_command(r, &action)) {
3049 switch (action) {
3050 case REPLAY_REVERT:
3051 in_progress_error = _("revert is already in progress");
3052 in_progress_advice =
3053 _("try \"git revert (--continue | %s--abort | --quit)\"");
3054 break;
3055 case REPLAY_PICK:
3056 in_progress_error = _("cherry-pick is already in progress");
3057 in_progress_advice =
3058 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3059 break;
3060 default:
3061 BUG("unexpected action in create_seq_dir");
3064 if (in_progress_error) {
3065 error("%s", in_progress_error);
3066 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3067 advise(in_progress_advice,
3068 advise_skip ? "--skip | " : "");
3069 return -1;
3071 if (mkdir(git_path_seq_dir(), 0777) < 0)
3072 return error_errno(_("could not create sequencer directory '%s'"),
3073 git_path_seq_dir());
3075 return 0;
3078 static int save_head(const char *head)
3080 struct lock_file head_lock = LOCK_INIT;
3081 struct strbuf buf = STRBUF_INIT;
3082 int fd;
3083 ssize_t written;
3085 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3086 if (fd < 0)
3087 return error_errno(_("could not lock HEAD"));
3088 strbuf_addf(&buf, "%s\n", head);
3089 written = write_in_full(fd, buf.buf, buf.len);
3090 strbuf_release(&buf);
3091 if (written < 0) {
3092 error_errno(_("could not write to '%s'"), git_path_head_file());
3093 rollback_lock_file(&head_lock);
3094 return -1;
3096 if (commit_lock_file(&head_lock) < 0)
3097 return error(_("failed to finalize '%s'"), git_path_head_file());
3098 return 0;
3101 static int rollback_is_safe(void)
3103 struct strbuf sb = STRBUF_INIT;
3104 struct object_id expected_head, actual_head;
3106 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3107 strbuf_trim(&sb);
3108 if (get_oid_hex(sb.buf, &expected_head)) {
3109 strbuf_release(&sb);
3110 die(_("could not parse %s"), git_path_abort_safety_file());
3112 strbuf_release(&sb);
3114 else if (errno == ENOENT)
3115 oidclr(&expected_head);
3116 else
3117 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3119 if (get_oid("HEAD", &actual_head))
3120 oidclr(&actual_head);
3122 return oideq(&actual_head, &expected_head);
3125 static int reset_merge(const struct object_id *oid)
3127 int ret;
3128 struct strvec argv = STRVEC_INIT;
3130 strvec_pushl(&argv, "reset", "--merge", NULL);
3132 if (!is_null_oid(oid))
3133 strvec_push(&argv, oid_to_hex(oid));
3135 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3136 strvec_clear(&argv);
3138 return ret;
3141 static int rollback_single_pick(struct repository *r)
3143 struct object_id head_oid;
3145 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3146 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3147 return error(_("no cherry-pick or revert in progress"));
3148 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3149 return error(_("cannot resolve HEAD"));
3150 if (is_null_oid(&head_oid))
3151 return error(_("cannot abort from a branch yet to be born"));
3152 return reset_merge(&head_oid);
3155 static int skip_single_pick(void)
3157 struct object_id head;
3159 if (read_ref_full("HEAD", 0, &head, NULL))
3160 return error(_("cannot resolve HEAD"));
3161 return reset_merge(&head);
3164 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3166 FILE *f;
3167 struct object_id oid;
3168 struct strbuf buf = STRBUF_INIT;
3169 const char *p;
3171 f = fopen(git_path_head_file(), "r");
3172 if (!f && errno == ENOENT) {
3174 * There is no multiple-cherry-pick in progress.
3175 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3176 * a single-cherry-pick in progress, abort that.
3178 return rollback_single_pick(r);
3180 if (!f)
3181 return error_errno(_("cannot open '%s'"), git_path_head_file());
3182 if (strbuf_getline_lf(&buf, f)) {
3183 error(_("cannot read '%s': %s"), git_path_head_file(),
3184 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3185 fclose(f);
3186 goto fail;
3188 fclose(f);
3189 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3190 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3191 git_path_head_file());
3192 goto fail;
3194 if (is_null_oid(&oid)) {
3195 error(_("cannot abort from a branch yet to be born"));
3196 goto fail;
3199 if (!rollback_is_safe()) {
3200 /* Do not error, just do not rollback */
3201 warning(_("You seem to have moved HEAD. "
3202 "Not rewinding, check your HEAD!"));
3203 } else
3204 if (reset_merge(&oid))
3205 goto fail;
3206 strbuf_release(&buf);
3207 return sequencer_remove_state(opts);
3208 fail:
3209 strbuf_release(&buf);
3210 return -1;
3213 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3215 enum replay_action action = -1;
3216 sequencer_get_last_command(r, &action);
3219 * Check whether the subcommand requested to skip the commit is actually
3220 * in progress and that it's safe to skip the commit.
3222 * opts->action tells us which subcommand requested to skip the commit.
3223 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3224 * action is in progress and we can skip the commit.
3226 * Otherwise we check that the last instruction was related to the
3227 * particular subcommand we're trying to execute and barf if that's not
3228 * the case.
3230 * Finally we check that the rollback is "safe", i.e., has the HEAD
3231 * moved? In this case, it doesn't make sense to "reset the merge" and
3232 * "skip the commit" as the user already handled this by committing. But
3233 * we'd not want to barf here, instead give advice on how to proceed. We
3234 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3235 * it gets removed when the user commits, so if it still exists we're
3236 * sure the user can't have committed before.
3238 switch (opts->action) {
3239 case REPLAY_REVERT:
3240 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3241 if (action != REPLAY_REVERT)
3242 return error(_("no revert in progress"));
3243 if (!rollback_is_safe())
3244 goto give_advice;
3246 break;
3247 case REPLAY_PICK:
3248 if (!refs_ref_exists(get_main_ref_store(r),
3249 "CHERRY_PICK_HEAD")) {
3250 if (action != REPLAY_PICK)
3251 return error(_("no cherry-pick in progress"));
3252 if (!rollback_is_safe())
3253 goto give_advice;
3255 break;
3256 default:
3257 BUG("unexpected action in sequencer_skip");
3260 if (skip_single_pick())
3261 return error(_("failed to skip the commit"));
3262 if (!is_directory(git_path_seq_dir()))
3263 return 0;
3265 return sequencer_continue(r, opts);
3267 give_advice:
3268 error(_("there is nothing to skip"));
3270 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3271 advise(_("have you committed already?\n"
3272 "try \"git %s --continue\""),
3273 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3275 return -1;
3278 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3280 struct lock_file todo_lock = LOCK_INIT;
3281 const char *todo_path = get_todo_path(opts);
3282 int next = todo_list->current, offset, fd;
3285 * rebase -i writes "git-rebase-todo" without the currently executing
3286 * command, appending it to "done" instead.
3288 if (is_rebase_i(opts))
3289 next++;
3291 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3292 if (fd < 0)
3293 return error_errno(_("could not lock '%s'"), todo_path);
3294 offset = get_item_line_offset(todo_list, next);
3295 if (write_in_full(fd, todo_list->buf.buf + offset,
3296 todo_list->buf.len - offset) < 0)
3297 return error_errno(_("could not write to '%s'"), todo_path);
3298 if (commit_lock_file(&todo_lock) < 0)
3299 return error(_("failed to finalize '%s'"), todo_path);
3301 if (is_rebase_i(opts) && next > 0) {
3302 const char *done = rebase_path_done();
3303 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3304 int ret = 0;
3306 if (fd < 0)
3307 return 0;
3308 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3309 get_item_line_length(todo_list, next - 1))
3310 < 0)
3311 ret = error_errno(_("could not write to '%s'"), done);
3312 if (close(fd) < 0)
3313 ret = error_errno(_("failed to finalize '%s'"), done);
3314 return ret;
3316 return 0;
3319 static int save_opts(struct replay_opts *opts)
3321 const char *opts_file = git_path_opts_file();
3322 int res = 0;
3324 if (opts->no_commit)
3325 res |= git_config_set_in_file_gently(opts_file,
3326 "options.no-commit", "true");
3327 if (opts->edit >= 0)
3328 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3329 opts->edit ? "true" : "false");
3330 if (opts->allow_empty)
3331 res |= git_config_set_in_file_gently(opts_file,
3332 "options.allow-empty", "true");
3333 if (opts->allow_empty_message)
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.allow-empty-message", "true");
3336 if (opts->keep_redundant_commits)
3337 res |= git_config_set_in_file_gently(opts_file,
3338 "options.keep-redundant-commits", "true");
3339 if (opts->signoff)
3340 res |= git_config_set_in_file_gently(opts_file,
3341 "options.signoff", "true");
3342 if (opts->record_origin)
3343 res |= git_config_set_in_file_gently(opts_file,
3344 "options.record-origin", "true");
3345 if (opts->allow_ff)
3346 res |= git_config_set_in_file_gently(opts_file,
3347 "options.allow-ff", "true");
3348 if (opts->mainline) {
3349 struct strbuf buf = STRBUF_INIT;
3350 strbuf_addf(&buf, "%d", opts->mainline);
3351 res |= git_config_set_in_file_gently(opts_file,
3352 "options.mainline", buf.buf);
3353 strbuf_release(&buf);
3355 if (opts->strategy)
3356 res |= git_config_set_in_file_gently(opts_file,
3357 "options.strategy", opts->strategy);
3358 if (opts->gpg_sign)
3359 res |= git_config_set_in_file_gently(opts_file,
3360 "options.gpg-sign", opts->gpg_sign);
3361 if (opts->xopts) {
3362 int i;
3363 for (i = 0; i < opts->xopts_nr; i++)
3364 res |= git_config_set_multivar_in_file_gently(opts_file,
3365 "options.strategy-option",
3366 opts->xopts[i], "^$", 0);
3368 if (opts->allow_rerere_auto)
3369 res |= git_config_set_in_file_gently(opts_file,
3370 "options.allow-rerere-auto",
3371 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3372 "true" : "false");
3374 if (opts->explicit_cleanup)
3375 res |= git_config_set_in_file_gently(opts_file,
3376 "options.default-msg-cleanup",
3377 describe_cleanup_mode(opts->default_msg_cleanup));
3378 return res;
3381 static int make_patch(struct repository *r,
3382 struct commit *commit,
3383 struct replay_opts *opts)
3385 struct strbuf buf = STRBUF_INIT;
3386 struct rev_info log_tree_opt;
3387 const char *subject;
3388 char hex[GIT_MAX_HEXSZ + 1];
3389 int res = 0;
3391 oid_to_hex_r(hex, &commit->object.oid);
3392 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3393 return -1;
3394 res |= write_rebase_head(&commit->object.oid);
3396 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3397 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3398 repo_init_revisions(r, &log_tree_opt, NULL);
3399 log_tree_opt.abbrev = 0;
3400 log_tree_opt.diff = 1;
3401 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3402 log_tree_opt.disable_stdin = 1;
3403 log_tree_opt.no_commit_id = 1;
3404 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3405 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3406 if (!log_tree_opt.diffopt.file)
3407 res |= error_errno(_("could not open '%s'"), buf.buf);
3408 else {
3409 res |= log_tree_commit(&log_tree_opt, commit);
3410 fclose(log_tree_opt.diffopt.file);
3412 strbuf_reset(&buf);
3414 strbuf_addf(&buf, "%s/message", get_dir(opts));
3415 if (!file_exists(buf.buf)) {
3416 const char *encoding = get_commit_output_encoding();
3417 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3418 find_commit_subject(commit_buffer, &subject);
3419 res |= write_message(subject, strlen(subject), buf.buf, 1);
3420 unuse_commit_buffer(commit, commit_buffer);
3422 strbuf_release(&buf);
3424 return res;
3427 static int intend_to_amend(void)
3429 struct object_id head;
3430 char *p;
3432 if (get_oid("HEAD", &head))
3433 return error(_("cannot read HEAD"));
3435 p = oid_to_hex(&head);
3436 return write_message(p, strlen(p), rebase_path_amend(), 1);
3439 static int error_with_patch(struct repository *r,
3440 struct commit *commit,
3441 const char *subject, int subject_len,
3442 struct replay_opts *opts,
3443 int exit_code, int to_amend)
3445 if (commit) {
3446 if (make_patch(r, commit, opts))
3447 return -1;
3448 } else if (copy_file(rebase_path_message(),
3449 git_path_merge_msg(r), 0666))
3450 return error(_("unable to copy '%s' to '%s'"),
3451 git_path_merge_msg(r), rebase_path_message());
3453 if (to_amend) {
3454 if (intend_to_amend())
3455 return -1;
3457 fprintf(stderr,
3458 _("You can amend the commit now, with\n"
3459 "\n"
3460 " git commit --amend %s\n"
3461 "\n"
3462 "Once you are satisfied with your changes, run\n"
3463 "\n"
3464 " git rebase --continue\n"),
3465 gpg_sign_opt_quoted(opts));
3466 } else if (exit_code) {
3467 if (commit)
3468 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3469 short_commit_name(commit), subject_len, subject);
3470 else
3472 * We don't have the hash of the parent so
3473 * just print the line from the todo file.
3475 fprintf_ln(stderr, _("Could not merge %.*s"),
3476 subject_len, subject);
3479 return exit_code;
3482 static int error_failed_squash(struct repository *r,
3483 struct commit *commit,
3484 struct replay_opts *opts,
3485 int subject_len,
3486 const char *subject)
3488 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3489 return error(_("could not copy '%s' to '%s'"),
3490 rebase_path_squash_msg(), rebase_path_message());
3491 unlink(git_path_merge_msg(r));
3492 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3493 return error(_("could not copy '%s' to '%s'"),
3494 rebase_path_message(),
3495 git_path_merge_msg(r));
3496 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3499 static int do_exec(struct repository *r, const char *command_line)
3501 struct strvec child_env = STRVEC_INIT;
3502 const char *child_argv[] = { NULL, NULL };
3503 int dirty, status;
3505 fprintf(stderr, _("Executing: %s\n"), command_line);
3506 child_argv[0] = command_line;
3507 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3508 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3509 absolute_path(get_git_work_tree()));
3510 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3511 child_env.v);
3513 /* force re-reading of the cache */
3514 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3515 return error(_("could not read index"));
3517 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3519 if (status) {
3520 warning(_("execution failed: %s\n%s"
3521 "You can fix the problem, and then run\n"
3522 "\n"
3523 " git rebase --continue\n"
3524 "\n"),
3525 command_line,
3526 dirty ? N_("and made changes to the index and/or the "
3527 "working tree\n") : "");
3528 if (status == 127)
3529 /* command not found */
3530 status = 1;
3531 } else if (dirty) {
3532 warning(_("execution succeeded: %s\nbut "
3533 "left changes to the index and/or the working tree\n"
3534 "Commit or stash your changes, and then run\n"
3535 "\n"
3536 " git rebase --continue\n"
3537 "\n"), command_line);
3538 status = 1;
3541 strvec_clear(&child_env);
3543 return status;
3546 __attribute__((format (printf, 2, 3)))
3547 static int safe_append(const char *filename, const char *fmt, ...)
3549 va_list ap;
3550 struct lock_file lock = LOCK_INIT;
3551 int fd = hold_lock_file_for_update(&lock, filename,
3552 LOCK_REPORT_ON_ERROR);
3553 struct strbuf buf = STRBUF_INIT;
3555 if (fd < 0)
3556 return -1;
3558 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3559 error_errno(_("could not read '%s'"), filename);
3560 rollback_lock_file(&lock);
3561 return -1;
3563 strbuf_complete(&buf, '\n');
3564 va_start(ap, fmt);
3565 strbuf_vaddf(&buf, fmt, ap);
3566 va_end(ap);
3568 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3569 error_errno(_("could not write to '%s'"), filename);
3570 strbuf_release(&buf);
3571 rollback_lock_file(&lock);
3572 return -1;
3574 if (commit_lock_file(&lock) < 0) {
3575 strbuf_release(&buf);
3576 rollback_lock_file(&lock);
3577 return error(_("failed to finalize '%s'"), filename);
3580 strbuf_release(&buf);
3581 return 0;
3584 static int do_label(struct repository *r, const char *name, int len)
3586 struct ref_store *refs = get_main_ref_store(r);
3587 struct ref_transaction *transaction;
3588 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3589 struct strbuf msg = STRBUF_INIT;
3590 int ret = 0;
3591 struct object_id head_oid;
3593 if (len == 1 && *name == '#')
3594 return error(_("illegal label name: '%.*s'"), len, name);
3596 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3597 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3599 transaction = ref_store_transaction_begin(refs, &err);
3600 if (!transaction) {
3601 error("%s", err.buf);
3602 ret = -1;
3603 } else if (get_oid("HEAD", &head_oid)) {
3604 error(_("could not read HEAD"));
3605 ret = -1;
3606 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3607 NULL, 0, msg.buf, &err) < 0 ||
3608 ref_transaction_commit(transaction, &err)) {
3609 error("%s", err.buf);
3610 ret = -1;
3612 ref_transaction_free(transaction);
3613 strbuf_release(&err);
3614 strbuf_release(&msg);
3616 if (!ret)
3617 ret = safe_append(rebase_path_refs_to_delete(),
3618 "%s\n", ref_name.buf);
3619 strbuf_release(&ref_name);
3621 return ret;
3624 __attribute__((format (printf, 3, 4)))
3625 static const char *reflog_message(struct replay_opts *opts,
3626 const char *sub_action, const char *fmt, ...)
3628 va_list ap;
3629 static struct strbuf buf = STRBUF_INIT;
3630 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3632 va_start(ap, fmt);
3633 strbuf_reset(&buf);
3634 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3635 if (sub_action)
3636 strbuf_addf(&buf, " (%s)", sub_action);
3637 if (fmt) {
3638 strbuf_addstr(&buf, ": ");
3639 strbuf_vaddf(&buf, fmt, ap);
3641 va_end(ap);
3643 return buf.buf;
3646 static int do_reset(struct repository *r,
3647 const char *name, int len,
3648 struct replay_opts *opts)
3650 struct strbuf ref_name = STRBUF_INIT;
3651 struct object_id oid;
3652 struct lock_file lock = LOCK_INIT;
3653 struct tree_desc desc;
3654 struct tree *tree;
3655 struct unpack_trees_options unpack_tree_opts;
3656 int ret = 0;
3658 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3659 return -1;
3661 if (len == 10 && !strncmp("[new root]", name, len)) {
3662 if (!opts->have_squash_onto) {
3663 const char *hex;
3664 if (commit_tree("", 0, the_hash_algo->empty_tree,
3665 NULL, &opts->squash_onto,
3666 NULL, NULL))
3667 return error(_("writing fake root commit"));
3668 opts->have_squash_onto = 1;
3669 hex = oid_to_hex(&opts->squash_onto);
3670 if (write_message(hex, strlen(hex),
3671 rebase_path_squash_onto(), 0))
3672 return error(_("writing squash-onto"));
3674 oidcpy(&oid, &opts->squash_onto);
3675 } else {
3676 int i;
3678 /* Determine the length of the label */
3679 for (i = 0; i < len; i++)
3680 if (isspace(name[i]))
3681 break;
3682 len = i;
3684 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3685 if (get_oid(ref_name.buf, &oid) &&
3686 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3687 error(_("could not read '%s'"), ref_name.buf);
3688 rollback_lock_file(&lock);
3689 strbuf_release(&ref_name);
3690 return -1;
3694 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3695 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3696 unpack_tree_opts.head_idx = 1;
3697 unpack_tree_opts.src_index = r->index;
3698 unpack_tree_opts.dst_index = r->index;
3699 unpack_tree_opts.fn = oneway_merge;
3700 unpack_tree_opts.merge = 1;
3701 unpack_tree_opts.update = 1;
3702 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3704 if (repo_read_index_unmerged(r)) {
3705 rollback_lock_file(&lock);
3706 strbuf_release(&ref_name);
3707 return error_resolve_conflict(_(action_name(opts)));
3710 if (!fill_tree_descriptor(r, &desc, &oid)) {
3711 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3712 rollback_lock_file(&lock);
3713 free((void *)desc.buffer);
3714 strbuf_release(&ref_name);
3715 return -1;
3718 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3719 rollback_lock_file(&lock);
3720 free((void *)desc.buffer);
3721 strbuf_release(&ref_name);
3722 return -1;
3725 tree = parse_tree_indirect(&oid);
3726 prime_cache_tree(r, r->index, tree);
3728 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3729 ret = error(_("could not write index"));
3730 free((void *)desc.buffer);
3732 if (!ret)
3733 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3734 len, name), "HEAD", &oid,
3735 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3737 strbuf_release(&ref_name);
3738 return ret;
3741 static struct commit *lookup_label(const char *label, int len,
3742 struct strbuf *buf)
3744 struct commit *commit;
3746 strbuf_reset(buf);
3747 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3748 commit = lookup_commit_reference_by_name(buf->buf);
3749 if (!commit) {
3750 /* fall back to non-rewritten ref or commit */
3751 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3752 commit = lookup_commit_reference_by_name(buf->buf);
3755 if (!commit)
3756 error(_("could not resolve '%s'"), buf->buf);
3758 return commit;
3761 static int do_merge(struct repository *r,
3762 struct commit *commit,
3763 const char *arg, int arg_len,
3764 int flags, int *check_todo, struct replay_opts *opts)
3766 int run_commit_flags = 0;
3767 struct strbuf ref_name = STRBUF_INIT;
3768 struct commit *head_commit, *merge_commit, *i;
3769 struct commit_list *bases, *j, *reversed = NULL;
3770 struct commit_list *to_merge = NULL, **tail = &to_merge;
3771 const char *strategy = !opts->xopts_nr &&
3772 (!opts->strategy ||
3773 !strcmp(opts->strategy, "recursive") ||
3774 !strcmp(opts->strategy, "ort")) ?
3775 NULL : opts->strategy;
3776 struct merge_options o;
3777 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3778 static struct lock_file lock;
3779 const char *p;
3781 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3782 ret = -1;
3783 goto leave_merge;
3786 head_commit = lookup_commit_reference_by_name("HEAD");
3787 if (!head_commit) {
3788 ret = error(_("cannot merge without a current revision"));
3789 goto leave_merge;
3793 * For octopus merges, the arg starts with the list of revisions to be
3794 * merged. The list is optionally followed by '#' and the oneline.
3796 merge_arg_len = oneline_offset = arg_len;
3797 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3798 if (!*p)
3799 break;
3800 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3801 p += 1 + strspn(p + 1, " \t\n");
3802 oneline_offset = p - arg;
3803 break;
3805 k = strcspn(p, " \t\n");
3806 if (!k)
3807 continue;
3808 merge_commit = lookup_label(p, k, &ref_name);
3809 if (!merge_commit) {
3810 ret = error(_("unable to parse '%.*s'"), k, p);
3811 goto leave_merge;
3813 tail = &commit_list_insert(merge_commit, tail)->next;
3814 p += k;
3815 merge_arg_len = p - arg;
3818 if (!to_merge) {
3819 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3820 goto leave_merge;
3823 if (opts->have_squash_onto &&
3824 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3826 * When the user tells us to "merge" something into a
3827 * "[new root]", let's simply fast-forward to the merge head.
3829 rollback_lock_file(&lock);
3830 if (to_merge->next)
3831 ret = error(_("octopus merge cannot be executed on "
3832 "top of a [new root]"));
3833 else
3834 ret = fast_forward_to(r, &to_merge->item->object.oid,
3835 &head_commit->object.oid, 0,
3836 opts);
3837 goto leave_merge;
3841 * If HEAD is not identical to the first parent of the original merge
3842 * commit, we cannot fast-forward.
3844 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3845 oideq(&commit->parents->item->object.oid,
3846 &head_commit->object.oid);
3849 * If any merge head is different from the original one, we cannot
3850 * fast-forward.
3852 if (can_fast_forward) {
3853 struct commit_list *p = commit->parents->next;
3855 for (j = to_merge; j && p; j = j->next, p = p->next)
3856 if (!oideq(&j->item->object.oid,
3857 &p->item->object.oid)) {
3858 can_fast_forward = 0;
3859 break;
3862 * If the number of merge heads differs from the original merge
3863 * commit, we cannot fast-forward.
3865 if (j || p)
3866 can_fast_forward = 0;
3869 if (can_fast_forward) {
3870 rollback_lock_file(&lock);
3871 ret = fast_forward_to(r, &commit->object.oid,
3872 &head_commit->object.oid, 0, opts);
3873 if (flags & TODO_EDIT_MERGE_MSG)
3874 goto fast_forward_edit;
3876 goto leave_merge;
3879 if (commit) {
3880 const char *encoding = get_commit_output_encoding();
3881 const char *message = logmsg_reencode(commit, NULL, encoding);
3882 const char *body;
3883 int len;
3885 if (!message) {
3886 ret = error(_("could not get commit message of '%s'"),
3887 oid_to_hex(&commit->object.oid));
3888 goto leave_merge;
3890 write_author_script(message);
3891 find_commit_subject(message, &body);
3892 len = strlen(body);
3893 ret = write_message(body, len, git_path_merge_msg(r), 0);
3894 unuse_commit_buffer(commit, message);
3895 if (ret) {
3896 error_errno(_("could not write '%s'"),
3897 git_path_merge_msg(r));
3898 goto leave_merge;
3900 } else {
3901 struct strbuf buf = STRBUF_INIT;
3902 int len;
3904 strbuf_addf(&buf, "author %s", git_author_info(0));
3905 write_author_script(buf.buf);
3906 strbuf_reset(&buf);
3908 if (oneline_offset < arg_len) {
3909 p = arg + oneline_offset;
3910 len = arg_len - oneline_offset;
3911 } else {
3912 strbuf_addf(&buf, "Merge %s '%.*s'",
3913 to_merge->next ? "branches" : "branch",
3914 merge_arg_len, arg);
3915 p = buf.buf;
3916 len = buf.len;
3919 ret = write_message(p, len, git_path_merge_msg(r), 0);
3920 strbuf_release(&buf);
3921 if (ret) {
3922 error_errno(_("could not write '%s'"),
3923 git_path_merge_msg(r));
3924 goto leave_merge;
3928 if (strategy || to_merge->next) {
3929 /* Octopus merge */
3930 struct child_process cmd = CHILD_PROCESS_INIT;
3932 if (read_env_script(&cmd.env_array)) {
3933 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3935 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3936 goto leave_merge;
3939 if (opts->committer_date_is_author_date)
3940 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3941 opts->ignore_date ?
3942 "" :
3943 author_date_from_env_array(&cmd.env_array));
3944 if (opts->ignore_date)
3945 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3947 cmd.git_cmd = 1;
3948 strvec_push(&cmd.args, "merge");
3949 strvec_push(&cmd.args, "-s");
3950 if (!strategy)
3951 strvec_push(&cmd.args, "octopus");
3952 else {
3953 strvec_push(&cmd.args, strategy);
3954 for (k = 0; k < opts->xopts_nr; k++)
3955 strvec_pushf(&cmd.args,
3956 "-X%s", opts->xopts[k]);
3958 if (!(flags & TODO_EDIT_MERGE_MSG))
3959 strvec_push(&cmd.args, "--no-edit");
3960 else
3961 strvec_push(&cmd.args, "--edit");
3962 strvec_push(&cmd.args, "--no-ff");
3963 strvec_push(&cmd.args, "--no-log");
3964 strvec_push(&cmd.args, "--no-stat");
3965 strvec_push(&cmd.args, "-F");
3966 strvec_push(&cmd.args, git_path_merge_msg(r));
3967 if (opts->gpg_sign)
3968 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3969 else
3970 strvec_push(&cmd.args, "--no-gpg-sign");
3972 /* Add the tips to be merged */
3973 for (j = to_merge; j; j = j->next)
3974 strvec_push(&cmd.args,
3975 oid_to_hex(&j->item->object.oid));
3977 strbuf_release(&ref_name);
3978 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3979 NULL, 0);
3980 rollback_lock_file(&lock);
3982 ret = run_command(&cmd);
3984 /* force re-reading of the cache */
3985 if (!ret && (discard_index(r->index) < 0 ||
3986 repo_read_index(r) < 0))
3987 ret = error(_("could not read index"));
3988 goto leave_merge;
3991 merge_commit = to_merge->item;
3992 bases = get_merge_bases(head_commit, merge_commit);
3993 if (bases && oideq(&merge_commit->object.oid,
3994 &bases->item->object.oid)) {
3995 ret = 0;
3996 /* skip merging an ancestor of HEAD */
3997 goto leave_merge;
4000 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4001 git_path_merge_head(r), 0);
4002 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4004 for (j = bases; j; j = j->next)
4005 commit_list_insert(j->item, &reversed);
4006 free_commit_list(bases);
4008 repo_read_index(r);
4009 init_merge_options(&o, r);
4010 o.branch1 = "HEAD";
4011 o.branch2 = ref_name.buf;
4012 o.buffer_output = 2;
4014 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4016 * TODO: Should use merge_incore_recursive() and
4017 * merge_switch_to_result(), skipping the call to
4018 * merge_switch_to_result() when we don't actually need to
4019 * update the index and working copy immediately.
4021 ret = merge_ort_recursive(&o,
4022 head_commit, merge_commit, reversed,
4023 &i);
4024 } else {
4025 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4026 &i);
4028 if (ret <= 0)
4029 fputs(o.obuf.buf, stdout);
4030 strbuf_release(&o.obuf);
4031 if (ret < 0) {
4032 error(_("could not even attempt to merge '%.*s'"),
4033 merge_arg_len, arg);
4034 goto leave_merge;
4037 * The return value of merge_recursive() is 1 on clean, and 0 on
4038 * unclean merge.
4040 * Let's reverse that, so that do_merge() returns 0 upon success and
4041 * 1 upon failed merge (keeping the return value -1 for the cases where
4042 * we will want to reschedule the `merge` command).
4044 ret = !ret;
4046 if (r->index->cache_changed &&
4047 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4048 ret = error(_("merge: Unable to write new index file"));
4049 goto leave_merge;
4052 rollback_lock_file(&lock);
4053 if (ret)
4054 repo_rerere(r, opts->allow_rerere_auto);
4055 else
4057 * In case of problems, we now want to return a positive
4058 * value (a negative one would indicate that the `merge`
4059 * command needs to be rescheduled).
4061 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4062 run_commit_flags);
4064 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4065 fast_forward_edit:
4066 *check_todo = 1;
4067 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4068 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4072 leave_merge:
4073 strbuf_release(&ref_name);
4074 rollback_lock_file(&lock);
4075 free_commit_list(to_merge);
4076 return ret;
4079 static int is_final_fixup(struct todo_list *todo_list)
4081 int i = todo_list->current;
4083 if (!is_fixup(todo_list->items[i].command))
4084 return 0;
4086 while (++i < todo_list->nr)
4087 if (is_fixup(todo_list->items[i].command))
4088 return 0;
4089 else if (!is_noop(todo_list->items[i].command))
4090 break;
4091 return 1;
4094 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4096 int i;
4098 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4099 if (!is_noop(todo_list->items[i].command))
4100 return todo_list->items[i].command;
4102 return -1;
4105 void create_autostash(struct repository *r, const char *path,
4106 const char *default_reflog_action)
4108 struct strbuf buf = STRBUF_INIT;
4109 struct lock_file lock_file = LOCK_INIT;
4110 int fd;
4112 fd = repo_hold_locked_index(r, &lock_file, 0);
4113 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4114 if (0 <= fd)
4115 repo_update_index_if_able(r, &lock_file);
4116 rollback_lock_file(&lock_file);
4118 if (has_unstaged_changes(r, 1) ||
4119 has_uncommitted_changes(r, 1)) {
4120 struct child_process stash = CHILD_PROCESS_INIT;
4121 struct object_id oid;
4123 strvec_pushl(&stash.args,
4124 "stash", "create", "autostash", NULL);
4125 stash.git_cmd = 1;
4126 stash.no_stdin = 1;
4127 strbuf_reset(&buf);
4128 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4129 die(_("Cannot autostash"));
4130 strbuf_trim_trailing_newline(&buf);
4131 if (get_oid(buf.buf, &oid))
4132 die(_("Unexpected stash response: '%s'"),
4133 buf.buf);
4134 strbuf_reset(&buf);
4135 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4137 if (safe_create_leading_directories_const(path))
4138 die(_("Could not create directory for '%s'"),
4139 path);
4140 write_file(path, "%s", oid_to_hex(&oid));
4141 printf(_("Created autostash: %s\n"), buf.buf);
4142 if (reset_head(r, NULL, "reset --hard",
4143 NULL, RESET_HEAD_HARD, NULL, NULL,
4144 default_reflog_action) < 0)
4145 die(_("could not reset --hard"));
4147 if (discard_index(r->index) < 0 ||
4148 repo_read_index(r) < 0)
4149 die(_("could not read index"));
4151 strbuf_release(&buf);
4154 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4156 struct child_process child = CHILD_PROCESS_INIT;
4157 int ret = 0;
4159 if (attempt_apply) {
4160 child.git_cmd = 1;
4161 child.no_stdout = 1;
4162 child.no_stderr = 1;
4163 strvec_push(&child.args, "stash");
4164 strvec_push(&child.args, "apply");
4165 strvec_push(&child.args, stash_oid);
4166 ret = run_command(&child);
4169 if (attempt_apply && !ret)
4170 fprintf(stderr, _("Applied autostash.\n"));
4171 else {
4172 struct child_process store = CHILD_PROCESS_INIT;
4174 store.git_cmd = 1;
4175 strvec_push(&store.args, "stash");
4176 strvec_push(&store.args, "store");
4177 strvec_push(&store.args, "-m");
4178 strvec_push(&store.args, "autostash");
4179 strvec_push(&store.args, "-q");
4180 strvec_push(&store.args, stash_oid);
4181 if (run_command(&store))
4182 ret = error(_("cannot store %s"), stash_oid);
4183 else
4184 fprintf(stderr,
4185 _("%s\n"
4186 "Your changes are safe in the stash.\n"
4187 "You can run \"git stash pop\" or"
4188 " \"git stash drop\" at any time.\n"),
4189 attempt_apply ?
4190 _("Applying autostash resulted in conflicts.") :
4191 _("Autostash exists; creating a new stash entry."));
4194 return ret;
4197 static int apply_save_autostash(const char *path, int attempt_apply)
4199 struct strbuf stash_oid = STRBUF_INIT;
4200 int ret = 0;
4202 if (!read_oneliner(&stash_oid, path,
4203 READ_ONELINER_SKIP_IF_EMPTY)) {
4204 strbuf_release(&stash_oid);
4205 return 0;
4207 strbuf_trim(&stash_oid);
4209 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4211 unlink(path);
4212 strbuf_release(&stash_oid);
4213 return ret;
4216 int save_autostash(const char *path)
4218 return apply_save_autostash(path, 0);
4221 int apply_autostash(const char *path)
4223 return apply_save_autostash(path, 1);
4226 int apply_autostash_oid(const char *stash_oid)
4228 return apply_save_autostash_oid(stash_oid, 1);
4231 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4232 const char *commit, const char *action)
4234 struct child_process cmd = CHILD_PROCESS_INIT;
4235 int ret;
4237 cmd.git_cmd = 1;
4239 strvec_push(&cmd.args, "checkout");
4240 strvec_push(&cmd.args, commit);
4241 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4243 if (opts->verbose)
4244 ret = run_command(&cmd);
4245 else
4246 ret = run_command_silent_on_success(&cmd);
4248 if (!ret)
4249 discard_index(r->index);
4251 return ret;
4254 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4255 const char *onto_name, const struct object_id *onto,
4256 const struct object_id *orig_head)
4258 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4260 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4261 apply_autostash(rebase_path_autostash());
4262 sequencer_remove_state(opts);
4263 return error(_("could not detach HEAD"));
4266 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4269 static int stopped_at_head(struct repository *r)
4271 struct object_id head;
4272 struct commit *commit;
4273 struct commit_message message;
4275 if (get_oid("HEAD", &head) ||
4276 !(commit = lookup_commit(r, &head)) ||
4277 parse_commit(commit) || get_message(commit, &message))
4278 fprintf(stderr, _("Stopped at HEAD\n"));
4279 else {
4280 fprintf(stderr, _("Stopped at %s\n"), message.label);
4281 free_message(commit, &message);
4283 return 0;
4287 static const char rescheduled_advice[] =
4288 N_("Could not execute the todo command\n"
4289 "\n"
4290 " %.*s"
4291 "\n"
4292 "It has been rescheduled; To edit the command before continuing, please\n"
4293 "edit the todo list first:\n"
4294 "\n"
4295 " git rebase --edit-todo\n"
4296 " git rebase --continue\n");
4298 static int pick_commits(struct repository *r,
4299 struct todo_list *todo_list,
4300 struct replay_opts *opts)
4302 int res = 0, reschedule = 0;
4303 char *prev_reflog_action;
4305 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4306 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4307 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4308 if (opts->allow_ff)
4309 assert(!(opts->signoff || opts->no_commit ||
4310 opts->record_origin || should_edit(opts) ||
4311 opts->committer_date_is_author_date ||
4312 opts->ignore_date));
4313 if (read_and_refresh_cache(r, opts))
4314 return -1;
4316 while (todo_list->current < todo_list->nr) {
4317 struct todo_item *item = todo_list->items + todo_list->current;
4318 const char *arg = todo_item_get_arg(todo_list, item);
4319 int check_todo = 0;
4321 if (save_todo(todo_list, opts))
4322 return -1;
4323 if (is_rebase_i(opts)) {
4324 if (item->command != TODO_COMMENT) {
4325 FILE *f = fopen(rebase_path_msgnum(), "w");
4327 todo_list->done_nr++;
4329 if (f) {
4330 fprintf(f, "%d\n", todo_list->done_nr);
4331 fclose(f);
4333 if (!opts->quiet)
4334 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4335 todo_list->done_nr,
4336 todo_list->total_nr,
4337 opts->verbose ? "\n" : "\r");
4339 unlink(rebase_path_message());
4340 unlink(rebase_path_author_script());
4341 unlink(rebase_path_stopped_sha());
4342 unlink(rebase_path_amend());
4343 unlink(git_path_merge_head(r));
4344 unlink(git_path_auto_merge(r));
4345 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4347 if (item->command == TODO_BREAK) {
4348 if (!opts->verbose)
4349 term_clear_line();
4350 return stopped_at_head(r);
4353 if (item->command <= TODO_SQUASH) {
4354 if (is_rebase_i(opts))
4355 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4356 command_to_string(item->command), NULL),
4358 res = do_pick_commit(r, item, opts,
4359 is_final_fixup(todo_list),
4360 &check_todo);
4361 if (is_rebase_i(opts))
4362 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4363 if (is_rebase_i(opts) && res < 0) {
4364 /* Reschedule */
4365 advise(_(rescheduled_advice),
4366 get_item_line_length(todo_list,
4367 todo_list->current),
4368 get_item_line(todo_list,
4369 todo_list->current));
4370 todo_list->current--;
4371 if (save_todo(todo_list, opts))
4372 return -1;
4374 if (item->command == TODO_EDIT) {
4375 struct commit *commit = item->commit;
4376 if (!res) {
4377 if (!opts->verbose)
4378 term_clear_line();
4379 fprintf(stderr,
4380 _("Stopped at %s... %.*s\n"),
4381 short_commit_name(commit),
4382 item->arg_len, arg);
4384 return error_with_patch(r, commit,
4385 arg, item->arg_len, opts, res, !res);
4387 if (is_rebase_i(opts) && !res)
4388 record_in_rewritten(&item->commit->object.oid,
4389 peek_command(todo_list, 1));
4390 if (res && is_fixup(item->command)) {
4391 if (res == 1)
4392 intend_to_amend();
4393 return error_failed_squash(r, item->commit, opts,
4394 item->arg_len, arg);
4395 } else if (res && is_rebase_i(opts) && item->commit) {
4396 int to_amend = 0;
4397 struct object_id oid;
4400 * If we are rewording and have either
4401 * fast-forwarded already, or are about to
4402 * create a new root commit, we want to amend,
4403 * otherwise we do not.
4405 if (item->command == TODO_REWORD &&
4406 !get_oid("HEAD", &oid) &&
4407 (oideq(&item->commit->object.oid, &oid) ||
4408 (opts->have_squash_onto &&
4409 oideq(&opts->squash_onto, &oid))))
4410 to_amend = 1;
4412 return res | error_with_patch(r, item->commit,
4413 arg, item->arg_len, opts,
4414 res, to_amend);
4416 } else if (item->command == TODO_EXEC) {
4417 char *end_of_arg = (char *)(arg + item->arg_len);
4418 int saved = *end_of_arg;
4420 if (!opts->verbose)
4421 term_clear_line();
4422 *end_of_arg = '\0';
4423 res = do_exec(r, arg);
4424 *end_of_arg = saved;
4426 if (res) {
4427 if (opts->reschedule_failed_exec)
4428 reschedule = 1;
4430 check_todo = 1;
4431 } else if (item->command == TODO_LABEL) {
4432 if ((res = do_label(r, arg, item->arg_len)))
4433 reschedule = 1;
4434 } else if (item->command == TODO_RESET) {
4435 if ((res = do_reset(r, arg, item->arg_len, opts)))
4436 reschedule = 1;
4437 } else if (item->command == TODO_MERGE) {
4438 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4439 item->flags, &check_todo, opts)) < 0)
4440 reschedule = 1;
4441 else if (item->commit)
4442 record_in_rewritten(&item->commit->object.oid,
4443 peek_command(todo_list, 1));
4444 if (res > 0)
4445 /* failed with merge conflicts */
4446 return error_with_patch(r, item->commit,
4447 arg, item->arg_len,
4448 opts, res, 0);
4449 } else if (!is_noop(item->command))
4450 return error(_("unknown command %d"), item->command);
4452 if (reschedule) {
4453 advise(_(rescheduled_advice),
4454 get_item_line_length(todo_list,
4455 todo_list->current),
4456 get_item_line(todo_list, todo_list->current));
4457 todo_list->current--;
4458 if (save_todo(todo_list, opts))
4459 return -1;
4460 if (item->commit)
4461 return error_with_patch(r,
4462 item->commit,
4463 arg, item->arg_len,
4464 opts, res, 0);
4465 } else if (is_rebase_i(opts) && check_todo && !res) {
4466 struct stat st;
4468 if (stat(get_todo_path(opts), &st)) {
4469 res = error_errno(_("could not stat '%s'"),
4470 get_todo_path(opts));
4471 } else if (match_stat_data(&todo_list->stat, &st)) {
4472 /* Reread the todo file if it has changed. */
4473 todo_list_release(todo_list);
4474 if (read_populate_todo(r, todo_list, opts))
4475 res = -1; /* message was printed */
4476 /* `current` will be incremented below */
4477 todo_list->current = -1;
4481 todo_list->current++;
4482 if (res)
4483 return res;
4486 if (is_rebase_i(opts)) {
4487 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4488 struct stat st;
4490 /* Stopped in the middle, as planned? */
4491 if (todo_list->current < todo_list->nr)
4492 return 0;
4494 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4495 starts_with(head_ref.buf, "refs/")) {
4496 const char *msg;
4497 struct object_id head, orig;
4498 int res;
4500 if (get_oid("HEAD", &head)) {
4501 res = error(_("cannot read HEAD"));
4502 cleanup_head_ref:
4503 strbuf_release(&head_ref);
4504 strbuf_release(&buf);
4505 return res;
4507 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4508 get_oid_hex(buf.buf, &orig)) {
4509 res = error(_("could not read orig-head"));
4510 goto cleanup_head_ref;
4512 strbuf_reset(&buf);
4513 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4514 res = error(_("could not read 'onto'"));
4515 goto cleanup_head_ref;
4517 msg = reflog_message(opts, "finish", "%s onto %s",
4518 head_ref.buf, buf.buf);
4519 if (update_ref(msg, head_ref.buf, &head, &orig,
4520 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4521 res = error(_("could not update %s"),
4522 head_ref.buf);
4523 goto cleanup_head_ref;
4525 msg = reflog_message(opts, "finish", "returning to %s",
4526 head_ref.buf);
4527 if (create_symref("HEAD", head_ref.buf, msg)) {
4528 res = error(_("could not update HEAD to %s"),
4529 head_ref.buf);
4530 goto cleanup_head_ref;
4532 strbuf_reset(&buf);
4535 if (opts->verbose) {
4536 struct rev_info log_tree_opt;
4537 struct object_id orig, head;
4539 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4540 repo_init_revisions(r, &log_tree_opt, NULL);
4541 log_tree_opt.diff = 1;
4542 log_tree_opt.diffopt.output_format =
4543 DIFF_FORMAT_DIFFSTAT;
4544 log_tree_opt.disable_stdin = 1;
4546 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4547 !get_oid(buf.buf, &orig) &&
4548 !get_oid("HEAD", &head)) {
4549 diff_tree_oid(&orig, &head, "",
4550 &log_tree_opt.diffopt);
4551 log_tree_diff_flush(&log_tree_opt);
4554 flush_rewritten_pending();
4555 if (!stat(rebase_path_rewritten_list(), &st) &&
4556 st.st_size > 0) {
4557 struct child_process child = CHILD_PROCESS_INIT;
4558 const char *post_rewrite_hook =
4559 find_hook("post-rewrite");
4561 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4562 child.git_cmd = 1;
4563 strvec_push(&child.args, "notes");
4564 strvec_push(&child.args, "copy");
4565 strvec_push(&child.args, "--for-rewrite=rebase");
4566 /* we don't care if this copying failed */
4567 run_command(&child);
4569 if (post_rewrite_hook) {
4570 struct child_process hook = CHILD_PROCESS_INIT;
4572 hook.in = open(rebase_path_rewritten_list(),
4573 O_RDONLY);
4574 hook.stdout_to_stderr = 1;
4575 hook.trace2_hook_name = "post-rewrite";
4576 strvec_push(&hook.args, post_rewrite_hook);
4577 strvec_push(&hook.args, "rebase");
4578 /* we don't care if this hook failed */
4579 run_command(&hook);
4582 apply_autostash(rebase_path_autostash());
4584 if (!opts->quiet) {
4585 if (!opts->verbose)
4586 term_clear_line();
4587 fprintf(stderr,
4588 _("Successfully rebased and updated %s.\n"),
4589 head_ref.buf);
4592 strbuf_release(&buf);
4593 strbuf_release(&head_ref);
4597 * Sequence of picks finished successfully; cleanup by
4598 * removing the .git/sequencer directory
4600 return sequencer_remove_state(opts);
4603 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4605 struct strvec argv = STRVEC_INIT;
4606 int ret;
4608 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4609 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4610 return error(_("no cherry-pick or revert in progress"));
4612 strvec_push(&argv, "commit");
4615 * continue_single_pick() handles the case of recovering from a
4616 * conflict. should_edit() doesn't handle that case; for a conflict,
4617 * we want to edit if the user asked for it, or if they didn't specify
4618 * and stdin is a tty.
4620 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4622 * Include --cleanup=strip as well because we don't want the
4623 * "# Conflicts:" messages.
4625 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4627 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4628 strvec_clear(&argv);
4629 return ret;
4632 static int commit_staged_changes(struct repository *r,
4633 struct replay_opts *opts,
4634 struct todo_list *todo_list)
4636 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4637 unsigned int final_fixup = 0, is_clean;
4639 if (has_unstaged_changes(r, 1))
4640 return error(_("cannot rebase: You have unstaged changes."));
4642 is_clean = !has_uncommitted_changes(r, 0);
4644 if (file_exists(rebase_path_amend())) {
4645 struct strbuf rev = STRBUF_INIT;
4646 struct object_id head, to_amend;
4648 if (get_oid("HEAD", &head))
4649 return error(_("cannot amend non-existing commit"));
4650 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4651 return error(_("invalid file: '%s'"), rebase_path_amend());
4652 if (get_oid_hex(rev.buf, &to_amend))
4653 return error(_("invalid contents: '%s'"),
4654 rebase_path_amend());
4655 if (!is_clean && !oideq(&head, &to_amend))
4656 return error(_("\nYou have uncommitted changes in your "
4657 "working tree. Please, commit them\n"
4658 "first and then run 'git rebase "
4659 "--continue' again."));
4661 * When skipping a failed fixup/squash, we need to edit the
4662 * commit message, the current fixup list and count, and if it
4663 * was the last fixup/squash in the chain, we need to clean up
4664 * the commit message and if there was a squash, let the user
4665 * edit it.
4667 if (!is_clean || !opts->current_fixup_count)
4668 ; /* this is not the final fixup */
4669 else if (!oideq(&head, &to_amend) ||
4670 !file_exists(rebase_path_stopped_sha())) {
4671 /* was a final fixup or squash done manually? */
4672 if (!is_fixup(peek_command(todo_list, 0))) {
4673 unlink(rebase_path_fixup_msg());
4674 unlink(rebase_path_squash_msg());
4675 unlink(rebase_path_current_fixups());
4676 strbuf_reset(&opts->current_fixups);
4677 opts->current_fixup_count = 0;
4679 } else {
4680 /* we are in a fixup/squash chain */
4681 const char *p = opts->current_fixups.buf;
4682 int len = opts->current_fixups.len;
4684 opts->current_fixup_count--;
4685 if (!len)
4686 BUG("Incorrect current_fixups:\n%s", p);
4687 while (len && p[len - 1] != '\n')
4688 len--;
4689 strbuf_setlen(&opts->current_fixups, len);
4690 if (write_message(p, len, rebase_path_current_fixups(),
4691 0) < 0)
4692 return error(_("could not write file: '%s'"),
4693 rebase_path_current_fixups());
4696 * If a fixup/squash in a fixup/squash chain failed, the
4697 * commit message is already correct, no need to commit
4698 * it again.
4700 * Only if it is the final command in the fixup/squash
4701 * chain, and only if the chain is longer than a single
4702 * fixup/squash command (which was just skipped), do we
4703 * actually need to re-commit with a cleaned up commit
4704 * message.
4706 if (opts->current_fixup_count > 0 &&
4707 !is_fixup(peek_command(todo_list, 0))) {
4708 final_fixup = 1;
4710 * If there was not a single "squash" in the
4711 * chain, we only need to clean up the commit
4712 * message, no need to bother the user with
4713 * opening the commit message in the editor.
4715 if (!starts_with(p, "squash ") &&
4716 !strstr(p, "\nsquash "))
4717 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4718 } else if (is_fixup(peek_command(todo_list, 0))) {
4720 * We need to update the squash message to skip
4721 * the latest commit message.
4723 struct commit *commit;
4724 const char *path = rebase_path_squash_msg();
4725 const char *encoding = get_commit_output_encoding();
4727 if (parse_head(r, &commit) ||
4728 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4729 write_message(p, strlen(p), path, 0)) {
4730 unuse_commit_buffer(commit, p);
4731 return error(_("could not write file: "
4732 "'%s'"), path);
4734 unuse_commit_buffer(commit, p);
4738 strbuf_release(&rev);
4739 flags |= AMEND_MSG;
4742 if (is_clean) {
4743 if (refs_ref_exists(get_main_ref_store(r),
4744 "CHERRY_PICK_HEAD") &&
4745 refs_delete_ref(get_main_ref_store(r), "",
4746 "CHERRY_PICK_HEAD", NULL, 0))
4747 return error(_("could not remove CHERRY_PICK_HEAD"));
4748 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4749 return error_errno(_("could not remove '%s'"),
4750 git_path_merge_msg(r));
4751 if (!final_fixup)
4752 return 0;
4755 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4756 opts, flags))
4757 return error(_("could not commit staged changes."));
4758 unlink(rebase_path_amend());
4759 unlink(git_path_merge_head(r));
4760 unlink(git_path_auto_merge(r));
4761 if (final_fixup) {
4762 unlink(rebase_path_fixup_msg());
4763 unlink(rebase_path_squash_msg());
4765 if (opts->current_fixup_count > 0) {
4767 * Whether final fixup or not, we just cleaned up the commit
4768 * message...
4770 unlink(rebase_path_current_fixups());
4771 strbuf_reset(&opts->current_fixups);
4772 opts->current_fixup_count = 0;
4774 return 0;
4777 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4779 struct todo_list todo_list = TODO_LIST_INIT;
4780 int res;
4782 if (read_and_refresh_cache(r, opts))
4783 return -1;
4785 if (read_populate_opts(opts))
4786 return -1;
4787 if (is_rebase_i(opts)) {
4788 if ((res = read_populate_todo(r, &todo_list, opts)))
4789 goto release_todo_list;
4791 if (file_exists(rebase_path_dropped())) {
4792 if ((res = todo_list_check_against_backup(r, &todo_list)))
4793 goto release_todo_list;
4795 unlink(rebase_path_dropped());
4798 if (commit_staged_changes(r, opts, &todo_list)) {
4799 res = -1;
4800 goto release_todo_list;
4802 } else if (!file_exists(get_todo_path(opts)))
4803 return continue_single_pick(r, opts);
4804 else if ((res = read_populate_todo(r, &todo_list, opts)))
4805 goto release_todo_list;
4807 if (!is_rebase_i(opts)) {
4808 /* Verify that the conflict has been resolved */
4809 if (refs_ref_exists(get_main_ref_store(r),
4810 "CHERRY_PICK_HEAD") ||
4811 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4812 res = continue_single_pick(r, opts);
4813 if (res)
4814 goto release_todo_list;
4816 if (index_differs_from(r, "HEAD", NULL, 0)) {
4817 res = error_dirty_index(r, opts);
4818 goto release_todo_list;
4820 todo_list.current++;
4821 } else if (file_exists(rebase_path_stopped_sha())) {
4822 struct strbuf buf = STRBUF_INIT;
4823 struct object_id oid;
4825 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4826 READ_ONELINER_SKIP_IF_EMPTY) &&
4827 !get_oid_hex(buf.buf, &oid))
4828 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4829 strbuf_release(&buf);
4832 res = pick_commits(r, &todo_list, opts);
4833 release_todo_list:
4834 todo_list_release(&todo_list);
4835 return res;
4838 static int single_pick(struct repository *r,
4839 struct commit *cmit,
4840 struct replay_opts *opts)
4842 int check_todo;
4843 struct todo_item item;
4845 item.command = opts->action == REPLAY_PICK ?
4846 TODO_PICK : TODO_REVERT;
4847 item.commit = cmit;
4849 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4850 return do_pick_commit(r, &item, opts, 0, &check_todo);
4853 int sequencer_pick_revisions(struct repository *r,
4854 struct replay_opts *opts)
4856 struct todo_list todo_list = TODO_LIST_INIT;
4857 struct object_id oid;
4858 int i, res;
4860 assert(opts->revs);
4861 if (read_and_refresh_cache(r, opts))
4862 return -1;
4864 for (i = 0; i < opts->revs->pending.nr; i++) {
4865 struct object_id oid;
4866 const char *name = opts->revs->pending.objects[i].name;
4868 /* This happens when using --stdin. */
4869 if (!strlen(name))
4870 continue;
4872 if (!get_oid(name, &oid)) {
4873 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4874 enum object_type type = oid_object_info(r,
4875 &oid,
4876 NULL);
4877 return error(_("%s: can't cherry-pick a %s"),
4878 name, type_name(type));
4880 } else
4881 return error(_("%s: bad revision"), name);
4885 * If we were called as "git cherry-pick <commit>", just
4886 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4887 * REVERT_HEAD, and don't touch the sequencer state.
4888 * This means it is possible to cherry-pick in the middle
4889 * of a cherry-pick sequence.
4891 if (opts->revs->cmdline.nr == 1 &&
4892 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4893 opts->revs->no_walk &&
4894 !opts->revs->cmdline.rev->flags) {
4895 struct commit *cmit;
4896 if (prepare_revision_walk(opts->revs))
4897 return error(_("revision walk setup failed"));
4898 cmit = get_revision(opts->revs);
4899 if (!cmit)
4900 return error(_("empty commit set passed"));
4901 if (get_revision(opts->revs))
4902 BUG("unexpected extra commit from walk");
4903 return single_pick(r, cmit, opts);
4907 * Start a new cherry-pick/ revert sequence; but
4908 * first, make sure that an existing one isn't in
4909 * progress
4912 if (walk_revs_populate_todo(&todo_list, opts) ||
4913 create_seq_dir(r) < 0)
4914 return -1;
4915 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4916 return error(_("can't revert as initial commit"));
4917 if (save_head(oid_to_hex(&oid)))
4918 return -1;
4919 if (save_opts(opts))
4920 return -1;
4921 update_abort_safety_file();
4922 res = pick_commits(r, &todo_list, opts);
4923 todo_list_release(&todo_list);
4924 return res;
4927 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4929 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4930 struct strbuf sob = STRBUF_INIT;
4931 int has_footer;
4933 strbuf_addstr(&sob, sign_off_header);
4934 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4935 strbuf_addch(&sob, '\n');
4937 if (!ignore_footer)
4938 strbuf_complete_line(msgbuf);
4941 * If the whole message buffer is equal to the sob, pretend that we
4942 * found a conforming footer with a matching sob
4944 if (msgbuf->len - ignore_footer == sob.len &&
4945 !strncmp(msgbuf->buf, sob.buf, sob.len))
4946 has_footer = 3;
4947 else
4948 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4950 if (!has_footer) {
4951 const char *append_newlines = NULL;
4952 size_t len = msgbuf->len - ignore_footer;
4954 if (!len) {
4956 * The buffer is completely empty. Leave foom for
4957 * the title and body to be filled in by the user.
4959 append_newlines = "\n\n";
4960 } else if (len == 1) {
4962 * Buffer contains a single newline. Add another
4963 * so that we leave room for the title and body.
4965 append_newlines = "\n";
4966 } else if (msgbuf->buf[len - 2] != '\n') {
4968 * Buffer ends with a single newline. Add another
4969 * so that there is an empty line between the message
4970 * body and the sob.
4972 append_newlines = "\n";
4973 } /* else, the buffer already ends with two newlines. */
4975 if (append_newlines)
4976 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4977 append_newlines, strlen(append_newlines));
4980 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4981 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4982 sob.buf, sob.len);
4984 strbuf_release(&sob);
4987 struct labels_entry {
4988 struct hashmap_entry entry;
4989 char label[FLEX_ARRAY];
4992 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4993 const struct hashmap_entry *entry_or_key, const void *key)
4995 const struct labels_entry *a, *b;
4997 a = container_of(eptr, const struct labels_entry, entry);
4998 b = container_of(entry_or_key, const struct labels_entry, entry);
5000 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5003 struct string_entry {
5004 struct oidmap_entry entry;
5005 char string[FLEX_ARRAY];
5008 struct label_state {
5009 struct oidmap commit2label;
5010 struct hashmap labels;
5011 struct strbuf buf;
5014 static const char *label_oid(struct object_id *oid, const char *label,
5015 struct label_state *state)
5017 struct labels_entry *labels_entry;
5018 struct string_entry *string_entry;
5019 struct object_id dummy;
5020 int i;
5022 string_entry = oidmap_get(&state->commit2label, oid);
5023 if (string_entry)
5024 return string_entry->string;
5027 * For "uninteresting" commits, i.e. commits that are not to be
5028 * rebased, and which can therefore not be labeled, we use a unique
5029 * abbreviation of the commit name. This is slightly more complicated
5030 * than calling find_unique_abbrev() because we also need to make
5031 * sure that the abbreviation does not conflict with any other
5032 * label.
5034 * We disallow "interesting" commits to be labeled by a string that
5035 * is a valid full-length hash, to ensure that we always can find an
5036 * abbreviation for any uninteresting commit's names that does not
5037 * clash with any other label.
5039 strbuf_reset(&state->buf);
5040 if (!label) {
5041 char *p;
5043 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5044 label = p = state->buf.buf;
5046 find_unique_abbrev_r(p, oid, default_abbrev);
5049 * We may need to extend the abbreviated hash so that there is
5050 * no conflicting label.
5052 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5053 size_t i = strlen(p) + 1;
5055 oid_to_hex_r(p, oid);
5056 for (; i < the_hash_algo->hexsz; i++) {
5057 char save = p[i];
5058 p[i] = '\0';
5059 if (!hashmap_get_from_hash(&state->labels,
5060 strihash(p), p))
5061 break;
5062 p[i] = save;
5065 } else {
5066 struct strbuf *buf = &state->buf;
5069 * Sanitize labels by replacing non-alpha-numeric characters
5070 * (including white-space ones) by dashes, as they might be
5071 * illegal in file names (and hence in ref names).
5073 * Note that we retain non-ASCII UTF-8 characters (identified
5074 * via the most significant bit). They should be all acceptable
5075 * in file names. We do not validate the UTF-8 here, that's not
5076 * the job of this function.
5078 for (; *label; label++)
5079 if ((*label & 0x80) || isalnum(*label))
5080 strbuf_addch(buf, *label);
5081 /* avoid leading dash and double-dashes */
5082 else if (buf->len && buf->buf[buf->len - 1] != '-')
5083 strbuf_addch(buf, '-');
5084 if (!buf->len) {
5085 strbuf_addstr(buf, "rev-");
5086 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5088 label = buf->buf;
5090 if ((buf->len == the_hash_algo->hexsz &&
5091 !get_oid_hex(label, &dummy)) ||
5092 (buf->len == 1 && *label == '#') ||
5093 hashmap_get_from_hash(&state->labels,
5094 strihash(label), label)) {
5096 * If the label already exists, or if the label is a
5097 * valid full OID, or the label is a '#' (which we use
5098 * as a separator between merge heads and oneline), we
5099 * append a dash and a number to make it unique.
5101 size_t len = buf->len;
5103 for (i = 2; ; i++) {
5104 strbuf_setlen(buf, len);
5105 strbuf_addf(buf, "-%d", i);
5106 if (!hashmap_get_from_hash(&state->labels,
5107 strihash(buf->buf),
5108 buf->buf))
5109 break;
5112 label = buf->buf;
5116 FLEX_ALLOC_STR(labels_entry, label, label);
5117 hashmap_entry_init(&labels_entry->entry, strihash(label));
5118 hashmap_add(&state->labels, &labels_entry->entry);
5120 FLEX_ALLOC_STR(string_entry, string, label);
5121 oidcpy(&string_entry->entry.oid, oid);
5122 oidmap_put(&state->commit2label, string_entry);
5124 return string_entry->string;
5127 static int make_script_with_merges(struct pretty_print_context *pp,
5128 struct rev_info *revs, struct strbuf *out,
5129 unsigned flags)
5131 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5132 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5133 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5134 int skipped_commit = 0;
5135 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5136 struct strbuf label = STRBUF_INIT;
5137 struct commit_list *commits = NULL, **tail = &commits, *iter;
5138 struct commit_list *tips = NULL, **tips_tail = &tips;
5139 struct commit *commit;
5140 struct oidmap commit2todo = OIDMAP_INIT;
5141 struct string_entry *entry;
5142 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5143 shown = OIDSET_INIT;
5144 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5146 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5147 const char *cmd_pick = abbr ? "p" : "pick",
5148 *cmd_label = abbr ? "l" : "label",
5149 *cmd_reset = abbr ? "t" : "reset",
5150 *cmd_merge = abbr ? "m" : "merge";
5152 oidmap_init(&commit2todo, 0);
5153 oidmap_init(&state.commit2label, 0);
5154 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5155 strbuf_init(&state.buf, 32);
5157 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5158 struct labels_entry *onto_label_entry;
5159 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5160 FLEX_ALLOC_STR(entry, string, "onto");
5161 oidcpy(&entry->entry.oid, oid);
5162 oidmap_put(&state.commit2label, entry);
5164 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5165 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5166 hashmap_add(&state.labels, &onto_label_entry->entry);
5170 * First phase:
5171 * - get onelines for all commits
5172 * - gather all branch tips (i.e. 2nd or later parents of merges)
5173 * - label all branch tips
5175 while ((commit = get_revision(revs))) {
5176 struct commit_list *to_merge;
5177 const char *p1, *p2;
5178 struct object_id *oid;
5179 int is_empty;
5181 tail = &commit_list_insert(commit, tail)->next;
5182 oidset_insert(&interesting, &commit->object.oid);
5184 is_empty = is_original_commit_empty(commit);
5185 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5186 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5187 warning(_("skipped previously applied commit %s"),
5188 short_commit_name(commit));
5189 skipped_commit = 1;
5190 continue;
5192 if (is_empty && !keep_empty)
5193 continue;
5195 strbuf_reset(&oneline);
5196 pretty_print_commit(pp, commit, &oneline);
5198 to_merge = commit->parents ? commit->parents->next : NULL;
5199 if (!to_merge) {
5200 /* non-merge commit: easy case */
5201 strbuf_reset(&buf);
5202 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5203 oid_to_hex(&commit->object.oid),
5204 oneline.buf);
5205 if (is_empty)
5206 strbuf_addf(&buf, " %c empty",
5207 comment_line_char);
5209 FLEX_ALLOC_STR(entry, string, buf.buf);
5210 oidcpy(&entry->entry.oid, &commit->object.oid);
5211 oidmap_put(&commit2todo, entry);
5213 continue;
5216 /* Create a label */
5217 strbuf_reset(&label);
5218 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5219 (p1 = strchr(p1, '\'')) &&
5220 (p2 = strchr(++p1, '\'')))
5221 strbuf_add(&label, p1, p2 - p1);
5222 else if (skip_prefix(oneline.buf, "Merge pull request ",
5223 &p1) &&
5224 (p1 = strstr(p1, " from ")))
5225 strbuf_addstr(&label, p1 + strlen(" from "));
5226 else
5227 strbuf_addbuf(&label, &oneline);
5229 strbuf_reset(&buf);
5230 strbuf_addf(&buf, "%s -C %s",
5231 cmd_merge, oid_to_hex(&commit->object.oid));
5233 /* label the tips of merged branches */
5234 for (; to_merge; to_merge = to_merge->next) {
5235 oid = &to_merge->item->object.oid;
5236 strbuf_addch(&buf, ' ');
5238 if (!oidset_contains(&interesting, oid)) {
5239 strbuf_addstr(&buf, label_oid(oid, NULL,
5240 &state));
5241 continue;
5244 tips_tail = &commit_list_insert(to_merge->item,
5245 tips_tail)->next;
5247 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5249 strbuf_addf(&buf, " # %s", oneline.buf);
5251 FLEX_ALLOC_STR(entry, string, buf.buf);
5252 oidcpy(&entry->entry.oid, &commit->object.oid);
5253 oidmap_put(&commit2todo, entry);
5255 if (skipped_commit)
5256 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5257 _("use --reapply-cherry-picks to include skipped commits"));
5260 * Second phase:
5261 * - label branch points
5262 * - add HEAD to the branch tips
5264 for (iter = commits; iter; iter = iter->next) {
5265 struct commit_list *parent = iter->item->parents;
5266 for (; parent; parent = parent->next) {
5267 struct object_id *oid = &parent->item->object.oid;
5268 if (!oidset_contains(&interesting, oid))
5269 continue;
5270 if (oidset_insert(&child_seen, oid))
5271 label_oid(oid, "branch-point", &state);
5274 /* Add HEAD as implicit "tip of branch" */
5275 if (!iter->next)
5276 tips_tail = &commit_list_insert(iter->item,
5277 tips_tail)->next;
5281 * Third phase: output the todo list. This is a bit tricky, as we
5282 * want to avoid jumping back and forth between revisions. To
5283 * accomplish that goal, we walk backwards from the branch tips,
5284 * gathering commits not yet shown, reversing the list on the fly,
5285 * then outputting that list (labeling revisions as needed).
5287 strbuf_addf(out, "%s onto\n", cmd_label);
5288 for (iter = tips; iter; iter = iter->next) {
5289 struct commit_list *list = NULL, *iter2;
5291 commit = iter->item;
5292 if (oidset_contains(&shown, &commit->object.oid))
5293 continue;
5294 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5296 if (entry)
5297 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5298 else
5299 strbuf_addch(out, '\n');
5301 while (oidset_contains(&interesting, &commit->object.oid) &&
5302 !oidset_contains(&shown, &commit->object.oid)) {
5303 commit_list_insert(commit, &list);
5304 if (!commit->parents) {
5305 commit = NULL;
5306 break;
5308 commit = commit->parents->item;
5311 if (!commit)
5312 strbuf_addf(out, "%s %s\n", cmd_reset,
5313 rebase_cousins || root_with_onto ?
5314 "onto" : "[new root]");
5315 else {
5316 const char *to = NULL;
5318 entry = oidmap_get(&state.commit2label,
5319 &commit->object.oid);
5320 if (entry)
5321 to = entry->string;
5322 else if (!rebase_cousins)
5323 to = label_oid(&commit->object.oid, NULL,
5324 &state);
5326 if (!to || !strcmp(to, "onto"))
5327 strbuf_addf(out, "%s onto\n", cmd_reset);
5328 else {
5329 strbuf_reset(&oneline);
5330 pretty_print_commit(pp, commit, &oneline);
5331 strbuf_addf(out, "%s %s # %s\n",
5332 cmd_reset, to, oneline.buf);
5336 for (iter2 = list; iter2; iter2 = iter2->next) {
5337 struct object_id *oid = &iter2->item->object.oid;
5338 entry = oidmap_get(&commit2todo, oid);
5339 /* only show if not already upstream */
5340 if (entry)
5341 strbuf_addf(out, "%s\n", entry->string);
5342 entry = oidmap_get(&state.commit2label, oid);
5343 if (entry)
5344 strbuf_addf(out, "%s %s\n",
5345 cmd_label, entry->string);
5346 oidset_insert(&shown, oid);
5349 free_commit_list(list);
5352 free_commit_list(commits);
5353 free_commit_list(tips);
5355 strbuf_release(&label);
5356 strbuf_release(&oneline);
5357 strbuf_release(&buf);
5359 oidmap_free(&commit2todo, 1);
5360 oidmap_free(&state.commit2label, 1);
5361 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5362 strbuf_release(&state.buf);
5364 return 0;
5367 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5368 const char **argv, unsigned flags)
5370 char *format = NULL;
5371 struct pretty_print_context pp = {0};
5372 struct rev_info revs;
5373 struct commit *commit;
5374 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5375 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5376 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5377 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5378 int skipped_commit = 0;
5380 repo_init_revisions(r, &revs, NULL);
5381 revs.verbose_header = 1;
5382 if (!rebase_merges)
5383 revs.max_parents = 1;
5384 revs.cherry_mark = !reapply_cherry_picks;
5385 revs.limited = 1;
5386 revs.reverse = 1;
5387 revs.right_only = 1;
5388 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5389 revs.topo_order = 1;
5391 revs.pretty_given = 1;
5392 git_config_get_string("rebase.instructionFormat", &format);
5393 if (!format || !*format) {
5394 free(format);
5395 format = xstrdup("%s");
5397 get_commit_format(format, &revs);
5398 free(format);
5399 pp.fmt = revs.commit_format;
5400 pp.output_encoding = get_log_output_encoding();
5402 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5403 return error(_("make_script: unhandled options"));
5405 if (prepare_revision_walk(&revs) < 0)
5406 return error(_("make_script: error preparing revisions"));
5408 if (rebase_merges)
5409 return make_script_with_merges(&pp, &revs, out, flags);
5411 while ((commit = get_revision(&revs))) {
5412 int is_empty = is_original_commit_empty(commit);
5414 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5415 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5416 warning(_("skipped previously applied commit %s"),
5417 short_commit_name(commit));
5418 skipped_commit = 1;
5419 continue;
5421 if (is_empty && !keep_empty)
5422 continue;
5423 strbuf_addf(out, "%s %s ", insn,
5424 oid_to_hex(&commit->object.oid));
5425 pretty_print_commit(&pp, commit, out);
5426 if (is_empty)
5427 strbuf_addf(out, " %c empty", comment_line_char);
5428 strbuf_addch(out, '\n');
5430 if (skipped_commit)
5431 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5432 _("use --reapply-cherry-picks to include skipped commits"));
5433 return 0;
5437 * Add commands after pick and (series of) squash/fixup commands
5438 * in the todo list.
5440 void todo_list_add_exec_commands(struct todo_list *todo_list,
5441 struct string_list *commands)
5443 struct strbuf *buf = &todo_list->buf;
5444 size_t base_offset = buf->len;
5445 int i, insert, nr = 0, alloc = 0;
5446 struct todo_item *items = NULL, *base_items = NULL;
5448 CALLOC_ARRAY(base_items, commands->nr);
5449 for (i = 0; i < commands->nr; i++) {
5450 size_t command_len = strlen(commands->items[i].string);
5452 strbuf_addstr(buf, commands->items[i].string);
5453 strbuf_addch(buf, '\n');
5455 base_items[i].command = TODO_EXEC;
5456 base_items[i].offset_in_buf = base_offset;
5457 base_items[i].arg_offset = base_offset + strlen("exec ");
5458 base_items[i].arg_len = command_len - strlen("exec ");
5460 base_offset += command_len + 1;
5464 * Insert <commands> after every pick. Here, fixup/squash chains
5465 * are considered part of the pick, so we insert the commands *after*
5466 * those chains if there are any.
5468 * As we insert the exec commands immediately after rearranging
5469 * any fixups and before the user edits the list, a fixup chain
5470 * can never contain comments (any comments are empty picks that
5471 * have been commented out because the user did not specify
5472 * --keep-empty). So, it is safe to insert an exec command
5473 * without looking at the command following a comment.
5475 insert = 0;
5476 for (i = 0; i < todo_list->nr; i++) {
5477 enum todo_command command = todo_list->items[i].command;
5478 if (insert && !is_fixup(command)) {
5479 ALLOC_GROW(items, nr + commands->nr, alloc);
5480 COPY_ARRAY(items + nr, base_items, commands->nr);
5481 nr += commands->nr;
5483 insert = 0;
5486 ALLOC_GROW(items, nr + 1, alloc);
5487 items[nr++] = todo_list->items[i];
5489 if (command == TODO_PICK || command == TODO_MERGE)
5490 insert = 1;
5493 /* insert or append final <commands> */
5494 if (insert || nr == todo_list->nr) {
5495 ALLOC_GROW(items, nr + commands->nr, alloc);
5496 COPY_ARRAY(items + nr, base_items, commands->nr);
5497 nr += commands->nr;
5500 free(base_items);
5501 FREE_AND_NULL(todo_list->items);
5502 todo_list->items = items;
5503 todo_list->nr = nr;
5504 todo_list->alloc = alloc;
5507 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5508 struct strbuf *buf, int num, unsigned flags)
5510 struct todo_item *item;
5511 int i, max = todo_list->nr;
5513 if (num > 0 && num < max)
5514 max = num;
5516 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5517 char cmd;
5519 /* if the item is not a command write it and continue */
5520 if (item->command >= TODO_COMMENT) {
5521 strbuf_addf(buf, "%.*s\n", item->arg_len,
5522 todo_item_get_arg(todo_list, item));
5523 continue;
5526 /* add command to the buffer */
5527 cmd = command_to_char(item->command);
5528 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5529 strbuf_addch(buf, cmd);
5530 else
5531 strbuf_addstr(buf, command_to_string(item->command));
5533 /* add commit id */
5534 if (item->commit) {
5535 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5536 short_commit_name(item->commit) :
5537 oid_to_hex(&item->commit->object.oid);
5539 if (item->command == TODO_FIXUP) {
5540 if (item->flags & TODO_EDIT_FIXUP_MSG)
5541 strbuf_addstr(buf, " -c");
5542 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5543 strbuf_addstr(buf, " -C");
5547 if (item->command == TODO_MERGE) {
5548 if (item->flags & TODO_EDIT_MERGE_MSG)
5549 strbuf_addstr(buf, " -c");
5550 else
5551 strbuf_addstr(buf, " -C");
5554 strbuf_addf(buf, " %s", oid);
5557 /* add all the rest */
5558 if (!item->arg_len)
5559 strbuf_addch(buf, '\n');
5560 else
5561 strbuf_addf(buf, " %.*s\n", item->arg_len,
5562 todo_item_get_arg(todo_list, item));
5566 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5567 const char *file, const char *shortrevisions,
5568 const char *shortonto, int num, unsigned flags)
5570 int res;
5571 struct strbuf buf = STRBUF_INIT;
5573 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5574 if (flags & TODO_LIST_APPEND_TODO_HELP)
5575 append_todo_help(count_commands(todo_list),
5576 shortrevisions, shortonto, &buf);
5578 res = write_message(buf.buf, buf.len, file, 0);
5579 strbuf_release(&buf);
5581 return res;
5584 /* skip picking commits whose parents are unchanged */
5585 static int skip_unnecessary_picks(struct repository *r,
5586 struct todo_list *todo_list,
5587 struct object_id *base_oid)
5589 struct object_id *parent_oid;
5590 int i;
5592 for (i = 0; i < todo_list->nr; i++) {
5593 struct todo_item *item = todo_list->items + i;
5595 if (item->command >= TODO_NOOP)
5596 continue;
5597 if (item->command != TODO_PICK)
5598 break;
5599 if (parse_commit(item->commit)) {
5600 return error(_("could not parse commit '%s'"),
5601 oid_to_hex(&item->commit->object.oid));
5603 if (!item->commit->parents)
5604 break; /* root commit */
5605 if (item->commit->parents->next)
5606 break; /* merge commit */
5607 parent_oid = &item->commit->parents->item->object.oid;
5608 if (!oideq(parent_oid, base_oid))
5609 break;
5610 oidcpy(base_oid, &item->commit->object.oid);
5612 if (i > 0) {
5613 const char *done_path = rebase_path_done();
5615 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5616 error_errno(_("could not write to '%s'"), done_path);
5617 return -1;
5620 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5621 todo_list->nr -= i;
5622 todo_list->current = 0;
5623 todo_list->done_nr += i;
5625 if (is_fixup(peek_command(todo_list, 0)))
5626 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5629 return 0;
5632 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5633 const char *shortrevisions, const char *onto_name,
5634 struct commit *onto, const struct object_id *orig_head,
5635 struct string_list *commands, unsigned autosquash,
5636 struct todo_list *todo_list)
5638 char shortonto[GIT_MAX_HEXSZ + 1];
5639 const char *todo_file = rebase_path_todo();
5640 struct todo_list new_todo = TODO_LIST_INIT;
5641 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5642 struct object_id oid = onto->object.oid;
5643 int res;
5645 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5647 if (buf->len == 0) {
5648 struct todo_item *item = append_new_todo(todo_list);
5649 item->command = TODO_NOOP;
5650 item->commit = NULL;
5651 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5654 if (autosquash && todo_list_rearrange_squash(todo_list))
5655 return -1;
5657 if (commands->nr)
5658 todo_list_add_exec_commands(todo_list, commands);
5660 if (count_commands(todo_list) == 0) {
5661 apply_autostash(rebase_path_autostash());
5662 sequencer_remove_state(opts);
5664 return error(_("nothing to do"));
5667 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5668 shortonto, flags);
5669 if (res == -1)
5670 return -1;
5671 else if (res == -2) {
5672 apply_autostash(rebase_path_autostash());
5673 sequencer_remove_state(opts);
5675 return -1;
5676 } else if (res == -3) {
5677 apply_autostash(rebase_path_autostash());
5678 sequencer_remove_state(opts);
5679 todo_list_release(&new_todo);
5681 return error(_("nothing to do"));
5682 } else if (res == -4) {
5683 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5684 todo_list_release(&new_todo);
5686 return -1;
5689 /* Expand the commit IDs */
5690 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5691 strbuf_swap(&new_todo.buf, &buf2);
5692 strbuf_release(&buf2);
5693 new_todo.total_nr -= new_todo.nr;
5694 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5695 BUG("invalid todo list after expanding IDs:\n%s",
5696 new_todo.buf.buf);
5698 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5699 todo_list_release(&new_todo);
5700 return error(_("could not skip unnecessary pick commands"));
5703 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5704 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5705 todo_list_release(&new_todo);
5706 return error_errno(_("could not write '%s'"), todo_file);
5709 res = -1;
5711 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5712 goto cleanup;
5714 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5715 goto cleanup;
5717 todo_list_write_total_nr(&new_todo);
5718 res = pick_commits(r, &new_todo, opts);
5720 cleanup:
5721 todo_list_release(&new_todo);
5723 return res;
5726 struct subject2item_entry {
5727 struct hashmap_entry entry;
5728 int i;
5729 char subject[FLEX_ARRAY];
5732 static int subject2item_cmp(const void *fndata,
5733 const struct hashmap_entry *eptr,
5734 const struct hashmap_entry *entry_or_key,
5735 const void *key)
5737 const struct subject2item_entry *a, *b;
5739 a = container_of(eptr, const struct subject2item_entry, entry);
5740 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5742 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5745 define_commit_slab(commit_todo_item, struct todo_item *);
5747 static int skip_fixupish(const char *subject, const char **p) {
5748 return skip_prefix(subject, "fixup! ", p) ||
5749 skip_prefix(subject, "amend! ", p) ||
5750 skip_prefix(subject, "squash! ", p);
5754 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5755 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5756 * after the former, and change "pick" to "fixup"/"squash".
5758 * Note that if the config has specified a custom instruction format, each log
5759 * message will have to be retrieved from the commit (as the oneline in the
5760 * script cannot be trusted) in order to normalize the autosquash arrangement.
5762 int todo_list_rearrange_squash(struct todo_list *todo_list)
5764 struct hashmap subject2item;
5765 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5766 char **subjects;
5767 struct commit_todo_item commit_todo;
5768 struct todo_item *items = NULL;
5770 init_commit_todo_item(&commit_todo);
5772 * The hashmap maps onelines to the respective todo list index.
5774 * If any items need to be rearranged, the next[i] value will indicate
5775 * which item was moved directly after the i'th.
5777 * In that case, last[i] will indicate the index of the latest item to
5778 * be moved to appear after the i'th.
5780 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5781 ALLOC_ARRAY(next, todo_list->nr);
5782 ALLOC_ARRAY(tail, todo_list->nr);
5783 ALLOC_ARRAY(subjects, todo_list->nr);
5784 for (i = 0; i < todo_list->nr; i++) {
5785 struct strbuf buf = STRBUF_INIT;
5786 struct todo_item *item = todo_list->items + i;
5787 const char *commit_buffer, *subject, *p;
5788 size_t subject_len;
5789 int i2 = -1;
5790 struct subject2item_entry *entry;
5792 next[i] = tail[i] = -1;
5793 if (!item->commit || item->command == TODO_DROP) {
5794 subjects[i] = NULL;
5795 continue;
5798 if (is_fixup(item->command)) {
5799 clear_commit_todo_item(&commit_todo);
5800 return error(_("the script was already rearranged."));
5803 *commit_todo_item_at(&commit_todo, item->commit) = item;
5805 parse_commit(item->commit);
5806 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5807 find_commit_subject(commit_buffer, &subject);
5808 format_subject(&buf, subject, " ");
5809 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5810 unuse_commit_buffer(item->commit, commit_buffer);
5811 if (skip_fixupish(subject, &p)) {
5812 struct commit *commit2;
5814 for (;;) {
5815 while (isspace(*p))
5816 p++;
5817 if (!skip_fixupish(p, &p))
5818 break;
5821 entry = hashmap_get_entry_from_hash(&subject2item,
5822 strhash(p), p,
5823 struct subject2item_entry,
5824 entry);
5825 if (entry)
5826 /* found by title */
5827 i2 = entry->i;
5828 else if (!strchr(p, ' ') &&
5829 (commit2 =
5830 lookup_commit_reference_by_name(p)) &&
5831 *commit_todo_item_at(&commit_todo, commit2))
5832 /* found by commit name */
5833 i2 = *commit_todo_item_at(&commit_todo, commit2)
5834 - todo_list->items;
5835 else {
5836 /* copy can be a prefix of the commit subject */
5837 for (i2 = 0; i2 < i; i2++)
5838 if (subjects[i2] &&
5839 starts_with(subjects[i2], p))
5840 break;
5841 if (i2 == i)
5842 i2 = -1;
5845 if (i2 >= 0) {
5846 rearranged = 1;
5847 if (starts_with(subject, "fixup!")) {
5848 todo_list->items[i].command = TODO_FIXUP;
5849 } else if (starts_with(subject, "amend!")) {
5850 todo_list->items[i].command = TODO_FIXUP;
5851 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5852 } else {
5853 todo_list->items[i].command = TODO_SQUASH;
5855 if (tail[i2] < 0) {
5856 next[i] = next[i2];
5857 next[i2] = i;
5858 } else {
5859 next[i] = next[tail[i2]];
5860 next[tail[i2]] = i;
5862 tail[i2] = i;
5863 } else if (!hashmap_get_from_hash(&subject2item,
5864 strhash(subject), subject)) {
5865 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5866 entry->i = i;
5867 hashmap_entry_init(&entry->entry,
5868 strhash(entry->subject));
5869 hashmap_put(&subject2item, &entry->entry);
5873 if (rearranged) {
5874 for (i = 0; i < todo_list->nr; i++) {
5875 enum todo_command command = todo_list->items[i].command;
5876 int cur = i;
5879 * Initially, all commands are 'pick's. If it is a
5880 * fixup or a squash now, we have rearranged it.
5882 if (is_fixup(command))
5883 continue;
5885 while (cur >= 0) {
5886 ALLOC_GROW(items, nr + 1, alloc);
5887 items[nr++] = todo_list->items[cur];
5888 cur = next[cur];
5892 FREE_AND_NULL(todo_list->items);
5893 todo_list->items = items;
5894 todo_list->nr = nr;
5895 todo_list->alloc = alloc;
5898 free(next);
5899 free(tail);
5900 for (i = 0; i < todo_list->nr; i++)
5901 free(subjects[i]);
5902 free(subjects);
5903 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5905 clear_commit_todo_item(&commit_todo);
5907 return 0;
5910 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5912 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5913 struct object_id cherry_pick_head, rebase_head;
5915 if (file_exists(git_path_seq_dir()))
5916 *whence = FROM_CHERRY_PICK_MULTI;
5917 if (file_exists(rebase_path()) &&
5918 !get_oid("REBASE_HEAD", &rebase_head) &&
5919 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5920 oideq(&rebase_head, &cherry_pick_head))
5921 *whence = FROM_REBASE_PICK;
5922 else
5923 *whence = FROM_CHERRY_PICK_SINGLE;
5925 return 1;
5928 return 0;