ls-refs: reject unknown arguments
[git/gitster.git] / sequencer.c
blob6831663692149187a8004fa71af649a3a9c65f1f
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 clean = merge_trees(&o, head_tree, next_tree, base_tree);
668 if (is_rebase_i(opts) && clean <= 0)
669 fputs(o.obuf.buf, stdout);
670 strbuf_release(&o.obuf);
672 if (clean < 0) {
673 rollback_lock_file(&index_lock);
674 return clean;
677 if (write_locked_index(r->index, &index_lock,
678 COMMIT_LOCK | SKIP_IF_UNCHANGED))
680 * TRANSLATORS: %s will be "revert", "cherry-pick" or
681 * "rebase".
683 return error(_("%s: Unable to write new index file"),
684 _(action_name(opts)));
686 if (!clean)
687 append_conflicts_hint(r->index, msgbuf,
688 opts->default_msg_cleanup);
690 return !clean;
693 static struct object_id *get_cache_tree_oid(struct index_state *istate)
695 if (!cache_tree_fully_valid(istate->cache_tree))
696 if (cache_tree_update(istate, 0)) {
697 error(_("unable to update cache tree"));
698 return NULL;
701 return &istate->cache_tree->oid;
704 static int is_index_unchanged(struct repository *r)
706 struct object_id head_oid, *cache_tree_oid;
707 struct commit *head_commit;
708 struct index_state *istate = r->index;
710 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
711 return error(_("could not resolve HEAD commit"));
713 head_commit = lookup_commit(r, &head_oid);
716 * If head_commit is NULL, check_commit, called from
717 * lookup_commit, would have indicated that head_commit is not
718 * a commit object already. parse_commit() will return failure
719 * without further complaints in such a case. Otherwise, if
720 * the commit is invalid, parse_commit() will complain. So
721 * there is nothing for us to say here. Just return failure.
723 if (parse_commit(head_commit))
724 return -1;
726 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
727 return -1;
729 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
732 static int write_author_script(const char *message)
734 struct strbuf buf = STRBUF_INIT;
735 const char *eol;
736 int res;
738 for (;;)
739 if (!*message || starts_with(message, "\n")) {
740 missing_author:
741 /* Missing 'author' line? */
742 unlink(rebase_path_author_script());
743 return 0;
744 } else if (skip_prefix(message, "author ", &message))
745 break;
746 else if ((eol = strchr(message, '\n')))
747 message = eol + 1;
748 else
749 goto missing_author;
751 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
752 while (*message && *message != '\n' && *message != '\r')
753 if (skip_prefix(message, " <", &message))
754 break;
755 else if (*message != '\'')
756 strbuf_addch(&buf, *(message++));
757 else
758 strbuf_addf(&buf, "'\\%c'", *(message++));
759 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
760 while (*message && *message != '\n' && *message != '\r')
761 if (skip_prefix(message, "> ", &message))
762 break;
763 else if (*message != '\'')
764 strbuf_addch(&buf, *(message++));
765 else
766 strbuf_addf(&buf, "'\\%c'", *(message++));
767 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
768 while (*message && *message != '\n' && *message != '\r')
769 if (*message != '\'')
770 strbuf_addch(&buf, *(message++));
771 else
772 strbuf_addf(&buf, "'\\%c'", *(message++));
773 strbuf_addch(&buf, '\'');
774 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
775 strbuf_release(&buf);
776 return res;
780 * Take a series of KEY='VALUE' lines where VALUE part is
781 * sq-quoted, and append <KEY, VALUE> at the end of the string list
783 static int parse_key_value_squoted(char *buf, struct string_list *list)
785 while (*buf) {
786 struct string_list_item *item;
787 char *np;
788 char *cp = strchr(buf, '=');
789 if (!cp) {
790 np = strchrnul(buf, '\n');
791 return error(_("no key present in '%.*s'"),
792 (int) (np - buf), buf);
794 np = strchrnul(cp, '\n');
795 *cp++ = '\0';
796 item = string_list_append(list, buf);
798 buf = np + (*np == '\n');
799 *np = '\0';
800 cp = sq_dequote(cp);
801 if (!cp)
802 return error(_("unable to dequote value of '%s'"),
803 item->string);
804 item->util = xstrdup(cp);
806 return 0;
810 * Reads and parses the state directory's "author-script" file, and sets name,
811 * email and date accordingly.
812 * Returns 0 on success, -1 if the file could not be parsed.
814 * The author script is of the format:
816 * GIT_AUTHOR_NAME='$author_name'
817 * GIT_AUTHOR_EMAIL='$author_email'
818 * GIT_AUTHOR_DATE='$author_date'
820 * where $author_name, $author_email and $author_date are quoted. We are strict
821 * with our parsing, as the file was meant to be eval'd in the now-removed
822 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
823 * from what this function expects, it is better to bail out than to do
824 * something that the user does not expect.
826 int read_author_script(const char *path, char **name, char **email, char **date,
827 int allow_missing)
829 struct strbuf buf = STRBUF_INIT;
830 struct string_list kv = STRING_LIST_INIT_DUP;
831 int retval = -1; /* assume failure */
832 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
834 if (strbuf_read_file(&buf, path, 256) <= 0) {
835 strbuf_release(&buf);
836 if (errno == ENOENT && allow_missing)
837 return 0;
838 else
839 return error_errno(_("could not open '%s' for reading"),
840 path);
843 if (parse_key_value_squoted(buf.buf, &kv))
844 goto finish;
846 for (i = 0; i < kv.nr; i++) {
847 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
848 if (name_i != -2)
849 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
850 else
851 name_i = i;
852 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
853 if (email_i != -2)
854 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
855 else
856 email_i = i;
857 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
858 if (date_i != -2)
859 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
860 else
861 date_i = i;
862 } else {
863 err = error(_("unknown variable '%s'"),
864 kv.items[i].string);
867 if (name_i == -2)
868 error(_("missing 'GIT_AUTHOR_NAME'"));
869 if (email_i == -2)
870 error(_("missing 'GIT_AUTHOR_EMAIL'"));
871 if (date_i == -2)
872 error(_("missing 'GIT_AUTHOR_DATE'"));
873 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
874 goto finish;
875 *name = kv.items[name_i].util;
876 *email = kv.items[email_i].util;
877 *date = kv.items[date_i].util;
878 retval = 0;
879 finish:
880 string_list_clear(&kv, !!retval);
881 strbuf_release(&buf);
882 return retval;
886 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
887 * file with shell quoting into struct strvec. Returns -1 on
888 * error, 0 otherwise.
890 static int read_env_script(struct strvec *env)
892 char *name, *email, *date;
894 if (read_author_script(rebase_path_author_script(),
895 &name, &email, &date, 0))
896 return -1;
898 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
899 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
900 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
901 free(name);
902 free(email);
903 free(date);
905 return 0;
908 static char *get_author(const char *message)
910 size_t len;
911 const char *a;
913 a = find_commit_header(message, "author", &len);
914 if (a)
915 return xmemdupz(a, len);
917 return NULL;
920 static const char *author_date_from_env_array(const struct strvec *env)
922 int i;
923 const char *date;
925 for (i = 0; i < env->nr; i++)
926 if (skip_prefix(env->v[i],
927 "GIT_AUTHOR_DATE=", &date))
928 return date;
930 * If GIT_AUTHOR_DATE is missing we should have already errored out when
931 * reading the script
933 BUG("GIT_AUTHOR_DATE missing from author script");
936 static const char staged_changes_advice[] =
937 N_("you have staged changes in your working tree\n"
938 "If these changes are meant to be squashed into the previous commit, run:\n"
939 "\n"
940 " git commit --amend %s\n"
941 "\n"
942 "If they are meant to go into a new commit, run:\n"
943 "\n"
944 " git commit %s\n"
945 "\n"
946 "In both cases, once you're done, continue with:\n"
947 "\n"
948 " git rebase --continue\n");
950 #define ALLOW_EMPTY (1<<0)
951 #define EDIT_MSG (1<<1)
952 #define AMEND_MSG (1<<2)
953 #define CLEANUP_MSG (1<<3)
954 #define VERIFY_MSG (1<<4)
955 #define CREATE_ROOT_COMMIT (1<<5)
956 #define VERBATIM_MSG (1<<6)
958 static int run_command_silent_on_success(struct child_process *cmd)
960 struct strbuf buf = STRBUF_INIT;
961 int rc;
963 cmd->stdout_to_stderr = 1;
964 rc = pipe_command(cmd,
965 NULL, 0,
966 NULL, 0,
967 &buf, 0);
969 if (rc)
970 fputs(buf.buf, stderr);
971 strbuf_release(&buf);
972 return rc;
976 * If we are cherry-pick, and if the merge did not result in
977 * hand-editing, we will hit this commit and inherit the original
978 * author date and name.
980 * If we are revert, or if our cherry-pick results in a hand merge,
981 * we had better say that the current user is responsible for that.
983 * An exception is when run_git_commit() is called during an
984 * interactive rebase: in that case, we will want to retain the
985 * author metadata.
987 static int run_git_commit(const char *defmsg,
988 struct replay_opts *opts,
989 unsigned int flags)
991 struct child_process cmd = CHILD_PROCESS_INIT;
993 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
994 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
996 cmd.git_cmd = 1;
998 if (is_rebase_i(opts) && !(!defmsg && (flags & AMEND_MSG)) &&
999 read_env_script(&cmd.env_array)) {
1000 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1002 return error(_(staged_changes_advice),
1003 gpg_opt, gpg_opt);
1006 if (opts->committer_date_is_author_date)
1007 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1008 opts->ignore_date ?
1009 "" :
1010 author_date_from_env_array(&cmd.env_array));
1011 if (opts->ignore_date)
1012 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1014 strvec_push(&cmd.args, "commit");
1016 if (!(flags & VERIFY_MSG))
1017 strvec_push(&cmd.args, "-n");
1018 if ((flags & AMEND_MSG))
1019 strvec_push(&cmd.args, "--amend");
1020 if (opts->gpg_sign)
1021 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1022 else
1023 strvec_push(&cmd.args, "--no-gpg-sign");
1024 if (defmsg)
1025 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1026 else if (!(flags & EDIT_MSG))
1027 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1028 if ((flags & CLEANUP_MSG))
1029 strvec_push(&cmd.args, "--cleanup=strip");
1030 if ((flags & VERBATIM_MSG))
1031 strvec_push(&cmd.args, "--cleanup=verbatim");
1032 if ((flags & EDIT_MSG))
1033 strvec_push(&cmd.args, "-e");
1034 else if (!(flags & CLEANUP_MSG) &&
1035 !opts->signoff && !opts->record_origin &&
1036 !opts->explicit_cleanup)
1037 strvec_push(&cmd.args, "--cleanup=verbatim");
1039 if ((flags & ALLOW_EMPTY))
1040 strvec_push(&cmd.args, "--allow-empty");
1042 if (!(flags & EDIT_MSG))
1043 strvec_push(&cmd.args, "--allow-empty-message");
1045 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1046 return run_command_silent_on_success(&cmd);
1047 else
1048 return run_command(&cmd);
1051 static int rest_is_empty(const struct strbuf *sb, int start)
1053 int i, eol;
1054 const char *nl;
1056 /* Check if the rest is just whitespace and Signed-off-by's. */
1057 for (i = start; i < sb->len; i++) {
1058 nl = memchr(sb->buf + i, '\n', sb->len - i);
1059 if (nl)
1060 eol = nl - sb->buf;
1061 else
1062 eol = sb->len;
1064 if (strlen(sign_off_header) <= eol - i &&
1065 starts_with(sb->buf + i, sign_off_header)) {
1066 i = eol;
1067 continue;
1069 while (i < eol)
1070 if (!isspace(sb->buf[i++]))
1071 return 0;
1074 return 1;
1077 void cleanup_message(struct strbuf *msgbuf,
1078 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1080 if (verbose || /* Truncate the message just before the diff, if any. */
1081 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1082 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1083 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1084 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1088 * Find out if the message in the strbuf contains only whitespace and
1089 * Signed-off-by lines.
1091 int message_is_empty(const struct strbuf *sb,
1092 enum commit_msg_cleanup_mode cleanup_mode)
1094 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1095 return 0;
1096 return rest_is_empty(sb, 0);
1100 * See if the user edited the message in the editor or left what
1101 * was in the template intact
1103 int template_untouched(const struct strbuf *sb, const char *template_file,
1104 enum commit_msg_cleanup_mode cleanup_mode)
1106 struct strbuf tmpl = STRBUF_INIT;
1107 const char *start;
1109 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1110 return 0;
1112 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1113 return 0;
1115 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1116 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1117 start = sb->buf;
1118 strbuf_release(&tmpl);
1119 return rest_is_empty(sb, start - sb->buf);
1122 int update_head_with_reflog(const struct commit *old_head,
1123 const struct object_id *new_head,
1124 const char *action, const struct strbuf *msg,
1125 struct strbuf *err)
1127 struct ref_transaction *transaction;
1128 struct strbuf sb = STRBUF_INIT;
1129 const char *nl;
1130 int ret = 0;
1132 if (action) {
1133 strbuf_addstr(&sb, action);
1134 strbuf_addstr(&sb, ": ");
1137 nl = strchr(msg->buf, '\n');
1138 if (nl) {
1139 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1140 } else {
1141 strbuf_addbuf(&sb, msg);
1142 strbuf_addch(&sb, '\n');
1145 transaction = ref_transaction_begin(err);
1146 if (!transaction ||
1147 ref_transaction_update(transaction, "HEAD", new_head,
1148 old_head ? &old_head->object.oid : null_oid(),
1149 0, sb.buf, err) ||
1150 ref_transaction_commit(transaction, err)) {
1151 ret = -1;
1153 ref_transaction_free(transaction);
1154 strbuf_release(&sb);
1156 return ret;
1159 static int run_rewrite_hook(const struct object_id *oldoid,
1160 const struct object_id *newoid)
1162 struct child_process proc = CHILD_PROCESS_INIT;
1163 const char *argv[3];
1164 int code;
1165 struct strbuf sb = STRBUF_INIT;
1167 argv[0] = find_hook("post-rewrite");
1168 if (!argv[0])
1169 return 0;
1171 argv[1] = "amend";
1172 argv[2] = NULL;
1174 proc.argv = argv;
1175 proc.in = -1;
1176 proc.stdout_to_stderr = 1;
1177 proc.trace2_hook_name = "post-rewrite";
1179 code = start_command(&proc);
1180 if (code)
1181 return code;
1182 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1183 sigchain_push(SIGPIPE, SIG_IGN);
1184 write_in_full(proc.in, sb.buf, sb.len);
1185 close(proc.in);
1186 strbuf_release(&sb);
1187 sigchain_pop(SIGPIPE);
1188 return finish_command(&proc);
1191 void commit_post_rewrite(struct repository *r,
1192 const struct commit *old_head,
1193 const struct object_id *new_head)
1195 struct notes_rewrite_cfg *cfg;
1197 cfg = init_copy_notes_for_rewrite("amend");
1198 if (cfg) {
1199 /* we are amending, so old_head is not NULL */
1200 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1201 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1203 run_rewrite_hook(&old_head->object.oid, new_head);
1206 static int run_prepare_commit_msg_hook(struct repository *r,
1207 struct strbuf *msg,
1208 const char *commit)
1210 int ret = 0;
1211 const char *name, *arg1 = NULL, *arg2 = NULL;
1213 name = git_path_commit_editmsg();
1214 if (write_message(msg->buf, msg->len, name, 0))
1215 return -1;
1217 if (commit) {
1218 arg1 = "commit";
1219 arg2 = commit;
1220 } else {
1221 arg1 = "message";
1223 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1224 arg1, arg2, NULL))
1225 ret = error(_("'prepare-commit-msg' hook failed"));
1227 return ret;
1230 static const char implicit_ident_advice_noconfig[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly. Run the\n"
1234 "following command and follow the instructions in your editor to edit\n"
1235 "your configuration file:\n"
1236 "\n"
1237 " git config --global --edit\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 " git commit --amend --reset-author\n");
1243 static const char implicit_ident_advice_config[] =
1244 N_("Your name and email address were configured automatically based\n"
1245 "on your username and hostname. Please check that they are accurate.\n"
1246 "You can suppress this message by setting them explicitly:\n"
1247 "\n"
1248 " git config --global user.name \"Your Name\"\n"
1249 " git config --global user.email you@example.com\n"
1250 "\n"
1251 "After doing this, you may fix the identity used for this commit with:\n"
1252 "\n"
1253 " git commit --amend --reset-author\n");
1255 static const char *implicit_ident_advice(void)
1257 char *user_config = interpolate_path("~/.gitconfig", 0);
1258 char *xdg_config = xdg_config_home("config");
1259 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1261 free(user_config);
1262 free(xdg_config);
1264 if (config_exists)
1265 return _(implicit_ident_advice_config);
1266 else
1267 return _(implicit_ident_advice_noconfig);
1271 void print_commit_summary(struct repository *r,
1272 const char *prefix,
1273 const struct object_id *oid,
1274 unsigned int flags)
1276 struct rev_info rev;
1277 struct commit *commit;
1278 struct strbuf format = STRBUF_INIT;
1279 const char *head;
1280 struct pretty_print_context pctx = {0};
1281 struct strbuf author_ident = STRBUF_INIT;
1282 struct strbuf committer_ident = STRBUF_INIT;
1284 commit = lookup_commit(r, oid);
1285 if (!commit)
1286 die(_("couldn't look up newly created commit"));
1287 if (parse_commit(commit))
1288 die(_("could not parse newly created commit"));
1290 strbuf_addstr(&format, "format:%h] %s");
1292 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1293 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1294 if (strbuf_cmp(&author_ident, &committer_ident)) {
1295 strbuf_addstr(&format, "\n Author: ");
1296 strbuf_addbuf_percentquote(&format, &author_ident);
1298 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1299 struct strbuf date = STRBUF_INIT;
1301 format_commit_message(commit, "%ad", &date, &pctx);
1302 strbuf_addstr(&format, "\n Date: ");
1303 strbuf_addbuf_percentquote(&format, &date);
1304 strbuf_release(&date);
1306 if (!committer_ident_sufficiently_given()) {
1307 strbuf_addstr(&format, "\n Committer: ");
1308 strbuf_addbuf_percentquote(&format, &committer_ident);
1309 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1310 strbuf_addch(&format, '\n');
1311 strbuf_addstr(&format, implicit_ident_advice());
1314 strbuf_release(&author_ident);
1315 strbuf_release(&committer_ident);
1317 repo_init_revisions(r, &rev, prefix);
1318 setup_revisions(0, NULL, &rev, NULL);
1320 rev.diff = 1;
1321 rev.diffopt.output_format =
1322 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1324 rev.verbose_header = 1;
1325 rev.show_root_diff = 1;
1326 get_commit_format(format.buf, &rev);
1327 rev.always_show_header = 0;
1328 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1329 rev.diffopt.break_opt = 0;
1330 diff_setup_done(&rev.diffopt);
1332 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1333 if (!head)
1334 die_errno(_("unable to resolve HEAD after creating commit"));
1335 if (!strcmp(head, "HEAD"))
1336 head = _("detached HEAD");
1337 else
1338 skip_prefix(head, "refs/heads/", &head);
1339 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1340 _(" (root-commit)") : "");
1342 if (!log_tree_commit(&rev, commit)) {
1343 rev.always_show_header = 1;
1344 rev.use_terminator = 1;
1345 log_tree_commit(&rev, commit);
1348 strbuf_release(&format);
1351 static int parse_head(struct repository *r, struct commit **head)
1353 struct commit *current_head;
1354 struct object_id oid;
1356 if (get_oid("HEAD", &oid)) {
1357 current_head = NULL;
1358 } else {
1359 current_head = lookup_commit_reference(r, &oid);
1360 if (!current_head)
1361 return error(_("could not parse HEAD"));
1362 if (!oideq(&oid, &current_head->object.oid)) {
1363 warning(_("HEAD %s is not a commit!"),
1364 oid_to_hex(&oid));
1366 if (parse_commit(current_head))
1367 return error(_("could not parse HEAD commit"));
1369 *head = current_head;
1371 return 0;
1375 * Try to commit without forking 'git commit'. In some cases we need
1376 * to run 'git commit' to display an error message
1378 * Returns:
1379 * -1 - error unable to commit
1380 * 0 - success
1381 * 1 - run 'git commit'
1383 static int try_to_commit(struct repository *r,
1384 struct strbuf *msg, const char *author,
1385 struct replay_opts *opts, unsigned int flags,
1386 struct object_id *oid)
1388 struct object_id tree;
1389 struct commit *current_head = NULL;
1390 struct commit_list *parents = NULL;
1391 struct commit_extra_header *extra = NULL;
1392 struct strbuf err = STRBUF_INIT;
1393 struct strbuf commit_msg = STRBUF_INIT;
1394 char *amend_author = NULL;
1395 const char *committer = NULL;
1396 const char *hook_commit = NULL;
1397 enum commit_msg_cleanup_mode cleanup;
1398 int res = 0;
1400 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1401 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1403 if (parse_head(r, &current_head))
1404 return -1;
1406 if (flags & AMEND_MSG) {
1407 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1408 const char *out_enc = get_commit_output_encoding();
1409 const char *message = logmsg_reencode(current_head, NULL,
1410 out_enc);
1412 if (!msg) {
1413 const char *orig_message = NULL;
1415 find_commit_subject(message, &orig_message);
1416 msg = &commit_msg;
1417 strbuf_addstr(msg, orig_message);
1418 hook_commit = "HEAD";
1420 author = amend_author = get_author(message);
1421 unuse_commit_buffer(current_head, message);
1422 if (!author) {
1423 res = error(_("unable to parse commit author"));
1424 goto out;
1426 parents = copy_commit_list(current_head->parents);
1427 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1428 } else if (current_head &&
1429 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1430 commit_list_insert(current_head, &parents);
1433 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1434 res = error(_("git write-tree failed to write a tree"));
1435 goto out;
1438 if (!(flags & ALLOW_EMPTY)) {
1439 struct commit *first_parent = current_head;
1441 if (flags & AMEND_MSG) {
1442 if (current_head->parents) {
1443 first_parent = current_head->parents->item;
1444 if (repo_parse_commit(r, first_parent)) {
1445 res = error(_("could not parse HEAD commit"));
1446 goto out;
1448 } else {
1449 first_parent = NULL;
1452 if (oideq(first_parent
1453 ? get_commit_tree_oid(first_parent)
1454 : the_hash_algo->empty_tree,
1455 &tree)) {
1456 res = 1; /* run 'git commit' to display error message */
1457 goto out;
1461 if (find_hook("prepare-commit-msg")) {
1462 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1463 if (res)
1464 goto out;
1465 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1466 2048) < 0) {
1467 res = error_errno(_("unable to read commit message "
1468 "from '%s'"),
1469 git_path_commit_editmsg());
1470 goto out;
1472 msg = &commit_msg;
1475 if (flags & CLEANUP_MSG)
1476 cleanup = COMMIT_MSG_CLEANUP_ALL;
1477 else if (flags & VERBATIM_MSG)
1478 cleanup = COMMIT_MSG_CLEANUP_NONE;
1479 else if ((opts->signoff || opts->record_origin) &&
1480 !opts->explicit_cleanup)
1481 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1482 else
1483 cleanup = opts->default_msg_cleanup;
1485 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1486 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1487 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1488 res = 1; /* run 'git commit' to display error message */
1489 goto out;
1492 if (opts->committer_date_is_author_date) {
1493 struct ident_split id;
1494 struct strbuf date = STRBUF_INIT;
1496 if (!opts->ignore_date) {
1497 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1498 res = error(_("invalid author identity '%s'"),
1499 author);
1500 goto out;
1502 if (!id.date_begin) {
1503 res = error(_(
1504 "corrupt author: missing date information"));
1505 goto out;
1507 strbuf_addf(&date, "@%.*s %.*s",
1508 (int)(id.date_end - id.date_begin),
1509 id.date_begin,
1510 (int)(id.tz_end - id.tz_begin),
1511 id.tz_begin);
1512 } else {
1513 reset_ident_date();
1515 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1516 getenv("GIT_COMMITTER_EMAIL"),
1517 WANT_COMMITTER_IDENT,
1518 opts->ignore_date ? NULL : date.buf,
1519 IDENT_STRICT);
1520 strbuf_release(&date);
1521 } else {
1522 reset_ident_date();
1525 if (opts->ignore_date) {
1526 struct ident_split id;
1527 char *name, *email;
1529 if (split_ident_line(&id, author, strlen(author)) < 0) {
1530 error(_("invalid author identity '%s'"), author);
1531 goto out;
1533 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1534 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1535 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1536 IDENT_STRICT);
1537 free(name);
1538 free(email);
1541 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1542 author, committer, opts->gpg_sign, extra)) {
1543 res = error(_("failed to write commit object"));
1544 goto out;
1547 if (update_head_with_reflog(current_head, oid,
1548 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1549 res = error("%s", err.buf);
1550 goto out;
1553 run_commit_hook(0, r->index_file, "post-commit", NULL);
1554 if (flags & AMEND_MSG)
1555 commit_post_rewrite(r, current_head, oid);
1557 out:
1558 free_commit_extra_headers(extra);
1559 strbuf_release(&err);
1560 strbuf_release(&commit_msg);
1561 free(amend_author);
1563 return res;
1566 static int write_rebase_head(struct object_id *oid)
1568 if (update_ref("rebase", "REBASE_HEAD", oid,
1569 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1570 return error(_("could not update %s"), "REBASE_HEAD");
1572 return 0;
1575 static int do_commit(struct repository *r,
1576 const char *msg_file, const char *author,
1577 struct replay_opts *opts, unsigned int flags,
1578 struct object_id *oid)
1580 int res = 1;
1582 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1583 struct object_id oid;
1584 struct strbuf sb = STRBUF_INIT;
1586 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1587 return error_errno(_("unable to read commit message "
1588 "from '%s'"),
1589 msg_file);
1591 res = try_to_commit(r, msg_file ? &sb : NULL,
1592 author, opts, flags, &oid);
1593 strbuf_release(&sb);
1594 if (!res) {
1595 refs_delete_ref(get_main_ref_store(r), "",
1596 "CHERRY_PICK_HEAD", NULL, 0);
1597 unlink(git_path_merge_msg(r));
1598 if (!is_rebase_i(opts))
1599 print_commit_summary(r, NULL, &oid,
1600 SUMMARY_SHOW_AUTHOR_DATE);
1601 return res;
1604 if (res == 1) {
1605 if (is_rebase_i(opts) && oid)
1606 if (write_rebase_head(oid))
1607 return -1;
1608 return run_git_commit(msg_file, opts, flags);
1611 return res;
1614 static int is_original_commit_empty(struct commit *commit)
1616 const struct object_id *ptree_oid;
1618 if (parse_commit(commit))
1619 return error(_("could not parse commit %s"),
1620 oid_to_hex(&commit->object.oid));
1621 if (commit->parents) {
1622 struct commit *parent = commit->parents->item;
1623 if (parse_commit(parent))
1624 return error(_("could not parse parent commit %s"),
1625 oid_to_hex(&parent->object.oid));
1626 ptree_oid = get_commit_tree_oid(parent);
1627 } else {
1628 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1631 return oideq(ptree_oid, get_commit_tree_oid(commit));
1635 * Should empty commits be allowed? Return status:
1636 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1637 * 0: Halt on empty commit
1638 * 1: Allow empty commit
1639 * 2: Drop empty commit
1641 static int allow_empty(struct repository *r,
1642 struct replay_opts *opts,
1643 struct commit *commit)
1645 int index_unchanged, originally_empty;
1648 * Four cases:
1650 * (1) we do not allow empty at all and error out.
1652 * (2) we allow ones that were initially empty, and
1653 * just drop the ones that become empty
1655 * (3) we allow ones that were initially empty, but
1656 * halt for the ones that become empty;
1658 * (4) we allow both.
1660 if (!opts->allow_empty)
1661 return 0; /* let "git commit" barf as necessary */
1663 index_unchanged = is_index_unchanged(r);
1664 if (index_unchanged < 0)
1665 return index_unchanged;
1666 if (!index_unchanged)
1667 return 0; /* we do not have to say --allow-empty */
1669 if (opts->keep_redundant_commits)
1670 return 1;
1672 originally_empty = is_original_commit_empty(commit);
1673 if (originally_empty < 0)
1674 return originally_empty;
1675 if (originally_empty)
1676 return 1;
1677 else if (opts->drop_redundant_commits)
1678 return 2;
1679 else
1680 return 0;
1683 static struct {
1684 char c;
1685 const char *str;
1686 } todo_command_info[] = {
1687 { 'p', "pick" },
1688 { 0, "revert" },
1689 { 'e', "edit" },
1690 { 'r', "reword" },
1691 { 'f', "fixup" },
1692 { 's', "squash" },
1693 { 'x', "exec" },
1694 { 'b', "break" },
1695 { 'l', "label" },
1696 { 't', "reset" },
1697 { 'm', "merge" },
1698 { 0, "noop" },
1699 { 'd', "drop" },
1700 { 0, NULL }
1703 static const char *command_to_string(const enum todo_command command)
1705 if (command < TODO_COMMENT)
1706 return todo_command_info[command].str;
1707 die(_("unknown command: %d"), command);
1710 static char command_to_char(const enum todo_command command)
1712 if (command < TODO_COMMENT)
1713 return todo_command_info[command].c;
1714 return comment_line_char;
1717 static int is_noop(const enum todo_command command)
1719 return TODO_NOOP <= command;
1722 static int is_fixup(enum todo_command command)
1724 return command == TODO_FIXUP || command == TODO_SQUASH;
1727 /* Does this command create a (non-merge) commit? */
1728 static int is_pick_or_similar(enum todo_command command)
1730 switch (command) {
1731 case TODO_PICK:
1732 case TODO_REVERT:
1733 case TODO_EDIT:
1734 case TODO_REWORD:
1735 case TODO_FIXUP:
1736 case TODO_SQUASH:
1737 return 1;
1738 default:
1739 return 0;
1743 enum todo_item_flags {
1744 TODO_EDIT_MERGE_MSG = (1 << 0),
1745 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1746 TODO_EDIT_FIXUP_MSG = (1 << 2),
1749 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1750 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1751 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1752 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1753 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1755 static int is_fixup_flag(enum todo_command command, unsigned flag)
1757 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1758 (flag & TODO_EDIT_FIXUP_MSG));
1762 * Wrapper around strbuf_add_commented_lines() which avoids double
1763 * commenting commit subjects.
1765 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1767 const char *s = str;
1768 while (len > 0 && s[0] == comment_line_char) {
1769 size_t count;
1770 const char *n = memchr(s, '\n', len);
1771 if (!n)
1772 count = len;
1773 else
1774 count = n - s + 1;
1775 strbuf_add(buf, s, count);
1776 s += count;
1777 len -= count;
1779 strbuf_add_commented_lines(buf, s, len);
1782 /* Does the current fixup chain contain a squash command? */
1783 static int seen_squash(struct replay_opts *opts)
1785 return starts_with(opts->current_fixups.buf, "squash") ||
1786 strstr(opts->current_fixups.buf, "\nsquash");
1789 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1791 strbuf_setlen(buf1, 2);
1792 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1793 strbuf_addch(buf1, '\n');
1794 strbuf_setlen(buf2, 2);
1795 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1796 strbuf_addch(buf2, '\n');
1800 * Comment out any un-commented commit messages, updating the message comments
1801 * to say they will be skipped but do not comment out the empty lines that
1802 * surround commit messages and their comments.
1804 static void update_squash_message_for_fixup(struct strbuf *msg)
1806 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1807 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1808 const char *s, *start;
1809 char *orig_msg;
1810 size_t orig_msg_len;
1811 int i = 1;
1813 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1814 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1815 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1816 while (s) {
1817 const char *next;
1818 size_t off;
1819 if (skip_prefix(s, buf1.buf, &next)) {
1821 * Copy the last message, preserving the blank line
1822 * preceding the current line
1824 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1825 copy_lines(msg, start, s - start - off);
1826 if (off)
1827 strbuf_addch(msg, '\n');
1829 * The next message needs to be commented out but the
1830 * message header is already commented out so just copy
1831 * it and the blank line that follows it.
1833 strbuf_addbuf(msg, &buf2);
1834 if (*next == '\n')
1835 strbuf_addch(msg, *next++);
1836 start = s = next;
1837 copy_lines = add_commented_lines;
1838 update_comment_bufs(&buf1, &buf2, ++i);
1839 } else if (skip_prefix(s, buf2.buf, &next)) {
1840 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1841 copy_lines(msg, start, s - start - off);
1842 start = s - off;
1843 s = next;
1844 copy_lines = strbuf_add;
1845 update_comment_bufs(&buf1, &buf2, ++i);
1846 } else {
1847 s = strchr(s, '\n');
1848 if (s)
1849 s++;
1852 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1853 free(orig_msg);
1854 strbuf_release(&buf1);
1855 strbuf_release(&buf2);
1858 static int append_squash_message(struct strbuf *buf, const char *body,
1859 enum todo_command command, struct replay_opts *opts,
1860 unsigned flag)
1862 const char *fixup_msg;
1863 size_t commented_len = 0, fixup_off;
1865 * amend is non-interactive and not normally used with fixup!
1866 * or squash! commits, so only comment out those subjects when
1867 * squashing commit messages.
1869 if (starts_with(body, "amend!") ||
1870 ((command == TODO_SQUASH || seen_squash(opts)) &&
1871 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1872 commented_len = commit_subject_length(body);
1874 strbuf_addf(buf, "\n%c ", comment_line_char);
1875 strbuf_addf(buf, _(nth_commit_msg_fmt),
1876 ++opts->current_fixup_count + 1);
1877 strbuf_addstr(buf, "\n\n");
1878 strbuf_add_commented_lines(buf, body, commented_len);
1879 /* buf->buf may be reallocated so store an offset into the buffer */
1880 fixup_off = buf->len;
1881 strbuf_addstr(buf, body + commented_len);
1883 /* fixup -C after squash behaves like squash */
1884 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1886 * We're replacing the commit message so we need to
1887 * append the Signed-off-by: trailer if the user
1888 * requested '--signoff'.
1890 if (opts->signoff)
1891 append_signoff(buf, 0, 0);
1893 if ((command == TODO_FIXUP) &&
1894 (flag & TODO_REPLACE_FIXUP_MSG) &&
1895 (file_exists(rebase_path_fixup_msg()) ||
1896 !file_exists(rebase_path_squash_msg()))) {
1897 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1898 if (write_message(fixup_msg, strlen(fixup_msg),
1899 rebase_path_fixup_msg(), 0) < 0)
1900 return error(_("cannot write '%s'"),
1901 rebase_path_fixup_msg());
1902 } else {
1903 unlink(rebase_path_fixup_msg());
1905 } else {
1906 unlink(rebase_path_fixup_msg());
1909 return 0;
1912 static int update_squash_messages(struct repository *r,
1913 enum todo_command command,
1914 struct commit *commit,
1915 struct replay_opts *opts,
1916 unsigned flag)
1918 struct strbuf buf = STRBUF_INIT;
1919 int res = 0;
1920 const char *message, *body;
1921 const char *encoding = get_commit_output_encoding();
1923 if (opts->current_fixup_count > 0) {
1924 struct strbuf header = STRBUF_INIT;
1925 char *eol;
1927 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1928 return error(_("could not read '%s'"),
1929 rebase_path_squash_msg());
1931 eol = buf.buf[0] != comment_line_char ?
1932 buf.buf : strchrnul(buf.buf, '\n');
1934 strbuf_addf(&header, "%c ", comment_line_char);
1935 strbuf_addf(&header, _(combined_commit_msg_fmt),
1936 opts->current_fixup_count + 2);
1937 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1938 strbuf_release(&header);
1939 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1940 update_squash_message_for_fixup(&buf);
1941 } else {
1942 struct object_id head;
1943 struct commit *head_commit;
1944 const char *head_message, *body;
1946 if (get_oid("HEAD", &head))
1947 return error(_("need a HEAD to fixup"));
1948 if (!(head_commit = lookup_commit_reference(r, &head)))
1949 return error(_("could not read HEAD"));
1950 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1951 return error(_("could not read HEAD's commit message"));
1953 find_commit_subject(head_message, &body);
1954 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1955 rebase_path_fixup_msg(), 0) < 0) {
1956 unuse_commit_buffer(head_commit, head_message);
1957 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1959 strbuf_addf(&buf, "%c ", comment_line_char);
1960 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1961 strbuf_addf(&buf, "\n%c ", comment_line_char);
1962 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1963 _(skip_first_commit_msg_str) :
1964 _(first_commit_msg_str));
1965 strbuf_addstr(&buf, "\n\n");
1966 if (is_fixup_flag(command, flag))
1967 strbuf_add_commented_lines(&buf, body, strlen(body));
1968 else
1969 strbuf_addstr(&buf, body);
1971 unuse_commit_buffer(head_commit, head_message);
1974 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1975 return error(_("could not read commit message of %s"),
1976 oid_to_hex(&commit->object.oid));
1977 find_commit_subject(message, &body);
1979 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1980 res = append_squash_message(&buf, body, command, opts, flag);
1981 } else if (command == TODO_FIXUP) {
1982 strbuf_addf(&buf, "\n%c ", comment_line_char);
1983 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1984 ++opts->current_fixup_count + 1);
1985 strbuf_addstr(&buf, "\n\n");
1986 strbuf_add_commented_lines(&buf, body, strlen(body));
1987 } else
1988 return error(_("unknown command: %d"), command);
1989 unuse_commit_buffer(commit, message);
1991 if (!res)
1992 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1994 strbuf_release(&buf);
1996 if (!res) {
1997 strbuf_addf(&opts->current_fixups, "%s%s %s",
1998 opts->current_fixups.len ? "\n" : "",
1999 command_to_string(command),
2000 oid_to_hex(&commit->object.oid));
2001 res = write_message(opts->current_fixups.buf,
2002 opts->current_fixups.len,
2003 rebase_path_current_fixups(), 0);
2006 return res;
2009 static void flush_rewritten_pending(void)
2011 struct strbuf buf = STRBUF_INIT;
2012 struct object_id newoid;
2013 FILE *out;
2015 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2016 !get_oid("HEAD", &newoid) &&
2017 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2018 char *bol = buf.buf, *eol;
2020 while (*bol) {
2021 eol = strchrnul(bol, '\n');
2022 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2023 bol, oid_to_hex(&newoid));
2024 if (!*eol)
2025 break;
2026 bol = eol + 1;
2028 fclose(out);
2029 unlink(rebase_path_rewritten_pending());
2031 strbuf_release(&buf);
2034 static void record_in_rewritten(struct object_id *oid,
2035 enum todo_command next_command)
2037 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2039 if (!out)
2040 return;
2042 fprintf(out, "%s\n", oid_to_hex(oid));
2043 fclose(out);
2045 if (!is_fixup(next_command))
2046 flush_rewritten_pending();
2049 static int should_edit(struct replay_opts *opts) {
2050 if (opts->edit < 0)
2052 * Note that we only handle the case of non-conflicted
2053 * commits; continue_single_pick() handles the conflicted
2054 * commits itself instead of calling this function.
2056 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2057 return opts->edit;
2060 static int do_pick_commit(struct repository *r,
2061 struct todo_item *item,
2062 struct replay_opts *opts,
2063 int final_fixup, int *check_todo)
2065 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2066 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2067 struct object_id head;
2068 struct commit *base, *next, *parent;
2069 const char *base_label, *next_label;
2070 char *author = NULL;
2071 struct commit_message msg = { NULL, NULL, NULL, NULL };
2072 struct strbuf msgbuf = STRBUF_INIT;
2073 int res, unborn = 0, reword = 0, allow, drop_commit;
2074 enum todo_command command = item->command;
2075 struct commit *commit = item->commit;
2077 if (opts->no_commit) {
2079 * We do not intend to commit immediately. We just want to
2080 * merge the differences in, so let's compute the tree
2081 * that represents the "current" state for the merge machinery
2082 * to work on.
2084 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2085 return error(_("your index file is unmerged."));
2086 } else {
2087 unborn = get_oid("HEAD", &head);
2088 /* Do we want to generate a root commit? */
2089 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2090 oideq(&head, &opts->squash_onto)) {
2091 if (is_fixup(command))
2092 return error(_("cannot fixup root commit"));
2093 flags |= CREATE_ROOT_COMMIT;
2094 unborn = 1;
2095 } else if (unborn)
2096 oidcpy(&head, the_hash_algo->empty_tree);
2097 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2098 NULL, 0))
2099 return error_dirty_index(r, opts);
2101 discard_index(r->index);
2103 if (!commit->parents)
2104 parent = NULL;
2105 else if (commit->parents->next) {
2106 /* Reverting or cherry-picking a merge commit */
2107 int cnt;
2108 struct commit_list *p;
2110 if (!opts->mainline)
2111 return error(_("commit %s is a merge but no -m option was given."),
2112 oid_to_hex(&commit->object.oid));
2114 for (cnt = 1, p = commit->parents;
2115 cnt != opts->mainline && p;
2116 cnt++)
2117 p = p->next;
2118 if (cnt != opts->mainline || !p)
2119 return error(_("commit %s does not have parent %d"),
2120 oid_to_hex(&commit->object.oid), opts->mainline);
2121 parent = p->item;
2122 } else if (1 < opts->mainline)
2124 * Non-first parent explicitly specified as mainline for
2125 * non-merge commit
2127 return error(_("commit %s does not have parent %d"),
2128 oid_to_hex(&commit->object.oid), opts->mainline);
2129 else
2130 parent = commit->parents->item;
2132 if (get_message(commit, &msg) != 0)
2133 return error(_("cannot get commit message for %s"),
2134 oid_to_hex(&commit->object.oid));
2136 if (opts->allow_ff && !is_fixup(command) &&
2137 ((parent && oideq(&parent->object.oid, &head)) ||
2138 (!parent && unborn))) {
2139 if (is_rebase_i(opts))
2140 write_author_script(msg.message);
2141 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2142 opts);
2143 if (res || command != TODO_REWORD)
2144 goto leave;
2145 reword = 1;
2146 msg_file = NULL;
2147 goto fast_forward_edit;
2149 if (parent && parse_commit(parent) < 0)
2150 /* TRANSLATORS: The first %s will be a "todo" command like
2151 "revert" or "pick", the second %s a SHA1. */
2152 return error(_("%s: cannot parse parent commit %s"),
2153 command_to_string(command),
2154 oid_to_hex(&parent->object.oid));
2157 * "commit" is an existing commit. We would want to apply
2158 * the difference it introduces since its first parent "prev"
2159 * on top of the current HEAD if we are cherry-pick. Or the
2160 * reverse of it if we are revert.
2163 if (command == TODO_REVERT) {
2164 base = commit;
2165 base_label = msg.label;
2166 next = parent;
2167 next_label = msg.parent_label;
2168 strbuf_addstr(&msgbuf, "Revert \"");
2169 strbuf_addstr(&msgbuf, msg.subject);
2170 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2171 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2173 if (commit->parents && commit->parents->next) {
2174 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2175 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2177 strbuf_addstr(&msgbuf, ".\n");
2178 } else {
2179 const char *p;
2181 base = parent;
2182 base_label = msg.parent_label;
2183 next = commit;
2184 next_label = msg.label;
2186 /* Append the commit log message to msgbuf. */
2187 if (find_commit_subject(msg.message, &p))
2188 strbuf_addstr(&msgbuf, p);
2190 if (opts->record_origin) {
2191 strbuf_complete_line(&msgbuf);
2192 if (!has_conforming_footer(&msgbuf, NULL, 0))
2193 strbuf_addch(&msgbuf, '\n');
2194 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2195 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2196 strbuf_addstr(&msgbuf, ")\n");
2198 if (!is_fixup(command))
2199 author = get_author(msg.message);
2202 if (command == TODO_REWORD)
2203 reword = 1;
2204 else if (is_fixup(command)) {
2205 if (update_squash_messages(r, command, commit,
2206 opts, item->flags))
2207 return -1;
2208 flags |= AMEND_MSG;
2209 if (!final_fixup)
2210 msg_file = rebase_path_squash_msg();
2211 else if (file_exists(rebase_path_fixup_msg())) {
2212 flags |= VERBATIM_MSG;
2213 msg_file = rebase_path_fixup_msg();
2214 } else {
2215 const char *dest = git_path_squash_msg(r);
2216 unlink(dest);
2217 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2218 return error(_("could not rename '%s' to '%s'"),
2219 rebase_path_squash_msg(), dest);
2220 unlink(git_path_merge_msg(r));
2221 msg_file = dest;
2222 flags |= EDIT_MSG;
2226 if (opts->signoff && !is_fixup(command))
2227 append_signoff(&msgbuf, 0, 0);
2229 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2230 res = -1;
2231 else if (!opts->strategy ||
2232 !strcmp(opts->strategy, "recursive") ||
2233 !strcmp(opts->strategy, "ort") ||
2234 command == TODO_REVERT) {
2235 res = do_recursive_merge(r, base, next, base_label, next_label,
2236 &head, &msgbuf, opts);
2237 if (res < 0)
2238 goto leave;
2240 res |= write_message(msgbuf.buf, msgbuf.len,
2241 git_path_merge_msg(r), 0);
2242 } else {
2243 struct commit_list *common = NULL;
2244 struct commit_list *remotes = NULL;
2246 res = write_message(msgbuf.buf, msgbuf.len,
2247 git_path_merge_msg(r), 0);
2249 commit_list_insert(base, &common);
2250 commit_list_insert(next, &remotes);
2251 res |= try_merge_command(r, opts->strategy,
2252 opts->xopts_nr, (const char **)opts->xopts,
2253 common, oid_to_hex(&head), remotes);
2254 free_commit_list(common);
2255 free_commit_list(remotes);
2257 strbuf_release(&msgbuf);
2260 * If the merge was clean or if it failed due to conflict, we write
2261 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2262 * However, if the merge did not even start, then we don't want to
2263 * write it at all.
2265 if ((command == TODO_PICK || command == TODO_REWORD ||
2266 command == TODO_EDIT) && !opts->no_commit &&
2267 (res == 0 || res == 1) &&
2268 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2269 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2270 res = -1;
2271 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2272 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2273 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2274 res = -1;
2276 if (res) {
2277 error(command == TODO_REVERT
2278 ? _("could not revert %s... %s")
2279 : _("could not apply %s... %s"),
2280 short_commit_name(commit), msg.subject);
2281 print_advice(r, res == 1, opts);
2282 repo_rerere(r, opts->allow_rerere_auto);
2283 goto leave;
2286 drop_commit = 0;
2287 allow = allow_empty(r, opts, commit);
2288 if (allow < 0) {
2289 res = allow;
2290 goto leave;
2291 } else if (allow == 1) {
2292 flags |= ALLOW_EMPTY;
2293 } else if (allow == 2) {
2294 drop_commit = 1;
2295 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2296 NULL, 0);
2297 unlink(git_path_merge_msg(r));
2298 unlink(git_path_auto_merge(r));
2299 fprintf(stderr,
2300 _("dropping %s %s -- patch contents already upstream\n"),
2301 oid_to_hex(&commit->object.oid), msg.subject);
2302 } /* else allow == 0 and there's nothing special to do */
2303 if (!opts->no_commit && !drop_commit) {
2304 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2305 res = do_commit(r, msg_file, author, opts, flags,
2306 commit? &commit->object.oid : NULL);
2307 else
2308 res = error(_("unable to parse commit author"));
2309 *check_todo = !!(flags & EDIT_MSG);
2310 if (!res && reword) {
2311 fast_forward_edit:
2312 res = run_git_commit(NULL, opts, EDIT_MSG |
2313 VERIFY_MSG | AMEND_MSG |
2314 (flags & ALLOW_EMPTY));
2315 *check_todo = 1;
2320 if (!res && final_fixup) {
2321 unlink(rebase_path_fixup_msg());
2322 unlink(rebase_path_squash_msg());
2323 unlink(rebase_path_current_fixups());
2324 strbuf_reset(&opts->current_fixups);
2325 opts->current_fixup_count = 0;
2328 leave:
2329 free_message(commit, &msg);
2330 free(author);
2331 update_abort_safety_file();
2333 return res;
2336 static int prepare_revs(struct replay_opts *opts)
2339 * picking (but not reverting) ranges (but not individual revisions)
2340 * should be done in reverse
2342 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2343 opts->revs->reverse ^= 1;
2345 if (prepare_revision_walk(opts->revs))
2346 return error(_("revision walk setup failed"));
2348 return 0;
2351 static int read_and_refresh_cache(struct repository *r,
2352 struct replay_opts *opts)
2354 struct lock_file index_lock = LOCK_INIT;
2355 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2356 if (repo_read_index(r) < 0) {
2357 rollback_lock_file(&index_lock);
2358 return error(_("git %s: failed to read the index"),
2359 _(action_name(opts)));
2361 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2362 if (index_fd >= 0) {
2363 if (write_locked_index(r->index, &index_lock,
2364 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2365 return error(_("git %s: failed to refresh the index"),
2366 _(action_name(opts)));
2369 return 0;
2372 void todo_list_release(struct todo_list *todo_list)
2374 strbuf_release(&todo_list->buf);
2375 FREE_AND_NULL(todo_list->items);
2376 todo_list->nr = todo_list->alloc = 0;
2379 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2381 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2382 todo_list->total_nr++;
2383 return todo_list->items + todo_list->nr++;
2386 const char *todo_item_get_arg(struct todo_list *todo_list,
2387 struct todo_item *item)
2389 return todo_list->buf.buf + item->arg_offset;
2392 static int is_command(enum todo_command command, const char **bol)
2394 const char *str = todo_command_info[command].str;
2395 const char nick = todo_command_info[command].c;
2396 const char *p = *bol + 1;
2398 return skip_prefix(*bol, str, bol) ||
2399 ((nick && **bol == nick) &&
2400 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2401 (*bol = p));
2404 static int parse_insn_line(struct repository *r, struct todo_item *item,
2405 const char *buf, const char *bol, char *eol)
2407 struct object_id commit_oid;
2408 char *end_of_object_name;
2409 int i, saved, status, padding;
2411 item->flags = 0;
2413 /* left-trim */
2414 bol += strspn(bol, " \t");
2416 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2417 item->command = TODO_COMMENT;
2418 item->commit = NULL;
2419 item->arg_offset = bol - buf;
2420 item->arg_len = eol - bol;
2421 return 0;
2424 for (i = 0; i < TODO_COMMENT; i++)
2425 if (is_command(i, &bol)) {
2426 item->command = i;
2427 break;
2429 if (i >= TODO_COMMENT)
2430 return -1;
2432 /* Eat up extra spaces/ tabs before object name */
2433 padding = strspn(bol, " \t");
2434 bol += padding;
2436 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2437 if (bol != eol)
2438 return error(_("%s does not accept arguments: '%s'"),
2439 command_to_string(item->command), bol);
2440 item->commit = NULL;
2441 item->arg_offset = bol - buf;
2442 item->arg_len = eol - bol;
2443 return 0;
2446 if (!padding)
2447 return error(_("missing arguments for %s"),
2448 command_to_string(item->command));
2450 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2451 item->command == TODO_RESET) {
2452 item->commit = NULL;
2453 item->arg_offset = bol - buf;
2454 item->arg_len = (int)(eol - bol);
2455 return 0;
2458 if (item->command == TODO_FIXUP) {
2459 if (skip_prefix(bol, "-C", &bol) &&
2460 (*bol == ' ' || *bol == '\t')) {
2461 bol += strspn(bol, " \t");
2462 item->flags |= TODO_REPLACE_FIXUP_MSG;
2463 } else if (skip_prefix(bol, "-c", &bol) &&
2464 (*bol == ' ' || *bol == '\t')) {
2465 bol += strspn(bol, " \t");
2466 item->flags |= TODO_EDIT_FIXUP_MSG;
2470 if (item->command == TODO_MERGE) {
2471 if (skip_prefix(bol, "-C", &bol))
2472 bol += strspn(bol, " \t");
2473 else if (skip_prefix(bol, "-c", &bol)) {
2474 bol += strspn(bol, " \t");
2475 item->flags |= TODO_EDIT_MERGE_MSG;
2476 } else {
2477 item->flags |= TODO_EDIT_MERGE_MSG;
2478 item->commit = NULL;
2479 item->arg_offset = bol - buf;
2480 item->arg_len = (int)(eol - bol);
2481 return 0;
2485 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2486 saved = *end_of_object_name;
2487 *end_of_object_name = '\0';
2488 status = get_oid(bol, &commit_oid);
2489 if (status < 0)
2490 error(_("could not parse '%s'"), bol); /* return later */
2491 *end_of_object_name = saved;
2493 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2494 item->arg_offset = bol - buf;
2495 item->arg_len = (int)(eol - bol);
2497 if (status < 0)
2498 return status;
2500 item->commit = lookup_commit_reference(r, &commit_oid);
2501 return item->commit ? 0 : -1;
2504 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2506 const char *todo_file, *bol;
2507 struct strbuf buf = STRBUF_INIT;
2508 int ret = 0;
2510 todo_file = git_path_todo_file();
2511 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2512 if (errno == ENOENT || errno == ENOTDIR)
2513 return -1;
2514 else
2515 return error_errno("unable to open '%s'", todo_file);
2517 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2518 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2519 *action = REPLAY_PICK;
2520 else if (is_command(TODO_REVERT, &bol) &&
2521 (*bol == ' ' || *bol == '\t'))
2522 *action = REPLAY_REVERT;
2523 else
2524 ret = -1;
2526 strbuf_release(&buf);
2528 return ret;
2531 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2532 struct todo_list *todo_list)
2534 struct todo_item *item;
2535 char *p = buf, *next_p;
2536 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2538 todo_list->current = todo_list->nr = 0;
2540 for (i = 1; *p; i++, p = next_p) {
2541 char *eol = strchrnul(p, '\n');
2543 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2545 if (p != eol && eol[-1] == '\r')
2546 eol--; /* strip Carriage Return */
2548 item = append_new_todo(todo_list);
2549 item->offset_in_buf = p - todo_list->buf.buf;
2550 if (parse_insn_line(r, item, buf, p, eol)) {
2551 res = error(_("invalid line %d: %.*s"),
2552 i, (int)(eol - p), p);
2553 item->command = TODO_COMMENT + 1;
2554 item->arg_offset = p - buf;
2555 item->arg_len = (int)(eol - p);
2556 item->commit = NULL;
2559 if (fixup_okay)
2560 ; /* do nothing */
2561 else if (is_fixup(item->command))
2562 return error(_("cannot '%s' without a previous commit"),
2563 command_to_string(item->command));
2564 else if (!is_noop(item->command))
2565 fixup_okay = 1;
2568 return res;
2571 static int count_commands(struct todo_list *todo_list)
2573 int count = 0, i;
2575 for (i = 0; i < todo_list->nr; i++)
2576 if (todo_list->items[i].command != TODO_COMMENT)
2577 count++;
2579 return count;
2582 static int get_item_line_offset(struct todo_list *todo_list, int index)
2584 return index < todo_list->nr ?
2585 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2588 static const char *get_item_line(struct todo_list *todo_list, int index)
2590 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2593 static int get_item_line_length(struct todo_list *todo_list, int index)
2595 return get_item_line_offset(todo_list, index + 1)
2596 - get_item_line_offset(todo_list, index);
2599 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2601 int fd;
2602 ssize_t len;
2604 fd = open(path, O_RDONLY);
2605 if (fd < 0)
2606 return error_errno(_("could not open '%s'"), path);
2607 len = strbuf_read(sb, fd, 0);
2608 close(fd);
2609 if (len < 0)
2610 return error(_("could not read '%s'."), path);
2611 return len;
2614 static int have_finished_the_last_pick(void)
2616 struct strbuf buf = STRBUF_INIT;
2617 const char *eol;
2618 const char *todo_path = git_path_todo_file();
2619 int ret = 0;
2621 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2622 if (errno == ENOENT) {
2623 return 0;
2624 } else {
2625 error_errno("unable to open '%s'", todo_path);
2626 return 0;
2629 /* If there is only one line then we are done */
2630 eol = strchr(buf.buf, '\n');
2631 if (!eol || !eol[1])
2632 ret = 1;
2634 strbuf_release(&buf);
2636 return ret;
2639 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2641 struct replay_opts opts = REPLAY_OPTS_INIT;
2642 int need_cleanup = 0;
2644 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2645 if (!refs_delete_ref(get_main_ref_store(r), "",
2646 "CHERRY_PICK_HEAD", NULL, 0) &&
2647 verbose)
2648 warning(_("cancelling a cherry picking in progress"));
2649 opts.action = REPLAY_PICK;
2650 need_cleanup = 1;
2653 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2654 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2655 NULL, 0) &&
2656 verbose)
2657 warning(_("cancelling a revert in progress"));
2658 opts.action = REPLAY_REVERT;
2659 need_cleanup = 1;
2662 unlink(git_path_auto_merge(r));
2664 if (!need_cleanup)
2665 return;
2667 if (!have_finished_the_last_pick())
2668 return;
2670 sequencer_remove_state(&opts);
2673 static void todo_list_write_total_nr(struct todo_list *todo_list)
2675 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2677 if (f) {
2678 fprintf(f, "%d\n", todo_list->total_nr);
2679 fclose(f);
2683 static int read_populate_todo(struct repository *r,
2684 struct todo_list *todo_list,
2685 struct replay_opts *opts)
2687 struct stat st;
2688 const char *todo_file = get_todo_path(opts);
2689 int res;
2691 strbuf_reset(&todo_list->buf);
2692 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2693 return -1;
2695 res = stat(todo_file, &st);
2696 if (res)
2697 return error(_("could not stat '%s'"), todo_file);
2698 fill_stat_data(&todo_list->stat, &st);
2700 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2701 if (res) {
2702 if (is_rebase_i(opts))
2703 return error(_("please fix this using "
2704 "'git rebase --edit-todo'."));
2705 return error(_("unusable instruction sheet: '%s'"), todo_file);
2708 if (!todo_list->nr &&
2709 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2710 return error(_("no commits parsed."));
2712 if (!is_rebase_i(opts)) {
2713 enum todo_command valid =
2714 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2715 int i;
2717 for (i = 0; i < todo_list->nr; i++)
2718 if (valid == todo_list->items[i].command)
2719 continue;
2720 else if (valid == TODO_PICK)
2721 return error(_("cannot cherry-pick during a revert."));
2722 else
2723 return error(_("cannot revert during a cherry-pick."));
2726 if (is_rebase_i(opts)) {
2727 struct todo_list done = TODO_LIST_INIT;
2729 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2730 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2731 todo_list->done_nr = count_commands(&done);
2732 else
2733 todo_list->done_nr = 0;
2735 todo_list->total_nr = todo_list->done_nr
2736 + count_commands(todo_list);
2737 todo_list_release(&done);
2739 todo_list_write_total_nr(todo_list);
2742 return 0;
2745 static int git_config_string_dup(char **dest,
2746 const char *var, const char *value)
2748 if (!value)
2749 return config_error_nonbool(var);
2750 free(*dest);
2751 *dest = xstrdup(value);
2752 return 0;
2755 static int populate_opts_cb(const char *key, const char *value, void *data)
2757 struct replay_opts *opts = data;
2758 int error_flag = 1;
2760 if (!value)
2761 error_flag = 0;
2762 else if (!strcmp(key, "options.no-commit"))
2763 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2764 else if (!strcmp(key, "options.edit"))
2765 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2766 else if (!strcmp(key, "options.allow-empty"))
2767 opts->allow_empty =
2768 git_config_bool_or_int(key, value, &error_flag);
2769 else if (!strcmp(key, "options.allow-empty-message"))
2770 opts->allow_empty_message =
2771 git_config_bool_or_int(key, value, &error_flag);
2772 else if (!strcmp(key, "options.keep-redundant-commits"))
2773 opts->keep_redundant_commits =
2774 git_config_bool_or_int(key, value, &error_flag);
2775 else if (!strcmp(key, "options.signoff"))
2776 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2777 else if (!strcmp(key, "options.record-origin"))
2778 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2779 else if (!strcmp(key, "options.allow-ff"))
2780 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2781 else if (!strcmp(key, "options.mainline"))
2782 opts->mainline = git_config_int(key, value);
2783 else if (!strcmp(key, "options.strategy"))
2784 git_config_string_dup(&opts->strategy, key, value);
2785 else if (!strcmp(key, "options.gpg-sign"))
2786 git_config_string_dup(&opts->gpg_sign, key, value);
2787 else if (!strcmp(key, "options.strategy-option")) {
2788 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2789 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2790 } else if (!strcmp(key, "options.allow-rerere-auto"))
2791 opts->allow_rerere_auto =
2792 git_config_bool_or_int(key, value, &error_flag) ?
2793 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2794 else if (!strcmp(key, "options.default-msg-cleanup")) {
2795 opts->explicit_cleanup = 1;
2796 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2797 } else
2798 return error(_("invalid key: %s"), key);
2800 if (!error_flag)
2801 return error(_("invalid value for %s: %s"), key, value);
2803 return 0;
2806 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2808 int i;
2809 char *strategy_opts_string = raw_opts;
2811 if (*strategy_opts_string == ' ')
2812 strategy_opts_string++;
2814 opts->xopts_nr = split_cmdline(strategy_opts_string,
2815 (const char ***)&opts->xopts);
2816 for (i = 0; i < opts->xopts_nr; i++) {
2817 const char *arg = opts->xopts[i];
2819 skip_prefix(arg, "--", &arg);
2820 opts->xopts[i] = xstrdup(arg);
2824 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2826 strbuf_reset(buf);
2827 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2828 return;
2829 opts->strategy = strbuf_detach(buf, NULL);
2830 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2831 return;
2833 parse_strategy_opts(opts, buf->buf);
2836 static int read_populate_opts(struct replay_opts *opts)
2838 if (is_rebase_i(opts)) {
2839 struct strbuf buf = STRBUF_INIT;
2840 int ret = 0;
2842 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2843 READ_ONELINER_SKIP_IF_EMPTY)) {
2844 if (!starts_with(buf.buf, "-S"))
2845 strbuf_reset(&buf);
2846 else {
2847 free(opts->gpg_sign);
2848 opts->gpg_sign = xstrdup(buf.buf + 2);
2850 strbuf_reset(&buf);
2853 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2854 READ_ONELINER_SKIP_IF_EMPTY)) {
2855 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2856 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2857 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2858 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2859 strbuf_reset(&buf);
2862 if (file_exists(rebase_path_verbose()))
2863 opts->verbose = 1;
2865 if (file_exists(rebase_path_quiet()))
2866 opts->quiet = 1;
2868 if (file_exists(rebase_path_signoff())) {
2869 opts->allow_ff = 0;
2870 opts->signoff = 1;
2873 if (file_exists(rebase_path_cdate_is_adate())) {
2874 opts->allow_ff = 0;
2875 opts->committer_date_is_author_date = 1;
2878 if (file_exists(rebase_path_ignore_date())) {
2879 opts->allow_ff = 0;
2880 opts->ignore_date = 1;
2883 if (file_exists(rebase_path_reschedule_failed_exec()))
2884 opts->reschedule_failed_exec = 1;
2885 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2886 opts->reschedule_failed_exec = 0;
2888 if (file_exists(rebase_path_drop_redundant_commits()))
2889 opts->drop_redundant_commits = 1;
2891 if (file_exists(rebase_path_keep_redundant_commits()))
2892 opts->keep_redundant_commits = 1;
2894 read_strategy_opts(opts, &buf);
2895 strbuf_reset(&buf);
2897 if (read_oneliner(&opts->current_fixups,
2898 rebase_path_current_fixups(),
2899 READ_ONELINER_SKIP_IF_EMPTY)) {
2900 const char *p = opts->current_fixups.buf;
2901 opts->current_fixup_count = 1;
2902 while ((p = strchr(p, '\n'))) {
2903 opts->current_fixup_count++;
2904 p++;
2908 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2909 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2910 ret = error(_("unusable squash-onto"));
2911 goto done_rebase_i;
2913 opts->have_squash_onto = 1;
2916 done_rebase_i:
2917 strbuf_release(&buf);
2918 return ret;
2921 if (!file_exists(git_path_opts_file()))
2922 return 0;
2924 * The function git_parse_source(), called from git_config_from_file(),
2925 * may die() in case of a syntactically incorrect file. We do not care
2926 * about this case, though, because we wrote that file ourselves, so we
2927 * are pretty certain that it is syntactically correct.
2929 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2930 return error(_("malformed options sheet: '%s'"),
2931 git_path_opts_file());
2932 return 0;
2935 static void write_strategy_opts(struct replay_opts *opts)
2937 int i;
2938 struct strbuf buf = STRBUF_INIT;
2940 for (i = 0; i < opts->xopts_nr; ++i)
2941 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2943 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2944 strbuf_release(&buf);
2947 int write_basic_state(struct replay_opts *opts, const char *head_name,
2948 struct commit *onto, const struct object_id *orig_head)
2950 if (head_name)
2951 write_file(rebase_path_head_name(), "%s\n", head_name);
2952 if (onto)
2953 write_file(rebase_path_onto(), "%s\n",
2954 oid_to_hex(&onto->object.oid));
2955 if (orig_head)
2956 write_file(rebase_path_orig_head(), "%s\n",
2957 oid_to_hex(orig_head));
2959 if (opts->quiet)
2960 write_file(rebase_path_quiet(), "%s", "");
2961 if (opts->verbose)
2962 write_file(rebase_path_verbose(), "%s", "");
2963 if (opts->strategy)
2964 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2965 if (opts->xopts_nr > 0)
2966 write_strategy_opts(opts);
2968 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2969 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2970 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2971 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2973 if (opts->gpg_sign)
2974 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2975 if (opts->signoff)
2976 write_file(rebase_path_signoff(), "--signoff\n");
2977 if (opts->drop_redundant_commits)
2978 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2979 if (opts->keep_redundant_commits)
2980 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2981 if (opts->committer_date_is_author_date)
2982 write_file(rebase_path_cdate_is_adate(), "%s", "");
2983 if (opts->ignore_date)
2984 write_file(rebase_path_ignore_date(), "%s", "");
2985 if (opts->reschedule_failed_exec)
2986 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2987 else
2988 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2990 return 0;
2993 static int walk_revs_populate_todo(struct todo_list *todo_list,
2994 struct replay_opts *opts)
2996 enum todo_command command = opts->action == REPLAY_PICK ?
2997 TODO_PICK : TODO_REVERT;
2998 const char *command_string = todo_command_info[command].str;
2999 const char *encoding;
3000 struct commit *commit;
3002 if (prepare_revs(opts))
3003 return -1;
3005 encoding = get_log_output_encoding();
3007 while ((commit = get_revision(opts->revs))) {
3008 struct todo_item *item = append_new_todo(todo_list);
3009 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3010 const char *subject;
3011 int subject_len;
3013 item->command = command;
3014 item->commit = commit;
3015 item->arg_offset = 0;
3016 item->arg_len = 0;
3017 item->offset_in_buf = todo_list->buf.len;
3018 subject_len = find_commit_subject(commit_buffer, &subject);
3019 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3020 short_commit_name(commit), subject_len, subject);
3021 unuse_commit_buffer(commit, commit_buffer);
3024 if (!todo_list->nr)
3025 return error(_("empty commit set passed"));
3027 return 0;
3030 static int create_seq_dir(struct repository *r)
3032 enum replay_action action;
3033 const char *in_progress_error = NULL;
3034 const char *in_progress_advice = NULL;
3035 unsigned int advise_skip =
3036 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3037 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3039 if (!sequencer_get_last_command(r, &action)) {
3040 switch (action) {
3041 case REPLAY_REVERT:
3042 in_progress_error = _("revert is already in progress");
3043 in_progress_advice =
3044 _("try \"git revert (--continue | %s--abort | --quit)\"");
3045 break;
3046 case REPLAY_PICK:
3047 in_progress_error = _("cherry-pick is already in progress");
3048 in_progress_advice =
3049 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3050 break;
3051 default:
3052 BUG("unexpected action in create_seq_dir");
3055 if (in_progress_error) {
3056 error("%s", in_progress_error);
3057 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3058 advise(in_progress_advice,
3059 advise_skip ? "--skip | " : "");
3060 return -1;
3062 if (mkdir(git_path_seq_dir(), 0777) < 0)
3063 return error_errno(_("could not create sequencer directory '%s'"),
3064 git_path_seq_dir());
3066 return 0;
3069 static int save_head(const char *head)
3071 struct lock_file head_lock = LOCK_INIT;
3072 struct strbuf buf = STRBUF_INIT;
3073 int fd;
3074 ssize_t written;
3076 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3077 if (fd < 0)
3078 return error_errno(_("could not lock HEAD"));
3079 strbuf_addf(&buf, "%s\n", head);
3080 written = write_in_full(fd, buf.buf, buf.len);
3081 strbuf_release(&buf);
3082 if (written < 0) {
3083 error_errno(_("could not write to '%s'"), git_path_head_file());
3084 rollback_lock_file(&head_lock);
3085 return -1;
3087 if (commit_lock_file(&head_lock) < 0)
3088 return error(_("failed to finalize '%s'"), git_path_head_file());
3089 return 0;
3092 static int rollback_is_safe(void)
3094 struct strbuf sb = STRBUF_INIT;
3095 struct object_id expected_head, actual_head;
3097 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3098 strbuf_trim(&sb);
3099 if (get_oid_hex(sb.buf, &expected_head)) {
3100 strbuf_release(&sb);
3101 die(_("could not parse %s"), git_path_abort_safety_file());
3103 strbuf_release(&sb);
3105 else if (errno == ENOENT)
3106 oidclr(&expected_head);
3107 else
3108 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3110 if (get_oid("HEAD", &actual_head))
3111 oidclr(&actual_head);
3113 return oideq(&actual_head, &expected_head);
3116 static int reset_merge(const struct object_id *oid)
3118 int ret;
3119 struct strvec argv = STRVEC_INIT;
3121 strvec_pushl(&argv, "reset", "--merge", NULL);
3123 if (!is_null_oid(oid))
3124 strvec_push(&argv, oid_to_hex(oid));
3126 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3127 strvec_clear(&argv);
3129 return ret;
3132 static int rollback_single_pick(struct repository *r)
3134 struct object_id head_oid;
3136 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3137 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3138 return error(_("no cherry-pick or revert in progress"));
3139 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3140 return error(_("cannot resolve HEAD"));
3141 if (is_null_oid(&head_oid))
3142 return error(_("cannot abort from a branch yet to be born"));
3143 return reset_merge(&head_oid);
3146 static int skip_single_pick(void)
3148 struct object_id head;
3150 if (read_ref_full("HEAD", 0, &head, NULL))
3151 return error(_("cannot resolve HEAD"));
3152 return reset_merge(&head);
3155 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3157 FILE *f;
3158 struct object_id oid;
3159 struct strbuf buf = STRBUF_INIT;
3160 const char *p;
3162 f = fopen(git_path_head_file(), "r");
3163 if (!f && errno == ENOENT) {
3165 * There is no multiple-cherry-pick in progress.
3166 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3167 * a single-cherry-pick in progress, abort that.
3169 return rollback_single_pick(r);
3171 if (!f)
3172 return error_errno(_("cannot open '%s'"), git_path_head_file());
3173 if (strbuf_getline_lf(&buf, f)) {
3174 error(_("cannot read '%s': %s"), git_path_head_file(),
3175 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3176 fclose(f);
3177 goto fail;
3179 fclose(f);
3180 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3181 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3182 git_path_head_file());
3183 goto fail;
3185 if (is_null_oid(&oid)) {
3186 error(_("cannot abort from a branch yet to be born"));
3187 goto fail;
3190 if (!rollback_is_safe()) {
3191 /* Do not error, just do not rollback */
3192 warning(_("You seem to have moved HEAD. "
3193 "Not rewinding, check your HEAD!"));
3194 } else
3195 if (reset_merge(&oid))
3196 goto fail;
3197 strbuf_release(&buf);
3198 return sequencer_remove_state(opts);
3199 fail:
3200 strbuf_release(&buf);
3201 return -1;
3204 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3206 enum replay_action action = -1;
3207 sequencer_get_last_command(r, &action);
3210 * Check whether the subcommand requested to skip the commit is actually
3211 * in progress and that it's safe to skip the commit.
3213 * opts->action tells us which subcommand requested to skip the commit.
3214 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3215 * action is in progress and we can skip the commit.
3217 * Otherwise we check that the last instruction was related to the
3218 * particular subcommand we're trying to execute and barf if that's not
3219 * the case.
3221 * Finally we check that the rollback is "safe", i.e., has the HEAD
3222 * moved? In this case, it doesn't make sense to "reset the merge" and
3223 * "skip the commit" as the user already handled this by committing. But
3224 * we'd not want to barf here, instead give advice on how to proceed. We
3225 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3226 * it gets removed when the user commits, so if it still exists we're
3227 * sure the user can't have committed before.
3229 switch (opts->action) {
3230 case REPLAY_REVERT:
3231 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3232 if (action != REPLAY_REVERT)
3233 return error(_("no revert in progress"));
3234 if (!rollback_is_safe())
3235 goto give_advice;
3237 break;
3238 case REPLAY_PICK:
3239 if (!refs_ref_exists(get_main_ref_store(r),
3240 "CHERRY_PICK_HEAD")) {
3241 if (action != REPLAY_PICK)
3242 return error(_("no cherry-pick in progress"));
3243 if (!rollback_is_safe())
3244 goto give_advice;
3246 break;
3247 default:
3248 BUG("unexpected action in sequencer_skip");
3251 if (skip_single_pick())
3252 return error(_("failed to skip the commit"));
3253 if (!is_directory(git_path_seq_dir()))
3254 return 0;
3256 return sequencer_continue(r, opts);
3258 give_advice:
3259 error(_("there is nothing to skip"));
3261 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3262 advise(_("have you committed already?\n"
3263 "try \"git %s --continue\""),
3264 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3266 return -1;
3269 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3271 struct lock_file todo_lock = LOCK_INIT;
3272 const char *todo_path = get_todo_path(opts);
3273 int next = todo_list->current, offset, fd;
3276 * rebase -i writes "git-rebase-todo" without the currently executing
3277 * command, appending it to "done" instead.
3279 if (is_rebase_i(opts))
3280 next++;
3282 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3283 if (fd < 0)
3284 return error_errno(_("could not lock '%s'"), todo_path);
3285 offset = get_item_line_offset(todo_list, next);
3286 if (write_in_full(fd, todo_list->buf.buf + offset,
3287 todo_list->buf.len - offset) < 0)
3288 return error_errno(_("could not write to '%s'"), todo_path);
3289 if (commit_lock_file(&todo_lock) < 0)
3290 return error(_("failed to finalize '%s'"), todo_path);
3292 if (is_rebase_i(opts) && next > 0) {
3293 const char *done = rebase_path_done();
3294 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3295 int ret = 0;
3297 if (fd < 0)
3298 return 0;
3299 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3300 get_item_line_length(todo_list, next - 1))
3301 < 0)
3302 ret = error_errno(_("could not write to '%s'"), done);
3303 if (close(fd) < 0)
3304 ret = error_errno(_("failed to finalize '%s'"), done);
3305 return ret;
3307 return 0;
3310 static int save_opts(struct replay_opts *opts)
3312 const char *opts_file = git_path_opts_file();
3313 int res = 0;
3315 if (opts->no_commit)
3316 res |= git_config_set_in_file_gently(opts_file,
3317 "options.no-commit", "true");
3318 if (opts->edit >= 0)
3319 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3320 opts->edit ? "true" : "false");
3321 if (opts->allow_empty)
3322 res |= git_config_set_in_file_gently(opts_file,
3323 "options.allow-empty", "true");
3324 if (opts->allow_empty_message)
3325 res |= git_config_set_in_file_gently(opts_file,
3326 "options.allow-empty-message", "true");
3327 if (opts->keep_redundant_commits)
3328 res |= git_config_set_in_file_gently(opts_file,
3329 "options.keep-redundant-commits", "true");
3330 if (opts->signoff)
3331 res |= git_config_set_in_file_gently(opts_file,
3332 "options.signoff", "true");
3333 if (opts->record_origin)
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.record-origin", "true");
3336 if (opts->allow_ff)
3337 res |= git_config_set_in_file_gently(opts_file,
3338 "options.allow-ff", "true");
3339 if (opts->mainline) {
3340 struct strbuf buf = STRBUF_INIT;
3341 strbuf_addf(&buf, "%d", opts->mainline);
3342 res |= git_config_set_in_file_gently(opts_file,
3343 "options.mainline", buf.buf);
3344 strbuf_release(&buf);
3346 if (opts->strategy)
3347 res |= git_config_set_in_file_gently(opts_file,
3348 "options.strategy", opts->strategy);
3349 if (opts->gpg_sign)
3350 res |= git_config_set_in_file_gently(opts_file,
3351 "options.gpg-sign", opts->gpg_sign);
3352 if (opts->xopts) {
3353 int i;
3354 for (i = 0; i < opts->xopts_nr; i++)
3355 res |= git_config_set_multivar_in_file_gently(opts_file,
3356 "options.strategy-option",
3357 opts->xopts[i], "^$", 0);
3359 if (opts->allow_rerere_auto)
3360 res |= git_config_set_in_file_gently(opts_file,
3361 "options.allow-rerere-auto",
3362 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3363 "true" : "false");
3365 if (opts->explicit_cleanup)
3366 res |= git_config_set_in_file_gently(opts_file,
3367 "options.default-msg-cleanup",
3368 describe_cleanup_mode(opts->default_msg_cleanup));
3369 return res;
3372 static int make_patch(struct repository *r,
3373 struct commit *commit,
3374 struct replay_opts *opts)
3376 struct strbuf buf = STRBUF_INIT;
3377 struct rev_info log_tree_opt;
3378 const char *subject;
3379 char hex[GIT_MAX_HEXSZ + 1];
3380 int res = 0;
3382 oid_to_hex_r(hex, &commit->object.oid);
3383 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3384 return -1;
3385 res |= write_rebase_head(&commit->object.oid);
3387 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3388 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3389 repo_init_revisions(r, &log_tree_opt, NULL);
3390 log_tree_opt.abbrev = 0;
3391 log_tree_opt.diff = 1;
3392 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3393 log_tree_opt.disable_stdin = 1;
3394 log_tree_opt.no_commit_id = 1;
3395 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3396 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3397 if (!log_tree_opt.diffopt.file)
3398 res |= error_errno(_("could not open '%s'"), buf.buf);
3399 else {
3400 res |= log_tree_commit(&log_tree_opt, commit);
3401 fclose(log_tree_opt.diffopt.file);
3403 strbuf_reset(&buf);
3405 strbuf_addf(&buf, "%s/message", get_dir(opts));
3406 if (!file_exists(buf.buf)) {
3407 const char *encoding = get_commit_output_encoding();
3408 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3409 find_commit_subject(commit_buffer, &subject);
3410 res |= write_message(subject, strlen(subject), buf.buf, 1);
3411 unuse_commit_buffer(commit, commit_buffer);
3413 strbuf_release(&buf);
3415 return res;
3418 static int intend_to_amend(void)
3420 struct object_id head;
3421 char *p;
3423 if (get_oid("HEAD", &head))
3424 return error(_("cannot read HEAD"));
3426 p = oid_to_hex(&head);
3427 return write_message(p, strlen(p), rebase_path_amend(), 1);
3430 static int error_with_patch(struct repository *r,
3431 struct commit *commit,
3432 const char *subject, int subject_len,
3433 struct replay_opts *opts,
3434 int exit_code, int to_amend)
3436 if (commit) {
3437 if (make_patch(r, commit, opts))
3438 return -1;
3439 } else if (copy_file(rebase_path_message(),
3440 git_path_merge_msg(r), 0666))
3441 return error(_("unable to copy '%s' to '%s'"),
3442 git_path_merge_msg(r), rebase_path_message());
3444 if (to_amend) {
3445 if (intend_to_amend())
3446 return -1;
3448 fprintf(stderr,
3449 _("You can amend the commit now, with\n"
3450 "\n"
3451 " git commit --amend %s\n"
3452 "\n"
3453 "Once you are satisfied with your changes, run\n"
3454 "\n"
3455 " git rebase --continue\n"),
3456 gpg_sign_opt_quoted(opts));
3457 } else if (exit_code) {
3458 if (commit)
3459 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3460 short_commit_name(commit), subject_len, subject);
3461 else
3463 * We don't have the hash of the parent so
3464 * just print the line from the todo file.
3466 fprintf_ln(stderr, _("Could not merge %.*s"),
3467 subject_len, subject);
3470 return exit_code;
3473 static int error_failed_squash(struct repository *r,
3474 struct commit *commit,
3475 struct replay_opts *opts,
3476 int subject_len,
3477 const char *subject)
3479 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3480 return error(_("could not copy '%s' to '%s'"),
3481 rebase_path_squash_msg(), rebase_path_message());
3482 unlink(git_path_merge_msg(r));
3483 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3484 return error(_("could not copy '%s' to '%s'"),
3485 rebase_path_message(),
3486 git_path_merge_msg(r));
3487 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3490 static int do_exec(struct repository *r, const char *command_line)
3492 struct strvec child_env = STRVEC_INIT;
3493 const char *child_argv[] = { NULL, NULL };
3494 int dirty, status;
3496 fprintf(stderr, _("Executing: %s\n"), command_line);
3497 child_argv[0] = command_line;
3498 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3499 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3500 absolute_path(get_git_work_tree()));
3501 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3502 child_env.v);
3504 /* force re-reading of the cache */
3505 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3506 return error(_("could not read index"));
3508 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3510 if (status) {
3511 warning(_("execution failed: %s\n%s"
3512 "You can fix the problem, and then run\n"
3513 "\n"
3514 " git rebase --continue\n"
3515 "\n"),
3516 command_line,
3517 dirty ? N_("and made changes to the index and/or the "
3518 "working tree\n") : "");
3519 if (status == 127)
3520 /* command not found */
3521 status = 1;
3522 } else if (dirty) {
3523 warning(_("execution succeeded: %s\nbut "
3524 "left changes to the index and/or the working tree\n"
3525 "Commit or stash your changes, and then run\n"
3526 "\n"
3527 " git rebase --continue\n"
3528 "\n"), command_line);
3529 status = 1;
3532 strvec_clear(&child_env);
3534 return status;
3537 __attribute__((format (printf, 2, 3)))
3538 static int safe_append(const char *filename, const char *fmt, ...)
3540 va_list ap;
3541 struct lock_file lock = LOCK_INIT;
3542 int fd = hold_lock_file_for_update(&lock, filename,
3543 LOCK_REPORT_ON_ERROR);
3544 struct strbuf buf = STRBUF_INIT;
3546 if (fd < 0)
3547 return -1;
3549 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3550 error_errno(_("could not read '%s'"), filename);
3551 rollback_lock_file(&lock);
3552 return -1;
3554 strbuf_complete(&buf, '\n');
3555 va_start(ap, fmt);
3556 strbuf_vaddf(&buf, fmt, ap);
3557 va_end(ap);
3559 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3560 error_errno(_("could not write to '%s'"), filename);
3561 strbuf_release(&buf);
3562 rollback_lock_file(&lock);
3563 return -1;
3565 if (commit_lock_file(&lock) < 0) {
3566 strbuf_release(&buf);
3567 rollback_lock_file(&lock);
3568 return error(_("failed to finalize '%s'"), filename);
3571 strbuf_release(&buf);
3572 return 0;
3575 static int do_label(struct repository *r, const char *name, int len)
3577 struct ref_store *refs = get_main_ref_store(r);
3578 struct ref_transaction *transaction;
3579 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3580 struct strbuf msg = STRBUF_INIT;
3581 int ret = 0;
3582 struct object_id head_oid;
3584 if (len == 1 && *name == '#')
3585 return error(_("illegal label name: '%.*s'"), len, name);
3587 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3588 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3590 transaction = ref_store_transaction_begin(refs, &err);
3591 if (!transaction) {
3592 error("%s", err.buf);
3593 ret = -1;
3594 } else if (get_oid("HEAD", &head_oid)) {
3595 error(_("could not read HEAD"));
3596 ret = -1;
3597 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3598 NULL, 0, msg.buf, &err) < 0 ||
3599 ref_transaction_commit(transaction, &err)) {
3600 error("%s", err.buf);
3601 ret = -1;
3603 ref_transaction_free(transaction);
3604 strbuf_release(&err);
3605 strbuf_release(&msg);
3607 if (!ret)
3608 ret = safe_append(rebase_path_refs_to_delete(),
3609 "%s\n", ref_name.buf);
3610 strbuf_release(&ref_name);
3612 return ret;
3615 __attribute__((format (printf, 3, 4)))
3616 static const char *reflog_message(struct replay_opts *opts,
3617 const char *sub_action, const char *fmt, ...)
3619 va_list ap;
3620 static struct strbuf buf = STRBUF_INIT;
3621 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3623 va_start(ap, fmt);
3624 strbuf_reset(&buf);
3625 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3626 if (sub_action)
3627 strbuf_addf(&buf, " (%s)", sub_action);
3628 if (fmt) {
3629 strbuf_addstr(&buf, ": ");
3630 strbuf_vaddf(&buf, fmt, ap);
3632 va_end(ap);
3634 return buf.buf;
3637 static int do_reset(struct repository *r,
3638 const char *name, int len,
3639 struct replay_opts *opts)
3641 struct strbuf ref_name = STRBUF_INIT;
3642 struct object_id oid;
3643 struct lock_file lock = LOCK_INIT;
3644 struct tree_desc desc;
3645 struct tree *tree;
3646 struct unpack_trees_options unpack_tree_opts;
3647 int ret = 0;
3649 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3650 return -1;
3652 if (len == 10 && !strncmp("[new root]", name, len)) {
3653 if (!opts->have_squash_onto) {
3654 const char *hex;
3655 if (commit_tree("", 0, the_hash_algo->empty_tree,
3656 NULL, &opts->squash_onto,
3657 NULL, NULL))
3658 return error(_("writing fake root commit"));
3659 opts->have_squash_onto = 1;
3660 hex = oid_to_hex(&opts->squash_onto);
3661 if (write_message(hex, strlen(hex),
3662 rebase_path_squash_onto(), 0))
3663 return error(_("writing squash-onto"));
3665 oidcpy(&oid, &opts->squash_onto);
3666 } else {
3667 int i;
3669 /* Determine the length of the label */
3670 for (i = 0; i < len; i++)
3671 if (isspace(name[i]))
3672 break;
3673 len = i;
3675 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3676 if (get_oid(ref_name.buf, &oid) &&
3677 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3678 error(_("could not read '%s'"), ref_name.buf);
3679 rollback_lock_file(&lock);
3680 strbuf_release(&ref_name);
3681 return -1;
3685 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3686 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3687 unpack_tree_opts.head_idx = 1;
3688 unpack_tree_opts.src_index = r->index;
3689 unpack_tree_opts.dst_index = r->index;
3690 unpack_tree_opts.fn = oneway_merge;
3691 unpack_tree_opts.merge = 1;
3692 unpack_tree_opts.update = 1;
3693 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3695 if (repo_read_index_unmerged(r)) {
3696 rollback_lock_file(&lock);
3697 strbuf_release(&ref_name);
3698 return error_resolve_conflict(_(action_name(opts)));
3701 if (!fill_tree_descriptor(r, &desc, &oid)) {
3702 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3703 rollback_lock_file(&lock);
3704 free((void *)desc.buffer);
3705 strbuf_release(&ref_name);
3706 return -1;
3709 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3710 rollback_lock_file(&lock);
3711 free((void *)desc.buffer);
3712 strbuf_release(&ref_name);
3713 return -1;
3716 tree = parse_tree_indirect(&oid);
3717 prime_cache_tree(r, r->index, tree);
3719 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3720 ret = error(_("could not write index"));
3721 free((void *)desc.buffer);
3723 if (!ret)
3724 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3725 len, name), "HEAD", &oid,
3726 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3728 strbuf_release(&ref_name);
3729 return ret;
3732 static struct commit *lookup_label(const char *label, int len,
3733 struct strbuf *buf)
3735 struct commit *commit;
3737 strbuf_reset(buf);
3738 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3739 commit = lookup_commit_reference_by_name(buf->buf);
3740 if (!commit) {
3741 /* fall back to non-rewritten ref or commit */
3742 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3743 commit = lookup_commit_reference_by_name(buf->buf);
3746 if (!commit)
3747 error(_("could not resolve '%s'"), buf->buf);
3749 return commit;
3752 static int do_merge(struct repository *r,
3753 struct commit *commit,
3754 const char *arg, int arg_len,
3755 int flags, int *check_todo, struct replay_opts *opts)
3757 int run_commit_flags = 0;
3758 struct strbuf ref_name = STRBUF_INIT;
3759 struct commit *head_commit, *merge_commit, *i;
3760 struct commit_list *bases, *j, *reversed = NULL;
3761 struct commit_list *to_merge = NULL, **tail = &to_merge;
3762 const char *strategy = !opts->xopts_nr &&
3763 (!opts->strategy ||
3764 !strcmp(opts->strategy, "recursive") ||
3765 !strcmp(opts->strategy, "ort")) ?
3766 NULL : opts->strategy;
3767 struct merge_options o;
3768 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3769 static struct lock_file lock;
3770 const char *p;
3772 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3773 ret = -1;
3774 goto leave_merge;
3777 head_commit = lookup_commit_reference_by_name("HEAD");
3778 if (!head_commit) {
3779 ret = error(_("cannot merge without a current revision"));
3780 goto leave_merge;
3784 * For octopus merges, the arg starts with the list of revisions to be
3785 * merged. The list is optionally followed by '#' and the oneline.
3787 merge_arg_len = oneline_offset = arg_len;
3788 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3789 if (!*p)
3790 break;
3791 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3792 p += 1 + strspn(p + 1, " \t\n");
3793 oneline_offset = p - arg;
3794 break;
3796 k = strcspn(p, " \t\n");
3797 if (!k)
3798 continue;
3799 merge_commit = lookup_label(p, k, &ref_name);
3800 if (!merge_commit) {
3801 ret = error(_("unable to parse '%.*s'"), k, p);
3802 goto leave_merge;
3804 tail = &commit_list_insert(merge_commit, tail)->next;
3805 p += k;
3806 merge_arg_len = p - arg;
3809 if (!to_merge) {
3810 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3811 goto leave_merge;
3814 if (opts->have_squash_onto &&
3815 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3817 * When the user tells us to "merge" something into a
3818 * "[new root]", let's simply fast-forward to the merge head.
3820 rollback_lock_file(&lock);
3821 if (to_merge->next)
3822 ret = error(_("octopus merge cannot be executed on "
3823 "top of a [new root]"));
3824 else
3825 ret = fast_forward_to(r, &to_merge->item->object.oid,
3826 &head_commit->object.oid, 0,
3827 opts);
3828 goto leave_merge;
3832 * If HEAD is not identical to the first parent of the original merge
3833 * commit, we cannot fast-forward.
3835 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3836 oideq(&commit->parents->item->object.oid,
3837 &head_commit->object.oid);
3840 * If any merge head is different from the original one, we cannot
3841 * fast-forward.
3843 if (can_fast_forward) {
3844 struct commit_list *p = commit->parents->next;
3846 for (j = to_merge; j && p; j = j->next, p = p->next)
3847 if (!oideq(&j->item->object.oid,
3848 &p->item->object.oid)) {
3849 can_fast_forward = 0;
3850 break;
3853 * If the number of merge heads differs from the original merge
3854 * commit, we cannot fast-forward.
3856 if (j || p)
3857 can_fast_forward = 0;
3860 if (can_fast_forward) {
3861 rollback_lock_file(&lock);
3862 ret = fast_forward_to(r, &commit->object.oid,
3863 &head_commit->object.oid, 0, opts);
3864 if (flags & TODO_EDIT_MERGE_MSG)
3865 goto fast_forward_edit;
3867 goto leave_merge;
3870 if (commit) {
3871 const char *encoding = get_commit_output_encoding();
3872 const char *message = logmsg_reencode(commit, NULL, encoding);
3873 const char *body;
3874 int len;
3876 if (!message) {
3877 ret = error(_("could not get commit message of '%s'"),
3878 oid_to_hex(&commit->object.oid));
3879 goto leave_merge;
3881 write_author_script(message);
3882 find_commit_subject(message, &body);
3883 len = strlen(body);
3884 ret = write_message(body, len, git_path_merge_msg(r), 0);
3885 unuse_commit_buffer(commit, message);
3886 if (ret) {
3887 error_errno(_("could not write '%s'"),
3888 git_path_merge_msg(r));
3889 goto leave_merge;
3891 } else {
3892 struct strbuf buf = STRBUF_INIT;
3893 int len;
3895 strbuf_addf(&buf, "author %s", git_author_info(0));
3896 write_author_script(buf.buf);
3897 strbuf_reset(&buf);
3899 if (oneline_offset < arg_len) {
3900 p = arg + oneline_offset;
3901 len = arg_len - oneline_offset;
3902 } else {
3903 strbuf_addf(&buf, "Merge %s '%.*s'",
3904 to_merge->next ? "branches" : "branch",
3905 merge_arg_len, arg);
3906 p = buf.buf;
3907 len = buf.len;
3910 ret = write_message(p, len, git_path_merge_msg(r), 0);
3911 strbuf_release(&buf);
3912 if (ret) {
3913 error_errno(_("could not write '%s'"),
3914 git_path_merge_msg(r));
3915 goto leave_merge;
3919 if (strategy || to_merge->next) {
3920 /* Octopus merge */
3921 struct child_process cmd = CHILD_PROCESS_INIT;
3923 if (read_env_script(&cmd.env_array)) {
3924 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3926 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3927 goto leave_merge;
3930 if (opts->committer_date_is_author_date)
3931 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3932 opts->ignore_date ?
3933 "" :
3934 author_date_from_env_array(&cmd.env_array));
3935 if (opts->ignore_date)
3936 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3938 cmd.git_cmd = 1;
3939 strvec_push(&cmd.args, "merge");
3940 strvec_push(&cmd.args, "-s");
3941 if (!strategy)
3942 strvec_push(&cmd.args, "octopus");
3943 else {
3944 strvec_push(&cmd.args, strategy);
3945 for (k = 0; k < opts->xopts_nr; k++)
3946 strvec_pushf(&cmd.args,
3947 "-X%s", opts->xopts[k]);
3949 if (!(flags & TODO_EDIT_MERGE_MSG))
3950 strvec_push(&cmd.args, "--no-edit");
3951 else
3952 strvec_push(&cmd.args, "--edit");
3953 strvec_push(&cmd.args, "--no-ff");
3954 strvec_push(&cmd.args, "--no-log");
3955 strvec_push(&cmd.args, "--no-stat");
3956 strvec_push(&cmd.args, "-F");
3957 strvec_push(&cmd.args, git_path_merge_msg(r));
3958 if (opts->gpg_sign)
3959 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3960 else
3961 strvec_push(&cmd.args, "--no-gpg-sign");
3963 /* Add the tips to be merged */
3964 for (j = to_merge; j; j = j->next)
3965 strvec_push(&cmd.args,
3966 oid_to_hex(&j->item->object.oid));
3968 strbuf_release(&ref_name);
3969 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3970 NULL, 0);
3971 rollback_lock_file(&lock);
3973 ret = run_command(&cmd);
3975 /* force re-reading of the cache */
3976 if (!ret && (discard_index(r->index) < 0 ||
3977 repo_read_index(r) < 0))
3978 ret = error(_("could not read index"));
3979 goto leave_merge;
3982 merge_commit = to_merge->item;
3983 bases = get_merge_bases(head_commit, merge_commit);
3984 if (bases && oideq(&merge_commit->object.oid,
3985 &bases->item->object.oid)) {
3986 ret = 0;
3987 /* skip merging an ancestor of HEAD */
3988 goto leave_merge;
3991 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3992 git_path_merge_head(r), 0);
3993 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3995 for (j = bases; j; j = j->next)
3996 commit_list_insert(j->item, &reversed);
3997 free_commit_list(bases);
3999 repo_read_index(r);
4000 init_merge_options(&o, r);
4001 o.branch1 = "HEAD";
4002 o.branch2 = ref_name.buf;
4003 o.buffer_output = 2;
4005 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4007 * TODO: Should use merge_incore_recursive() and
4008 * merge_switch_to_result(), skipping the call to
4009 * merge_switch_to_result() when we don't actually need to
4010 * update the index and working copy immediately.
4012 ret = merge_ort_recursive(&o,
4013 head_commit, merge_commit, reversed,
4014 &i);
4015 } else {
4016 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4017 &i);
4019 if (ret <= 0)
4020 fputs(o.obuf.buf, stdout);
4021 strbuf_release(&o.obuf);
4022 if (ret < 0) {
4023 error(_("could not even attempt to merge '%.*s'"),
4024 merge_arg_len, arg);
4025 goto leave_merge;
4028 * The return value of merge_recursive() is 1 on clean, and 0 on
4029 * unclean merge.
4031 * Let's reverse that, so that do_merge() returns 0 upon success and
4032 * 1 upon failed merge (keeping the return value -1 for the cases where
4033 * we will want to reschedule the `merge` command).
4035 ret = !ret;
4037 if (r->index->cache_changed &&
4038 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4039 ret = error(_("merge: Unable to write new index file"));
4040 goto leave_merge;
4043 rollback_lock_file(&lock);
4044 if (ret)
4045 repo_rerere(r, opts->allow_rerere_auto);
4046 else
4048 * In case of problems, we now want to return a positive
4049 * value (a negative one would indicate that the `merge`
4050 * command needs to be rescheduled).
4052 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4053 run_commit_flags);
4055 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4056 fast_forward_edit:
4057 *check_todo = 1;
4058 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4059 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4063 leave_merge:
4064 strbuf_release(&ref_name);
4065 rollback_lock_file(&lock);
4066 free_commit_list(to_merge);
4067 return ret;
4070 static int is_final_fixup(struct todo_list *todo_list)
4072 int i = todo_list->current;
4074 if (!is_fixup(todo_list->items[i].command))
4075 return 0;
4077 while (++i < todo_list->nr)
4078 if (is_fixup(todo_list->items[i].command))
4079 return 0;
4080 else if (!is_noop(todo_list->items[i].command))
4081 break;
4082 return 1;
4085 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4087 int i;
4089 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4090 if (!is_noop(todo_list->items[i].command))
4091 return todo_list->items[i].command;
4093 return -1;
4096 void create_autostash(struct repository *r, const char *path,
4097 const char *default_reflog_action)
4099 struct strbuf buf = STRBUF_INIT;
4100 struct lock_file lock_file = LOCK_INIT;
4101 int fd;
4103 fd = repo_hold_locked_index(r, &lock_file, 0);
4104 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4105 if (0 <= fd)
4106 repo_update_index_if_able(r, &lock_file);
4107 rollback_lock_file(&lock_file);
4109 if (has_unstaged_changes(r, 1) ||
4110 has_uncommitted_changes(r, 1)) {
4111 struct child_process stash = CHILD_PROCESS_INIT;
4112 struct object_id oid;
4114 strvec_pushl(&stash.args,
4115 "stash", "create", "autostash", NULL);
4116 stash.git_cmd = 1;
4117 stash.no_stdin = 1;
4118 strbuf_reset(&buf);
4119 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4120 die(_("Cannot autostash"));
4121 strbuf_trim_trailing_newline(&buf);
4122 if (get_oid(buf.buf, &oid))
4123 die(_("Unexpected stash response: '%s'"),
4124 buf.buf);
4125 strbuf_reset(&buf);
4126 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4128 if (safe_create_leading_directories_const(path))
4129 die(_("Could not create directory for '%s'"),
4130 path);
4131 write_file(path, "%s", oid_to_hex(&oid));
4132 printf(_("Created autostash: %s\n"), buf.buf);
4133 if (reset_head(r, NULL, "reset --hard",
4134 NULL, RESET_HEAD_HARD, NULL, NULL,
4135 default_reflog_action) < 0)
4136 die(_("could not reset --hard"));
4138 if (discard_index(r->index) < 0 ||
4139 repo_read_index(r) < 0)
4140 die(_("could not read index"));
4142 strbuf_release(&buf);
4145 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4147 struct child_process child = CHILD_PROCESS_INIT;
4148 int ret = 0;
4150 if (attempt_apply) {
4151 child.git_cmd = 1;
4152 child.no_stdout = 1;
4153 child.no_stderr = 1;
4154 strvec_push(&child.args, "stash");
4155 strvec_push(&child.args, "apply");
4156 strvec_push(&child.args, stash_oid);
4157 ret = run_command(&child);
4160 if (attempt_apply && !ret)
4161 fprintf(stderr, _("Applied autostash.\n"));
4162 else {
4163 struct child_process store = CHILD_PROCESS_INIT;
4165 store.git_cmd = 1;
4166 strvec_push(&store.args, "stash");
4167 strvec_push(&store.args, "store");
4168 strvec_push(&store.args, "-m");
4169 strvec_push(&store.args, "autostash");
4170 strvec_push(&store.args, "-q");
4171 strvec_push(&store.args, stash_oid);
4172 if (run_command(&store))
4173 ret = error(_("cannot store %s"), stash_oid);
4174 else
4175 fprintf(stderr,
4176 _("%s\n"
4177 "Your changes are safe in the stash.\n"
4178 "You can run \"git stash pop\" or"
4179 " \"git stash drop\" at any time.\n"),
4180 attempt_apply ?
4181 _("Applying autostash resulted in conflicts.") :
4182 _("Autostash exists; creating a new stash entry."));
4185 return ret;
4188 static int apply_save_autostash(const char *path, int attempt_apply)
4190 struct strbuf stash_oid = STRBUF_INIT;
4191 int ret = 0;
4193 if (!read_oneliner(&stash_oid, path,
4194 READ_ONELINER_SKIP_IF_EMPTY)) {
4195 strbuf_release(&stash_oid);
4196 return 0;
4198 strbuf_trim(&stash_oid);
4200 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4202 unlink(path);
4203 strbuf_release(&stash_oid);
4204 return ret;
4207 int save_autostash(const char *path)
4209 return apply_save_autostash(path, 0);
4212 int apply_autostash(const char *path)
4214 return apply_save_autostash(path, 1);
4217 int apply_autostash_oid(const char *stash_oid)
4219 return apply_save_autostash_oid(stash_oid, 1);
4222 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4223 const char *commit, const char *action)
4225 struct child_process cmd = CHILD_PROCESS_INIT;
4226 int ret;
4228 cmd.git_cmd = 1;
4230 strvec_push(&cmd.args, "checkout");
4231 strvec_push(&cmd.args, commit);
4232 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4234 if (opts->verbose)
4235 ret = run_command(&cmd);
4236 else
4237 ret = run_command_silent_on_success(&cmd);
4239 if (!ret)
4240 discard_index(r->index);
4242 return ret;
4245 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4246 const char *onto_name, const struct object_id *onto,
4247 const struct object_id *orig_head)
4249 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4251 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4252 apply_autostash(rebase_path_autostash());
4253 sequencer_remove_state(opts);
4254 return error(_("could not detach HEAD"));
4257 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4260 static int stopped_at_head(struct repository *r)
4262 struct object_id head;
4263 struct commit *commit;
4264 struct commit_message message;
4266 if (get_oid("HEAD", &head) ||
4267 !(commit = lookup_commit(r, &head)) ||
4268 parse_commit(commit) || get_message(commit, &message))
4269 fprintf(stderr, _("Stopped at HEAD\n"));
4270 else {
4271 fprintf(stderr, _("Stopped at %s\n"), message.label);
4272 free_message(commit, &message);
4274 return 0;
4278 static const char rescheduled_advice[] =
4279 N_("Could not execute the todo command\n"
4280 "\n"
4281 " %.*s"
4282 "\n"
4283 "It has been rescheduled; To edit the command before continuing, please\n"
4284 "edit the todo list first:\n"
4285 "\n"
4286 " git rebase --edit-todo\n"
4287 " git rebase --continue\n");
4289 static int pick_commits(struct repository *r,
4290 struct todo_list *todo_list,
4291 struct replay_opts *opts)
4293 int res = 0, reschedule = 0;
4294 char *prev_reflog_action;
4296 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4297 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4298 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4299 if (opts->allow_ff)
4300 assert(!(opts->signoff || opts->no_commit ||
4301 opts->record_origin || should_edit(opts) ||
4302 opts->committer_date_is_author_date ||
4303 opts->ignore_date));
4304 if (read_and_refresh_cache(r, opts))
4305 return -1;
4307 while (todo_list->current < todo_list->nr) {
4308 struct todo_item *item = todo_list->items + todo_list->current;
4309 const char *arg = todo_item_get_arg(todo_list, item);
4310 int check_todo = 0;
4312 if (save_todo(todo_list, opts))
4313 return -1;
4314 if (is_rebase_i(opts)) {
4315 if (item->command != TODO_COMMENT) {
4316 FILE *f = fopen(rebase_path_msgnum(), "w");
4318 todo_list->done_nr++;
4320 if (f) {
4321 fprintf(f, "%d\n", todo_list->done_nr);
4322 fclose(f);
4324 if (!opts->quiet)
4325 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4326 todo_list->done_nr,
4327 todo_list->total_nr,
4328 opts->verbose ? "\n" : "\r");
4330 unlink(rebase_path_message());
4331 unlink(rebase_path_author_script());
4332 unlink(rebase_path_stopped_sha());
4333 unlink(rebase_path_amend());
4334 unlink(git_path_merge_head(r));
4335 unlink(git_path_auto_merge(r));
4336 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4338 if (item->command == TODO_BREAK) {
4339 if (!opts->verbose)
4340 term_clear_line();
4341 return stopped_at_head(r);
4344 if (item->command <= TODO_SQUASH) {
4345 if (is_rebase_i(opts))
4346 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4347 command_to_string(item->command), NULL),
4349 res = do_pick_commit(r, item, opts,
4350 is_final_fixup(todo_list),
4351 &check_todo);
4352 if (is_rebase_i(opts))
4353 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4354 if (is_rebase_i(opts) && res < 0) {
4355 /* Reschedule */
4356 advise(_(rescheduled_advice),
4357 get_item_line_length(todo_list,
4358 todo_list->current),
4359 get_item_line(todo_list,
4360 todo_list->current));
4361 todo_list->current--;
4362 if (save_todo(todo_list, opts))
4363 return -1;
4365 if (item->command == TODO_EDIT) {
4366 struct commit *commit = item->commit;
4367 if (!res) {
4368 if (!opts->verbose)
4369 term_clear_line();
4370 fprintf(stderr,
4371 _("Stopped at %s... %.*s\n"),
4372 short_commit_name(commit),
4373 item->arg_len, arg);
4375 return error_with_patch(r, commit,
4376 arg, item->arg_len, opts, res, !res);
4378 if (is_rebase_i(opts) && !res)
4379 record_in_rewritten(&item->commit->object.oid,
4380 peek_command(todo_list, 1));
4381 if (res && is_fixup(item->command)) {
4382 if (res == 1)
4383 intend_to_amend();
4384 return error_failed_squash(r, item->commit, opts,
4385 item->arg_len, arg);
4386 } else if (res && is_rebase_i(opts) && item->commit) {
4387 int to_amend = 0;
4388 struct object_id oid;
4391 * If we are rewording and have either
4392 * fast-forwarded already, or are about to
4393 * create a new root commit, we want to amend,
4394 * otherwise we do not.
4396 if (item->command == TODO_REWORD &&
4397 !get_oid("HEAD", &oid) &&
4398 (oideq(&item->commit->object.oid, &oid) ||
4399 (opts->have_squash_onto &&
4400 oideq(&opts->squash_onto, &oid))))
4401 to_amend = 1;
4403 return res | error_with_patch(r, item->commit,
4404 arg, item->arg_len, opts,
4405 res, to_amend);
4407 } else if (item->command == TODO_EXEC) {
4408 char *end_of_arg = (char *)(arg + item->arg_len);
4409 int saved = *end_of_arg;
4411 if (!opts->verbose)
4412 term_clear_line();
4413 *end_of_arg = '\0';
4414 res = do_exec(r, arg);
4415 *end_of_arg = saved;
4417 if (res) {
4418 if (opts->reschedule_failed_exec)
4419 reschedule = 1;
4421 check_todo = 1;
4422 } else if (item->command == TODO_LABEL) {
4423 if ((res = do_label(r, arg, item->arg_len)))
4424 reschedule = 1;
4425 } else if (item->command == TODO_RESET) {
4426 if ((res = do_reset(r, arg, item->arg_len, opts)))
4427 reschedule = 1;
4428 } else if (item->command == TODO_MERGE) {
4429 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4430 item->flags, &check_todo, opts)) < 0)
4431 reschedule = 1;
4432 else if (item->commit)
4433 record_in_rewritten(&item->commit->object.oid,
4434 peek_command(todo_list, 1));
4435 if (res > 0)
4436 /* failed with merge conflicts */
4437 return error_with_patch(r, item->commit,
4438 arg, item->arg_len,
4439 opts, res, 0);
4440 } else if (!is_noop(item->command))
4441 return error(_("unknown command %d"), item->command);
4443 if (reschedule) {
4444 advise(_(rescheduled_advice),
4445 get_item_line_length(todo_list,
4446 todo_list->current),
4447 get_item_line(todo_list, todo_list->current));
4448 todo_list->current--;
4449 if (save_todo(todo_list, opts))
4450 return -1;
4451 if (item->commit)
4452 return error_with_patch(r,
4453 item->commit,
4454 arg, item->arg_len,
4455 opts, res, 0);
4456 } else if (is_rebase_i(opts) && check_todo && !res) {
4457 struct stat st;
4459 if (stat(get_todo_path(opts), &st)) {
4460 res = error_errno(_("could not stat '%s'"),
4461 get_todo_path(opts));
4462 } else if (match_stat_data(&todo_list->stat, &st)) {
4463 /* Reread the todo file if it has changed. */
4464 todo_list_release(todo_list);
4465 if (read_populate_todo(r, todo_list, opts))
4466 res = -1; /* message was printed */
4467 /* `current` will be incremented below */
4468 todo_list->current = -1;
4472 todo_list->current++;
4473 if (res)
4474 return res;
4477 if (is_rebase_i(opts)) {
4478 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4479 struct stat st;
4481 /* Stopped in the middle, as planned? */
4482 if (todo_list->current < todo_list->nr)
4483 return 0;
4485 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4486 starts_with(head_ref.buf, "refs/")) {
4487 const char *msg;
4488 struct object_id head, orig;
4489 int res;
4491 if (get_oid("HEAD", &head)) {
4492 res = error(_("cannot read HEAD"));
4493 cleanup_head_ref:
4494 strbuf_release(&head_ref);
4495 strbuf_release(&buf);
4496 return res;
4498 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4499 get_oid_hex(buf.buf, &orig)) {
4500 res = error(_("could not read orig-head"));
4501 goto cleanup_head_ref;
4503 strbuf_reset(&buf);
4504 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4505 res = error(_("could not read 'onto'"));
4506 goto cleanup_head_ref;
4508 msg = reflog_message(opts, "finish", "%s onto %s",
4509 head_ref.buf, buf.buf);
4510 if (update_ref(msg, head_ref.buf, &head, &orig,
4511 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4512 res = error(_("could not update %s"),
4513 head_ref.buf);
4514 goto cleanup_head_ref;
4516 msg = reflog_message(opts, "finish", "returning to %s",
4517 head_ref.buf);
4518 if (create_symref("HEAD", head_ref.buf, msg)) {
4519 res = error(_("could not update HEAD to %s"),
4520 head_ref.buf);
4521 goto cleanup_head_ref;
4523 strbuf_reset(&buf);
4526 if (opts->verbose) {
4527 struct rev_info log_tree_opt;
4528 struct object_id orig, head;
4530 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4531 repo_init_revisions(r, &log_tree_opt, NULL);
4532 log_tree_opt.diff = 1;
4533 log_tree_opt.diffopt.output_format =
4534 DIFF_FORMAT_DIFFSTAT;
4535 log_tree_opt.disable_stdin = 1;
4537 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4538 !get_oid(buf.buf, &orig) &&
4539 !get_oid("HEAD", &head)) {
4540 diff_tree_oid(&orig, &head, "",
4541 &log_tree_opt.diffopt);
4542 log_tree_diff_flush(&log_tree_opt);
4545 flush_rewritten_pending();
4546 if (!stat(rebase_path_rewritten_list(), &st) &&
4547 st.st_size > 0) {
4548 struct child_process child = CHILD_PROCESS_INIT;
4549 const char *post_rewrite_hook =
4550 find_hook("post-rewrite");
4552 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4553 child.git_cmd = 1;
4554 strvec_push(&child.args, "notes");
4555 strvec_push(&child.args, "copy");
4556 strvec_push(&child.args, "--for-rewrite=rebase");
4557 /* we don't care if this copying failed */
4558 run_command(&child);
4560 if (post_rewrite_hook) {
4561 struct child_process hook = CHILD_PROCESS_INIT;
4563 hook.in = open(rebase_path_rewritten_list(),
4564 O_RDONLY);
4565 hook.stdout_to_stderr = 1;
4566 hook.trace2_hook_name = "post-rewrite";
4567 strvec_push(&hook.args, post_rewrite_hook);
4568 strvec_push(&hook.args, "rebase");
4569 /* we don't care if this hook failed */
4570 run_command(&hook);
4573 apply_autostash(rebase_path_autostash());
4575 if (!opts->quiet) {
4576 if (!opts->verbose)
4577 term_clear_line();
4578 fprintf(stderr,
4579 _("Successfully rebased and updated %s.\n"),
4580 head_ref.buf);
4583 strbuf_release(&buf);
4584 strbuf_release(&head_ref);
4588 * Sequence of picks finished successfully; cleanup by
4589 * removing the .git/sequencer directory
4591 return sequencer_remove_state(opts);
4594 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4596 struct strvec argv = STRVEC_INIT;
4597 int ret;
4599 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4600 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4601 return error(_("no cherry-pick or revert in progress"));
4603 strvec_push(&argv, "commit");
4606 * continue_single_pick() handles the case of recovering from a
4607 * conflict. should_edit() doesn't handle that case; for a conflict,
4608 * we want to edit if the user asked for it, or if they didn't specify
4609 * and stdin is a tty.
4611 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4613 * Include --cleanup=strip as well because we don't want the
4614 * "# Conflicts:" messages.
4616 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4618 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4619 strvec_clear(&argv);
4620 return ret;
4623 static int commit_staged_changes(struct repository *r,
4624 struct replay_opts *opts,
4625 struct todo_list *todo_list)
4627 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4628 unsigned int final_fixup = 0, is_clean;
4630 if (has_unstaged_changes(r, 1))
4631 return error(_("cannot rebase: You have unstaged changes."));
4633 is_clean = !has_uncommitted_changes(r, 0);
4635 if (file_exists(rebase_path_amend())) {
4636 struct strbuf rev = STRBUF_INIT;
4637 struct object_id head, to_amend;
4639 if (get_oid("HEAD", &head))
4640 return error(_("cannot amend non-existing commit"));
4641 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4642 return error(_("invalid file: '%s'"), rebase_path_amend());
4643 if (get_oid_hex(rev.buf, &to_amend))
4644 return error(_("invalid contents: '%s'"),
4645 rebase_path_amend());
4646 if (!is_clean && !oideq(&head, &to_amend))
4647 return error(_("\nYou have uncommitted changes in your "
4648 "working tree. Please, commit them\n"
4649 "first and then run 'git rebase "
4650 "--continue' again."));
4652 * When skipping a failed fixup/squash, we need to edit the
4653 * commit message, the current fixup list and count, and if it
4654 * was the last fixup/squash in the chain, we need to clean up
4655 * the commit message and if there was a squash, let the user
4656 * edit it.
4658 if (!is_clean || !opts->current_fixup_count)
4659 ; /* this is not the final fixup */
4660 else if (!oideq(&head, &to_amend) ||
4661 !file_exists(rebase_path_stopped_sha())) {
4662 /* was a final fixup or squash done manually? */
4663 if (!is_fixup(peek_command(todo_list, 0))) {
4664 unlink(rebase_path_fixup_msg());
4665 unlink(rebase_path_squash_msg());
4666 unlink(rebase_path_current_fixups());
4667 strbuf_reset(&opts->current_fixups);
4668 opts->current_fixup_count = 0;
4670 } else {
4671 /* we are in a fixup/squash chain */
4672 const char *p = opts->current_fixups.buf;
4673 int len = opts->current_fixups.len;
4675 opts->current_fixup_count--;
4676 if (!len)
4677 BUG("Incorrect current_fixups:\n%s", p);
4678 while (len && p[len - 1] != '\n')
4679 len--;
4680 strbuf_setlen(&opts->current_fixups, len);
4681 if (write_message(p, len, rebase_path_current_fixups(),
4682 0) < 0)
4683 return error(_("could not write file: '%s'"),
4684 rebase_path_current_fixups());
4687 * If a fixup/squash in a fixup/squash chain failed, the
4688 * commit message is already correct, no need to commit
4689 * it again.
4691 * Only if it is the final command in the fixup/squash
4692 * chain, and only if the chain is longer than a single
4693 * fixup/squash command (which was just skipped), do we
4694 * actually need to re-commit with a cleaned up commit
4695 * message.
4697 if (opts->current_fixup_count > 0 &&
4698 !is_fixup(peek_command(todo_list, 0))) {
4699 final_fixup = 1;
4701 * If there was not a single "squash" in the
4702 * chain, we only need to clean up the commit
4703 * message, no need to bother the user with
4704 * opening the commit message in the editor.
4706 if (!starts_with(p, "squash ") &&
4707 !strstr(p, "\nsquash "))
4708 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4709 } else if (is_fixup(peek_command(todo_list, 0))) {
4711 * We need to update the squash message to skip
4712 * the latest commit message.
4714 struct commit *commit;
4715 const char *path = rebase_path_squash_msg();
4716 const char *encoding = get_commit_output_encoding();
4718 if (parse_head(r, &commit) ||
4719 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4720 write_message(p, strlen(p), path, 0)) {
4721 unuse_commit_buffer(commit, p);
4722 return error(_("could not write file: "
4723 "'%s'"), path);
4725 unuse_commit_buffer(commit, p);
4729 strbuf_release(&rev);
4730 flags |= AMEND_MSG;
4733 if (is_clean) {
4734 if (refs_ref_exists(get_main_ref_store(r),
4735 "CHERRY_PICK_HEAD") &&
4736 refs_delete_ref(get_main_ref_store(r), "",
4737 "CHERRY_PICK_HEAD", NULL, 0))
4738 return error(_("could not remove CHERRY_PICK_HEAD"));
4739 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4740 return error_errno(_("could not remove '%s'"),
4741 git_path_merge_msg(r));
4742 if (!final_fixup)
4743 return 0;
4746 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4747 opts, flags))
4748 return error(_("could not commit staged changes."));
4749 unlink(rebase_path_amend());
4750 unlink(git_path_merge_head(r));
4751 unlink(git_path_auto_merge(r));
4752 if (final_fixup) {
4753 unlink(rebase_path_fixup_msg());
4754 unlink(rebase_path_squash_msg());
4756 if (opts->current_fixup_count > 0) {
4758 * Whether final fixup or not, we just cleaned up the commit
4759 * message...
4761 unlink(rebase_path_current_fixups());
4762 strbuf_reset(&opts->current_fixups);
4763 opts->current_fixup_count = 0;
4765 return 0;
4768 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4770 struct todo_list todo_list = TODO_LIST_INIT;
4771 int res;
4773 if (read_and_refresh_cache(r, opts))
4774 return -1;
4776 if (read_populate_opts(opts))
4777 return -1;
4778 if (is_rebase_i(opts)) {
4779 if ((res = read_populate_todo(r, &todo_list, opts)))
4780 goto release_todo_list;
4782 if (file_exists(rebase_path_dropped())) {
4783 if ((res = todo_list_check_against_backup(r, &todo_list)))
4784 goto release_todo_list;
4786 unlink(rebase_path_dropped());
4789 if (commit_staged_changes(r, opts, &todo_list)) {
4790 res = -1;
4791 goto release_todo_list;
4793 } else if (!file_exists(get_todo_path(opts)))
4794 return continue_single_pick(r, opts);
4795 else if ((res = read_populate_todo(r, &todo_list, opts)))
4796 goto release_todo_list;
4798 if (!is_rebase_i(opts)) {
4799 /* Verify that the conflict has been resolved */
4800 if (refs_ref_exists(get_main_ref_store(r),
4801 "CHERRY_PICK_HEAD") ||
4802 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4803 res = continue_single_pick(r, opts);
4804 if (res)
4805 goto release_todo_list;
4807 if (index_differs_from(r, "HEAD", NULL, 0)) {
4808 res = error_dirty_index(r, opts);
4809 goto release_todo_list;
4811 todo_list.current++;
4812 } else if (file_exists(rebase_path_stopped_sha())) {
4813 struct strbuf buf = STRBUF_INIT;
4814 struct object_id oid;
4816 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4817 READ_ONELINER_SKIP_IF_EMPTY) &&
4818 !get_oid_hex(buf.buf, &oid))
4819 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4820 strbuf_release(&buf);
4823 res = pick_commits(r, &todo_list, opts);
4824 release_todo_list:
4825 todo_list_release(&todo_list);
4826 return res;
4829 static int single_pick(struct repository *r,
4830 struct commit *cmit,
4831 struct replay_opts *opts)
4833 int check_todo;
4834 struct todo_item item;
4836 item.command = opts->action == REPLAY_PICK ?
4837 TODO_PICK : TODO_REVERT;
4838 item.commit = cmit;
4840 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4841 return do_pick_commit(r, &item, opts, 0, &check_todo);
4844 int sequencer_pick_revisions(struct repository *r,
4845 struct replay_opts *opts)
4847 struct todo_list todo_list = TODO_LIST_INIT;
4848 struct object_id oid;
4849 int i, res;
4851 assert(opts->revs);
4852 if (read_and_refresh_cache(r, opts))
4853 return -1;
4855 for (i = 0; i < opts->revs->pending.nr; i++) {
4856 struct object_id oid;
4857 const char *name = opts->revs->pending.objects[i].name;
4859 /* This happens when using --stdin. */
4860 if (!strlen(name))
4861 continue;
4863 if (!get_oid(name, &oid)) {
4864 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4865 enum object_type type = oid_object_info(r,
4866 &oid,
4867 NULL);
4868 return error(_("%s: can't cherry-pick a %s"),
4869 name, type_name(type));
4871 } else
4872 return error(_("%s: bad revision"), name);
4876 * If we were called as "git cherry-pick <commit>", just
4877 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4878 * REVERT_HEAD, and don't touch the sequencer state.
4879 * This means it is possible to cherry-pick in the middle
4880 * of a cherry-pick sequence.
4882 if (opts->revs->cmdline.nr == 1 &&
4883 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4884 opts->revs->no_walk &&
4885 !opts->revs->cmdline.rev->flags) {
4886 struct commit *cmit;
4887 if (prepare_revision_walk(opts->revs))
4888 return error(_("revision walk setup failed"));
4889 cmit = get_revision(opts->revs);
4890 if (!cmit)
4891 return error(_("empty commit set passed"));
4892 if (get_revision(opts->revs))
4893 BUG("unexpected extra commit from walk");
4894 return single_pick(r, cmit, opts);
4898 * Start a new cherry-pick/ revert sequence; but
4899 * first, make sure that an existing one isn't in
4900 * progress
4903 if (walk_revs_populate_todo(&todo_list, opts) ||
4904 create_seq_dir(r) < 0)
4905 return -1;
4906 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4907 return error(_("can't revert as initial commit"));
4908 if (save_head(oid_to_hex(&oid)))
4909 return -1;
4910 if (save_opts(opts))
4911 return -1;
4912 update_abort_safety_file();
4913 res = pick_commits(r, &todo_list, opts);
4914 todo_list_release(&todo_list);
4915 return res;
4918 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4920 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4921 struct strbuf sob = STRBUF_INIT;
4922 int has_footer;
4924 strbuf_addstr(&sob, sign_off_header);
4925 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4926 strbuf_addch(&sob, '\n');
4928 if (!ignore_footer)
4929 strbuf_complete_line(msgbuf);
4932 * If the whole message buffer is equal to the sob, pretend that we
4933 * found a conforming footer with a matching sob
4935 if (msgbuf->len - ignore_footer == sob.len &&
4936 !strncmp(msgbuf->buf, sob.buf, sob.len))
4937 has_footer = 3;
4938 else
4939 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4941 if (!has_footer) {
4942 const char *append_newlines = NULL;
4943 size_t len = msgbuf->len - ignore_footer;
4945 if (!len) {
4947 * The buffer is completely empty. Leave foom for
4948 * the title and body to be filled in by the user.
4950 append_newlines = "\n\n";
4951 } else if (len == 1) {
4953 * Buffer contains a single newline. Add another
4954 * so that we leave room for the title and body.
4956 append_newlines = "\n";
4957 } else if (msgbuf->buf[len - 2] != '\n') {
4959 * Buffer ends with a single newline. Add another
4960 * so that there is an empty line between the message
4961 * body and the sob.
4963 append_newlines = "\n";
4964 } /* else, the buffer already ends with two newlines. */
4966 if (append_newlines)
4967 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4968 append_newlines, strlen(append_newlines));
4971 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4972 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4973 sob.buf, sob.len);
4975 strbuf_release(&sob);
4978 struct labels_entry {
4979 struct hashmap_entry entry;
4980 char label[FLEX_ARRAY];
4983 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4984 const struct hashmap_entry *entry_or_key, const void *key)
4986 const struct labels_entry *a, *b;
4988 a = container_of(eptr, const struct labels_entry, entry);
4989 b = container_of(entry_or_key, const struct labels_entry, entry);
4991 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4994 struct string_entry {
4995 struct oidmap_entry entry;
4996 char string[FLEX_ARRAY];
4999 struct label_state {
5000 struct oidmap commit2label;
5001 struct hashmap labels;
5002 struct strbuf buf;
5005 static const char *label_oid(struct object_id *oid, const char *label,
5006 struct label_state *state)
5008 struct labels_entry *labels_entry;
5009 struct string_entry *string_entry;
5010 struct object_id dummy;
5011 int i;
5013 string_entry = oidmap_get(&state->commit2label, oid);
5014 if (string_entry)
5015 return string_entry->string;
5018 * For "uninteresting" commits, i.e. commits that are not to be
5019 * rebased, and which can therefore not be labeled, we use a unique
5020 * abbreviation of the commit name. This is slightly more complicated
5021 * than calling find_unique_abbrev() because we also need to make
5022 * sure that the abbreviation does not conflict with any other
5023 * label.
5025 * We disallow "interesting" commits to be labeled by a string that
5026 * is a valid full-length hash, to ensure that we always can find an
5027 * abbreviation for any uninteresting commit's names that does not
5028 * clash with any other label.
5030 strbuf_reset(&state->buf);
5031 if (!label) {
5032 char *p;
5034 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5035 label = p = state->buf.buf;
5037 find_unique_abbrev_r(p, oid, default_abbrev);
5040 * We may need to extend the abbreviated hash so that there is
5041 * no conflicting label.
5043 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5044 size_t i = strlen(p) + 1;
5046 oid_to_hex_r(p, oid);
5047 for (; i < the_hash_algo->hexsz; i++) {
5048 char save = p[i];
5049 p[i] = '\0';
5050 if (!hashmap_get_from_hash(&state->labels,
5051 strihash(p), p))
5052 break;
5053 p[i] = save;
5056 } else {
5057 struct strbuf *buf = &state->buf;
5060 * Sanitize labels by replacing non-alpha-numeric characters
5061 * (including white-space ones) by dashes, as they might be
5062 * illegal in file names (and hence in ref names).
5064 * Note that we retain non-ASCII UTF-8 characters (identified
5065 * via the most significant bit). They should be all acceptable
5066 * in file names. We do not validate the UTF-8 here, that's not
5067 * the job of this function.
5069 for (; *label; label++)
5070 if ((*label & 0x80) || isalnum(*label))
5071 strbuf_addch(buf, *label);
5072 /* avoid leading dash and double-dashes */
5073 else if (buf->len && buf->buf[buf->len - 1] != '-')
5074 strbuf_addch(buf, '-');
5075 if (!buf->len) {
5076 strbuf_addstr(buf, "rev-");
5077 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5079 label = buf->buf;
5081 if ((buf->len == the_hash_algo->hexsz &&
5082 !get_oid_hex(label, &dummy)) ||
5083 (buf->len == 1 && *label == '#') ||
5084 hashmap_get_from_hash(&state->labels,
5085 strihash(label), label)) {
5087 * If the label already exists, or if the label is a
5088 * valid full OID, or the label is a '#' (which we use
5089 * as a separator between merge heads and oneline), we
5090 * append a dash and a number to make it unique.
5092 size_t len = buf->len;
5094 for (i = 2; ; i++) {
5095 strbuf_setlen(buf, len);
5096 strbuf_addf(buf, "-%d", i);
5097 if (!hashmap_get_from_hash(&state->labels,
5098 strihash(buf->buf),
5099 buf->buf))
5100 break;
5103 label = buf->buf;
5107 FLEX_ALLOC_STR(labels_entry, label, label);
5108 hashmap_entry_init(&labels_entry->entry, strihash(label));
5109 hashmap_add(&state->labels, &labels_entry->entry);
5111 FLEX_ALLOC_STR(string_entry, string, label);
5112 oidcpy(&string_entry->entry.oid, oid);
5113 oidmap_put(&state->commit2label, string_entry);
5115 return string_entry->string;
5118 static int make_script_with_merges(struct pretty_print_context *pp,
5119 struct rev_info *revs, struct strbuf *out,
5120 unsigned flags)
5122 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5123 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5124 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5125 int skipped_commit = 0;
5126 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5127 struct strbuf label = STRBUF_INIT;
5128 struct commit_list *commits = NULL, **tail = &commits, *iter;
5129 struct commit_list *tips = NULL, **tips_tail = &tips;
5130 struct commit *commit;
5131 struct oidmap commit2todo = OIDMAP_INIT;
5132 struct string_entry *entry;
5133 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5134 shown = OIDSET_INIT;
5135 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5137 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5138 const char *cmd_pick = abbr ? "p" : "pick",
5139 *cmd_label = abbr ? "l" : "label",
5140 *cmd_reset = abbr ? "t" : "reset",
5141 *cmd_merge = abbr ? "m" : "merge";
5143 oidmap_init(&commit2todo, 0);
5144 oidmap_init(&state.commit2label, 0);
5145 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5146 strbuf_init(&state.buf, 32);
5148 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5149 struct labels_entry *onto_label_entry;
5150 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5151 FLEX_ALLOC_STR(entry, string, "onto");
5152 oidcpy(&entry->entry.oid, oid);
5153 oidmap_put(&state.commit2label, entry);
5155 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5156 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5157 hashmap_add(&state.labels, &onto_label_entry->entry);
5161 * First phase:
5162 * - get onelines for all commits
5163 * - gather all branch tips (i.e. 2nd or later parents of merges)
5164 * - label all branch tips
5166 while ((commit = get_revision(revs))) {
5167 struct commit_list *to_merge;
5168 const char *p1, *p2;
5169 struct object_id *oid;
5170 int is_empty;
5172 tail = &commit_list_insert(commit, tail)->next;
5173 oidset_insert(&interesting, &commit->object.oid);
5175 is_empty = is_original_commit_empty(commit);
5176 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5177 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5178 warning(_("skipped previously applied commit %s"),
5179 short_commit_name(commit));
5180 skipped_commit = 1;
5181 continue;
5183 if (is_empty && !keep_empty)
5184 continue;
5186 strbuf_reset(&oneline);
5187 pretty_print_commit(pp, commit, &oneline);
5189 to_merge = commit->parents ? commit->parents->next : NULL;
5190 if (!to_merge) {
5191 /* non-merge commit: easy case */
5192 strbuf_reset(&buf);
5193 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5194 oid_to_hex(&commit->object.oid),
5195 oneline.buf);
5196 if (is_empty)
5197 strbuf_addf(&buf, " %c empty",
5198 comment_line_char);
5200 FLEX_ALLOC_STR(entry, string, buf.buf);
5201 oidcpy(&entry->entry.oid, &commit->object.oid);
5202 oidmap_put(&commit2todo, entry);
5204 continue;
5207 /* Create a label */
5208 strbuf_reset(&label);
5209 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5210 (p1 = strchr(p1, '\'')) &&
5211 (p2 = strchr(++p1, '\'')))
5212 strbuf_add(&label, p1, p2 - p1);
5213 else if (skip_prefix(oneline.buf, "Merge pull request ",
5214 &p1) &&
5215 (p1 = strstr(p1, " from ")))
5216 strbuf_addstr(&label, p1 + strlen(" from "));
5217 else
5218 strbuf_addbuf(&label, &oneline);
5220 strbuf_reset(&buf);
5221 strbuf_addf(&buf, "%s -C %s",
5222 cmd_merge, oid_to_hex(&commit->object.oid));
5224 /* label the tips of merged branches */
5225 for (; to_merge; to_merge = to_merge->next) {
5226 oid = &to_merge->item->object.oid;
5227 strbuf_addch(&buf, ' ');
5229 if (!oidset_contains(&interesting, oid)) {
5230 strbuf_addstr(&buf, label_oid(oid, NULL,
5231 &state));
5232 continue;
5235 tips_tail = &commit_list_insert(to_merge->item,
5236 tips_tail)->next;
5238 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5240 strbuf_addf(&buf, " # %s", oneline.buf);
5242 FLEX_ALLOC_STR(entry, string, buf.buf);
5243 oidcpy(&entry->entry.oid, &commit->object.oid);
5244 oidmap_put(&commit2todo, entry);
5246 if (skipped_commit)
5247 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5248 _("use --reapply-cherry-picks to include skipped commits"));
5251 * Second phase:
5252 * - label branch points
5253 * - add HEAD to the branch tips
5255 for (iter = commits; iter; iter = iter->next) {
5256 struct commit_list *parent = iter->item->parents;
5257 for (; parent; parent = parent->next) {
5258 struct object_id *oid = &parent->item->object.oid;
5259 if (!oidset_contains(&interesting, oid))
5260 continue;
5261 if (oidset_insert(&child_seen, oid))
5262 label_oid(oid, "branch-point", &state);
5265 /* Add HEAD as implicit "tip of branch" */
5266 if (!iter->next)
5267 tips_tail = &commit_list_insert(iter->item,
5268 tips_tail)->next;
5272 * Third phase: output the todo list. This is a bit tricky, as we
5273 * want to avoid jumping back and forth between revisions. To
5274 * accomplish that goal, we walk backwards from the branch tips,
5275 * gathering commits not yet shown, reversing the list on the fly,
5276 * then outputting that list (labeling revisions as needed).
5278 strbuf_addf(out, "%s onto\n", cmd_label);
5279 for (iter = tips; iter; iter = iter->next) {
5280 struct commit_list *list = NULL, *iter2;
5282 commit = iter->item;
5283 if (oidset_contains(&shown, &commit->object.oid))
5284 continue;
5285 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5287 if (entry)
5288 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5289 else
5290 strbuf_addch(out, '\n');
5292 while (oidset_contains(&interesting, &commit->object.oid) &&
5293 !oidset_contains(&shown, &commit->object.oid)) {
5294 commit_list_insert(commit, &list);
5295 if (!commit->parents) {
5296 commit = NULL;
5297 break;
5299 commit = commit->parents->item;
5302 if (!commit)
5303 strbuf_addf(out, "%s %s\n", cmd_reset,
5304 rebase_cousins || root_with_onto ?
5305 "onto" : "[new root]");
5306 else {
5307 const char *to = NULL;
5309 entry = oidmap_get(&state.commit2label,
5310 &commit->object.oid);
5311 if (entry)
5312 to = entry->string;
5313 else if (!rebase_cousins)
5314 to = label_oid(&commit->object.oid, NULL,
5315 &state);
5317 if (!to || !strcmp(to, "onto"))
5318 strbuf_addf(out, "%s onto\n", cmd_reset);
5319 else {
5320 strbuf_reset(&oneline);
5321 pretty_print_commit(pp, commit, &oneline);
5322 strbuf_addf(out, "%s %s # %s\n",
5323 cmd_reset, to, oneline.buf);
5327 for (iter2 = list; iter2; iter2 = iter2->next) {
5328 struct object_id *oid = &iter2->item->object.oid;
5329 entry = oidmap_get(&commit2todo, oid);
5330 /* only show if not already upstream */
5331 if (entry)
5332 strbuf_addf(out, "%s\n", entry->string);
5333 entry = oidmap_get(&state.commit2label, oid);
5334 if (entry)
5335 strbuf_addf(out, "%s %s\n",
5336 cmd_label, entry->string);
5337 oidset_insert(&shown, oid);
5340 free_commit_list(list);
5343 free_commit_list(commits);
5344 free_commit_list(tips);
5346 strbuf_release(&label);
5347 strbuf_release(&oneline);
5348 strbuf_release(&buf);
5350 oidmap_free(&commit2todo, 1);
5351 oidmap_free(&state.commit2label, 1);
5352 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5353 strbuf_release(&state.buf);
5355 return 0;
5358 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5359 const char **argv, unsigned flags)
5361 char *format = NULL;
5362 struct pretty_print_context pp = {0};
5363 struct rev_info revs;
5364 struct commit *commit;
5365 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5366 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5367 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5368 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5369 int skipped_commit = 0;
5371 repo_init_revisions(r, &revs, NULL);
5372 revs.verbose_header = 1;
5373 if (!rebase_merges)
5374 revs.max_parents = 1;
5375 revs.cherry_mark = !reapply_cherry_picks;
5376 revs.limited = 1;
5377 revs.reverse = 1;
5378 revs.right_only = 1;
5379 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5380 revs.topo_order = 1;
5382 revs.pretty_given = 1;
5383 git_config_get_string("rebase.instructionFormat", &format);
5384 if (!format || !*format) {
5385 free(format);
5386 format = xstrdup("%s");
5388 get_commit_format(format, &revs);
5389 free(format);
5390 pp.fmt = revs.commit_format;
5391 pp.output_encoding = get_log_output_encoding();
5393 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5394 return error(_("make_script: unhandled options"));
5396 if (prepare_revision_walk(&revs) < 0)
5397 return error(_("make_script: error preparing revisions"));
5399 if (rebase_merges)
5400 return make_script_with_merges(&pp, &revs, out, flags);
5402 while ((commit = get_revision(&revs))) {
5403 int is_empty = is_original_commit_empty(commit);
5405 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5406 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5407 warning(_("skipped previously applied commit %s"),
5408 short_commit_name(commit));
5409 skipped_commit = 1;
5410 continue;
5412 if (is_empty && !keep_empty)
5413 continue;
5414 strbuf_addf(out, "%s %s ", insn,
5415 oid_to_hex(&commit->object.oid));
5416 pretty_print_commit(&pp, commit, out);
5417 if (is_empty)
5418 strbuf_addf(out, " %c empty", comment_line_char);
5419 strbuf_addch(out, '\n');
5421 if (skipped_commit)
5422 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5423 _("use --reapply-cherry-picks to include skipped commits"));
5424 return 0;
5428 * Add commands after pick and (series of) squash/fixup commands
5429 * in the todo list.
5431 void todo_list_add_exec_commands(struct todo_list *todo_list,
5432 struct string_list *commands)
5434 struct strbuf *buf = &todo_list->buf;
5435 size_t base_offset = buf->len;
5436 int i, insert, nr = 0, alloc = 0;
5437 struct todo_item *items = NULL, *base_items = NULL;
5439 CALLOC_ARRAY(base_items, commands->nr);
5440 for (i = 0; i < commands->nr; i++) {
5441 size_t command_len = strlen(commands->items[i].string);
5443 strbuf_addstr(buf, commands->items[i].string);
5444 strbuf_addch(buf, '\n');
5446 base_items[i].command = TODO_EXEC;
5447 base_items[i].offset_in_buf = base_offset;
5448 base_items[i].arg_offset = base_offset + strlen("exec ");
5449 base_items[i].arg_len = command_len - strlen("exec ");
5451 base_offset += command_len + 1;
5455 * Insert <commands> after every pick. Here, fixup/squash chains
5456 * are considered part of the pick, so we insert the commands *after*
5457 * those chains if there are any.
5459 * As we insert the exec commands immediately after rearranging
5460 * any fixups and before the user edits the list, a fixup chain
5461 * can never contain comments (any comments are empty picks that
5462 * have been commented out because the user did not specify
5463 * --keep-empty). So, it is safe to insert an exec command
5464 * without looking at the command following a comment.
5466 insert = 0;
5467 for (i = 0; i < todo_list->nr; i++) {
5468 enum todo_command command = todo_list->items[i].command;
5469 if (insert && !is_fixup(command)) {
5470 ALLOC_GROW(items, nr + commands->nr, alloc);
5471 COPY_ARRAY(items + nr, base_items, commands->nr);
5472 nr += commands->nr;
5474 insert = 0;
5477 ALLOC_GROW(items, nr + 1, alloc);
5478 items[nr++] = todo_list->items[i];
5480 if (command == TODO_PICK || command == TODO_MERGE)
5481 insert = 1;
5484 /* insert or append final <commands> */
5485 if (insert || nr == todo_list->nr) {
5486 ALLOC_GROW(items, nr + commands->nr, alloc);
5487 COPY_ARRAY(items + nr, base_items, commands->nr);
5488 nr += commands->nr;
5491 free(base_items);
5492 FREE_AND_NULL(todo_list->items);
5493 todo_list->items = items;
5494 todo_list->nr = nr;
5495 todo_list->alloc = alloc;
5498 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5499 struct strbuf *buf, int num, unsigned flags)
5501 struct todo_item *item;
5502 int i, max = todo_list->nr;
5504 if (num > 0 && num < max)
5505 max = num;
5507 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5508 char cmd;
5510 /* if the item is not a command write it and continue */
5511 if (item->command >= TODO_COMMENT) {
5512 strbuf_addf(buf, "%.*s\n", item->arg_len,
5513 todo_item_get_arg(todo_list, item));
5514 continue;
5517 /* add command to the buffer */
5518 cmd = command_to_char(item->command);
5519 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5520 strbuf_addch(buf, cmd);
5521 else
5522 strbuf_addstr(buf, command_to_string(item->command));
5524 /* add commit id */
5525 if (item->commit) {
5526 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5527 short_commit_name(item->commit) :
5528 oid_to_hex(&item->commit->object.oid);
5530 if (item->command == TODO_FIXUP) {
5531 if (item->flags & TODO_EDIT_FIXUP_MSG)
5532 strbuf_addstr(buf, " -c");
5533 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5534 strbuf_addstr(buf, " -C");
5538 if (item->command == TODO_MERGE) {
5539 if (item->flags & TODO_EDIT_MERGE_MSG)
5540 strbuf_addstr(buf, " -c");
5541 else
5542 strbuf_addstr(buf, " -C");
5545 strbuf_addf(buf, " %s", oid);
5548 /* add all the rest */
5549 if (!item->arg_len)
5550 strbuf_addch(buf, '\n');
5551 else
5552 strbuf_addf(buf, " %.*s\n", item->arg_len,
5553 todo_item_get_arg(todo_list, item));
5557 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5558 const char *file, const char *shortrevisions,
5559 const char *shortonto, int num, unsigned flags)
5561 int res;
5562 struct strbuf buf = STRBUF_INIT;
5564 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5565 if (flags & TODO_LIST_APPEND_TODO_HELP)
5566 append_todo_help(count_commands(todo_list),
5567 shortrevisions, shortonto, &buf);
5569 res = write_message(buf.buf, buf.len, file, 0);
5570 strbuf_release(&buf);
5572 return res;
5575 /* skip picking commits whose parents are unchanged */
5576 static int skip_unnecessary_picks(struct repository *r,
5577 struct todo_list *todo_list,
5578 struct object_id *base_oid)
5580 struct object_id *parent_oid;
5581 int i;
5583 for (i = 0; i < todo_list->nr; i++) {
5584 struct todo_item *item = todo_list->items + i;
5586 if (item->command >= TODO_NOOP)
5587 continue;
5588 if (item->command != TODO_PICK)
5589 break;
5590 if (parse_commit(item->commit)) {
5591 return error(_("could not parse commit '%s'"),
5592 oid_to_hex(&item->commit->object.oid));
5594 if (!item->commit->parents)
5595 break; /* root commit */
5596 if (item->commit->parents->next)
5597 break; /* merge commit */
5598 parent_oid = &item->commit->parents->item->object.oid;
5599 if (!oideq(parent_oid, base_oid))
5600 break;
5601 oidcpy(base_oid, &item->commit->object.oid);
5603 if (i > 0) {
5604 const char *done_path = rebase_path_done();
5606 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5607 error_errno(_("could not write to '%s'"), done_path);
5608 return -1;
5611 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5612 todo_list->nr -= i;
5613 todo_list->current = 0;
5614 todo_list->done_nr += i;
5616 if (is_fixup(peek_command(todo_list, 0)))
5617 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5620 return 0;
5623 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5624 const char *shortrevisions, const char *onto_name,
5625 struct commit *onto, const struct object_id *orig_head,
5626 struct string_list *commands, unsigned autosquash,
5627 struct todo_list *todo_list)
5629 char shortonto[GIT_MAX_HEXSZ + 1];
5630 const char *todo_file = rebase_path_todo();
5631 struct todo_list new_todo = TODO_LIST_INIT;
5632 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5633 struct object_id oid = onto->object.oid;
5634 int res;
5636 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5638 if (buf->len == 0) {
5639 struct todo_item *item = append_new_todo(todo_list);
5640 item->command = TODO_NOOP;
5641 item->commit = NULL;
5642 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5645 if (autosquash && todo_list_rearrange_squash(todo_list))
5646 return -1;
5648 if (commands->nr)
5649 todo_list_add_exec_commands(todo_list, commands);
5651 if (count_commands(todo_list) == 0) {
5652 apply_autostash(rebase_path_autostash());
5653 sequencer_remove_state(opts);
5655 return error(_("nothing to do"));
5658 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5659 shortonto, flags);
5660 if (res == -1)
5661 return -1;
5662 else if (res == -2) {
5663 apply_autostash(rebase_path_autostash());
5664 sequencer_remove_state(opts);
5666 return -1;
5667 } else if (res == -3) {
5668 apply_autostash(rebase_path_autostash());
5669 sequencer_remove_state(opts);
5670 todo_list_release(&new_todo);
5672 return error(_("nothing to do"));
5673 } else if (res == -4) {
5674 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5675 todo_list_release(&new_todo);
5677 return -1;
5680 /* Expand the commit IDs */
5681 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5682 strbuf_swap(&new_todo.buf, &buf2);
5683 strbuf_release(&buf2);
5684 new_todo.total_nr -= new_todo.nr;
5685 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5686 BUG("invalid todo list after expanding IDs:\n%s",
5687 new_todo.buf.buf);
5689 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5690 todo_list_release(&new_todo);
5691 return error(_("could not skip unnecessary pick commands"));
5694 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5695 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5696 todo_list_release(&new_todo);
5697 return error_errno(_("could not write '%s'"), todo_file);
5700 res = -1;
5702 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5703 goto cleanup;
5705 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5706 goto cleanup;
5708 todo_list_write_total_nr(&new_todo);
5709 res = pick_commits(r, &new_todo, opts);
5711 cleanup:
5712 todo_list_release(&new_todo);
5714 return res;
5717 struct subject2item_entry {
5718 struct hashmap_entry entry;
5719 int i;
5720 char subject[FLEX_ARRAY];
5723 static int subject2item_cmp(const void *fndata,
5724 const struct hashmap_entry *eptr,
5725 const struct hashmap_entry *entry_or_key,
5726 const void *key)
5728 const struct subject2item_entry *a, *b;
5730 a = container_of(eptr, const struct subject2item_entry, entry);
5731 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5733 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5736 define_commit_slab(commit_todo_item, struct todo_item *);
5738 static int skip_fixupish(const char *subject, const char **p) {
5739 return skip_prefix(subject, "fixup! ", p) ||
5740 skip_prefix(subject, "amend! ", p) ||
5741 skip_prefix(subject, "squash! ", p);
5745 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5746 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5747 * after the former, and change "pick" to "fixup"/"squash".
5749 * Note that if the config has specified a custom instruction format, each log
5750 * message will have to be retrieved from the commit (as the oneline in the
5751 * script cannot be trusted) in order to normalize the autosquash arrangement.
5753 int todo_list_rearrange_squash(struct todo_list *todo_list)
5755 struct hashmap subject2item;
5756 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5757 char **subjects;
5758 struct commit_todo_item commit_todo;
5759 struct todo_item *items = NULL;
5761 init_commit_todo_item(&commit_todo);
5763 * The hashmap maps onelines to the respective todo list index.
5765 * If any items need to be rearranged, the next[i] value will indicate
5766 * which item was moved directly after the i'th.
5768 * In that case, last[i] will indicate the index of the latest item to
5769 * be moved to appear after the i'th.
5771 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5772 ALLOC_ARRAY(next, todo_list->nr);
5773 ALLOC_ARRAY(tail, todo_list->nr);
5774 ALLOC_ARRAY(subjects, todo_list->nr);
5775 for (i = 0; i < todo_list->nr; i++) {
5776 struct strbuf buf = STRBUF_INIT;
5777 struct todo_item *item = todo_list->items + i;
5778 const char *commit_buffer, *subject, *p;
5779 size_t subject_len;
5780 int i2 = -1;
5781 struct subject2item_entry *entry;
5783 next[i] = tail[i] = -1;
5784 if (!item->commit || item->command == TODO_DROP) {
5785 subjects[i] = NULL;
5786 continue;
5789 if (is_fixup(item->command)) {
5790 clear_commit_todo_item(&commit_todo);
5791 return error(_("the script was already rearranged."));
5794 *commit_todo_item_at(&commit_todo, item->commit) = item;
5796 parse_commit(item->commit);
5797 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5798 find_commit_subject(commit_buffer, &subject);
5799 format_subject(&buf, subject, " ");
5800 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5801 unuse_commit_buffer(item->commit, commit_buffer);
5802 if (skip_fixupish(subject, &p)) {
5803 struct commit *commit2;
5805 for (;;) {
5806 while (isspace(*p))
5807 p++;
5808 if (!skip_fixupish(p, &p))
5809 break;
5812 entry = hashmap_get_entry_from_hash(&subject2item,
5813 strhash(p), p,
5814 struct subject2item_entry,
5815 entry);
5816 if (entry)
5817 /* found by title */
5818 i2 = entry->i;
5819 else if (!strchr(p, ' ') &&
5820 (commit2 =
5821 lookup_commit_reference_by_name(p)) &&
5822 *commit_todo_item_at(&commit_todo, commit2))
5823 /* found by commit name */
5824 i2 = *commit_todo_item_at(&commit_todo, commit2)
5825 - todo_list->items;
5826 else {
5827 /* copy can be a prefix of the commit subject */
5828 for (i2 = 0; i2 < i; i2++)
5829 if (subjects[i2] &&
5830 starts_with(subjects[i2], p))
5831 break;
5832 if (i2 == i)
5833 i2 = -1;
5836 if (i2 >= 0) {
5837 rearranged = 1;
5838 if (starts_with(subject, "fixup!")) {
5839 todo_list->items[i].command = TODO_FIXUP;
5840 } else if (starts_with(subject, "amend!")) {
5841 todo_list->items[i].command = TODO_FIXUP;
5842 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5843 } else {
5844 todo_list->items[i].command = TODO_SQUASH;
5846 if (tail[i2] < 0) {
5847 next[i] = next[i2];
5848 next[i2] = i;
5849 } else {
5850 next[i] = next[tail[i2]];
5851 next[tail[i2]] = i;
5853 tail[i2] = i;
5854 } else if (!hashmap_get_from_hash(&subject2item,
5855 strhash(subject), subject)) {
5856 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5857 entry->i = i;
5858 hashmap_entry_init(&entry->entry,
5859 strhash(entry->subject));
5860 hashmap_put(&subject2item, &entry->entry);
5864 if (rearranged) {
5865 for (i = 0; i < todo_list->nr; i++) {
5866 enum todo_command command = todo_list->items[i].command;
5867 int cur = i;
5870 * Initially, all commands are 'pick's. If it is a
5871 * fixup or a squash now, we have rearranged it.
5873 if (is_fixup(command))
5874 continue;
5876 while (cur >= 0) {
5877 ALLOC_GROW(items, nr + 1, alloc);
5878 items[nr++] = todo_list->items[cur];
5879 cur = next[cur];
5883 FREE_AND_NULL(todo_list->items);
5884 todo_list->items = items;
5885 todo_list->nr = nr;
5886 todo_list->alloc = alloc;
5889 free(next);
5890 free(tail);
5891 for (i = 0; i < todo_list->nr; i++)
5892 free(subjects[i]);
5893 free(subjects);
5894 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5896 clear_commit_todo_item(&commit_todo);
5898 return 0;
5901 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5903 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5904 struct object_id cherry_pick_head, rebase_head;
5906 if (file_exists(git_path_seq_dir()))
5907 *whence = FROM_CHERRY_PICK_MULTI;
5908 if (file_exists(rebase_path()) &&
5909 !get_oid("REBASE_HEAD", &rebase_head) &&
5910 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5911 oideq(&rebase_head, &cherry_pick_head))
5912 *whence = FROM_REBASE_PICK;
5913 else
5914 *whence = FROM_CHERRY_PICK_SINGLE;
5916 return 1;
5919 return 0;