revisions API: have release_revisions() release "grep_filter"
[git/debian.git] / sequencer.c
blob41ae5e25278d5156dd0db251fe5cd2fe19744713
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "hook.h"
12 #include "exec-cmd.h"
13 #include "utf8.h"
14 #include "cache-tree.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "rerere.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
20 #include "refs.h"
21 #include "strvec.h"
22 #include "quote.h"
23 #include "trailer.h"
24 #include "log-tree.h"
25 #include "wt-status.h"
26 #include "hashmap.h"
27 #include "notes-utils.h"
28 #include "sigchain.h"
29 #include "unpack-trees.h"
30 #include "worktree.h"
31 #include "oidmap.h"
32 #include "oidset.h"
33 #include "commit-slab.h"
34 #include "alias.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
37 #include "reset.h"
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
41 static const char sign_off_header[] = "Signed-off-by: ";
42 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
44 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
46 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
48 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
49 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
50 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
51 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
53 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
55 * The file containing rebase commands, comments, and empty lines.
56 * This file is created by "git rebase -i" then edited by the user. As
57 * the lines are processed, they are removed from the front of this
58 * file and written to the tail of 'done'.
60 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
61 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
63 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
66 * The rebase command lines that have already been processed. A line
67 * is moved here when it is first handled, before any associated user
68 * actions.
70 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
72 * The file to keep track of how many commands were already processed (e.g.
73 * for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
77 * The file to keep track of how many commands are to be processed in total
78 * (e.g. for the prompt).
80 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
82 * The commit message that is planned to be used for any changes that
83 * need to be committed following a user interaction.
85 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
87 * The file into which is accumulated the suggested commit message for
88 * squash/fixup commands. When the first of a series of squash/fixups
89 * is seen, the file is created and the commit message from the
90 * previous commit and from the first squash/fixup commit are written
91 * to it. The commit message for each subsequent squash/fixup commit
92 * is appended to the file as it is processed.
94 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
96 * If the current series of squash/fixups has not yet included a squash
97 * command, then this file exists and holds the commit message of the
98 * original "pick" commit. (If the series ends without a "squash"
99 * command, then this can be used as the commit message of the combined
100 * commit without opening the editor.)
102 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
104 * This file contains the list fixup/squash commands that have been
105 * accumulated into message-fixup or message-squash so far.
107 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
109 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
110 * GIT_AUTHOR_DATE that will be used for the commit that is currently
111 * being rebased.
113 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
115 * When an "edit" rebase command is being processed, the SHA1 of the
116 * commit to be edited is recorded in this file. When "git rebase
117 * --continue" is executed, if there are any staged changes then they
118 * will be amended to the HEAD commit, but only provided the HEAD
119 * commit is still the commit to be edited. When any other rebase
120 * command is processed, this file is deleted.
122 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
124 * When we stop at a given patch via the "edit" command, this file contains
125 * the commit object name of the corresponding patch.
127 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
129 * For the post-rewrite hook, we make a list of rewritten commits and
130 * their new sha1s. The rewritten-pending list keeps the sha1s of
131 * commits that have been processed, but not committed yet,
132 * e.g. because they are waiting for a 'squash' command.
134 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
135 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
136 "rebase-merge/rewritten-pending")
139 * The path of the file containing the OID of the "squash onto" commit, i.e.
140 * the dummy commit used for `reset [new root]`.
142 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
145 * The path of the file listing refs that need to be deleted after the rebase
146 * finishes. This is used by the `label` command to record the need for cleanup.
148 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
151 * The following files are written by git-rebase just after parsing the
152 * command-line.
154 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
155 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
156 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
157 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
158 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
159 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
160 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
161 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
162 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
163 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
164 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
165 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
166 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
167 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
170 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
172 static int git_sequencer_config(const char *k, const char *v, void *cb)
174 struct replay_opts *opts = cb;
175 int status;
177 if (!strcmp(k, "commit.cleanup")) {
178 const char *s;
180 status = git_config_string(&s, k, v);
181 if (status)
182 return status;
184 if (!strcmp(s, "verbatim")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "whitespace")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
189 opts->explicit_cleanup = 1;
190 } else if (!strcmp(s, "strip")) {
191 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
192 opts->explicit_cleanup = 1;
193 } else if (!strcmp(s, "scissors")) {
194 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
195 opts->explicit_cleanup = 1;
196 } else {
197 warning(_("invalid commit message cleanup mode '%s'"),
201 free((char *)s);
202 return status;
205 if (!strcmp(k, "commit.gpgsign")) {
206 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
207 return 0;
210 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
211 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212 if (ret == 0) {
214 * pull.twohead is allowed to be multi-valued; we only
215 * care about the first value.
217 char *tmp = strchr(opts->default_strategy, ' ');
218 if (tmp)
219 *tmp = '\0';
221 return ret;
224 status = git_gpg_config(k, v, NULL);
225 if (status)
226 return status;
228 return git_diff_basic_config(k, v, NULL);
231 void sequencer_init_config(struct replay_opts *opts)
233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
234 git_config(git_sequencer_config, opts);
237 static inline int is_rebase_i(const struct replay_opts *opts)
239 return opts->action == REPLAY_INTERACTIVE_REBASE;
242 static const char *get_dir(const struct replay_opts *opts)
244 if (is_rebase_i(opts))
245 return rebase_path();
246 return git_path_seq_dir();
249 static const char *get_todo_path(const struct replay_opts *opts)
251 if (is_rebase_i(opts))
252 return rebase_path_todo();
253 return git_path_todo_file();
257 * Returns 0 for non-conforming footer
258 * Returns 1 for conforming footer
259 * Returns 2 when sob exists within conforming footer
260 * Returns 3 when sob exists within conforming footer as last entry
262 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
263 size_t ignore_footer)
265 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
266 struct trailer_info info;
267 size_t i;
268 int found_sob = 0, found_sob_last = 0;
269 char saved_char;
271 opts.no_divider = 1;
273 if (ignore_footer) {
274 saved_char = sb->buf[sb->len - ignore_footer];
275 sb->buf[sb->len - ignore_footer] = '\0';
278 trailer_info_get(&info, sb->buf, &opts);
280 if (ignore_footer)
281 sb->buf[sb->len - ignore_footer] = saved_char;
283 if (info.trailer_start == info.trailer_end)
284 return 0;
286 for (i = 0; i < info.trailer_nr; i++)
287 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
288 found_sob = 1;
289 if (i == info.trailer_nr - 1)
290 found_sob_last = 1;
293 trailer_info_release(&info);
295 if (found_sob_last)
296 return 3;
297 if (found_sob)
298 return 2;
299 return 1;
302 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
304 static struct strbuf buf = STRBUF_INIT;
306 strbuf_reset(&buf);
307 if (opts->gpg_sign)
308 sq_quotef(&buf, "-S%s", opts->gpg_sign);
309 return buf.buf;
312 int sequencer_remove_state(struct replay_opts *opts)
314 struct strbuf buf = STRBUF_INIT;
315 int i, ret = 0;
317 if (is_rebase_i(opts) &&
318 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319 char *p = buf.buf;
320 while (*p) {
321 char *eol = strchr(p, '\n');
322 if (eol)
323 *eol = '\0';
324 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
325 warning(_("could not delete '%s'"), p);
326 ret = -1;
328 if (!eol)
329 break;
330 p = eol + 1;
334 free(opts->gpg_sign);
335 free(opts->default_strategy);
336 free(opts->strategy);
337 for (i = 0; i < opts->xopts_nr; i++)
338 free(opts->xopts[i]);
339 free(opts->xopts);
340 strbuf_release(&opts->current_fixups);
342 strbuf_reset(&buf);
343 strbuf_addstr(&buf, get_dir(opts));
344 if (remove_dir_recursively(&buf, 0))
345 ret = error(_("could not remove '%s'"), buf.buf);
346 strbuf_release(&buf);
348 return ret;
351 static const char *action_name(const struct replay_opts *opts)
353 switch (opts->action) {
354 case REPLAY_REVERT:
355 return N_("revert");
356 case REPLAY_PICK:
357 return N_("cherry-pick");
358 case REPLAY_INTERACTIVE_REBASE:
359 return N_("rebase");
361 die(_("unknown action: %d"), opts->action);
364 struct commit_message {
365 char *parent_label;
366 char *label;
367 char *subject;
368 const char *message;
371 static const char *short_commit_name(struct commit *commit)
373 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
376 static int get_message(struct commit *commit, struct commit_message *out)
378 const char *abbrev, *subject;
379 int subject_len;
381 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
382 abbrev = short_commit_name(commit);
384 subject_len = find_commit_subject(out->message, &subject);
386 out->subject = xmemdupz(subject, subject_len);
387 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
388 out->parent_label = xstrfmt("parent of %s", out->label);
390 return 0;
393 static void free_message(struct commit *commit, struct commit_message *msg)
395 free(msg->parent_label);
396 free(msg->label);
397 free(msg->subject);
398 unuse_commit_buffer(commit, msg->message);
401 static void print_advice(struct repository *r, int show_hint,
402 struct replay_opts *opts)
404 char *msg = getenv("GIT_CHERRY_PICK_HELP");
406 if (msg) {
407 advise("%s\n", msg);
409 * A conflict has occurred but the porcelain
410 * (typically rebase --interactive) wants to take care
411 * of the commit itself so remove CHERRY_PICK_HEAD
413 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
414 NULL, 0);
415 return;
418 if (show_hint) {
419 if (opts->no_commit)
420 advise(_("after resolving the conflicts, mark the corrected paths\n"
421 "with 'git add <paths>' or 'git rm <paths>'"));
422 else if (opts->action == REPLAY_PICK)
423 advise(_("After resolving the conflicts, mark them with\n"
424 "\"git add/rm <pathspec>\", then run\n"
425 "\"git cherry-pick --continue\".\n"
426 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
427 "To abort and get back to the state before \"git cherry-pick\",\n"
428 "run \"git cherry-pick --abort\"."));
429 else if (opts->action == REPLAY_REVERT)
430 advise(_("After resolving the conflicts, mark them with\n"
431 "\"git add/rm <pathspec>\", then run\n"
432 "\"git revert --continue\".\n"
433 "You can instead skip this commit with \"git revert --skip\".\n"
434 "To abort and get back to the state before \"git revert\",\n"
435 "run \"git revert --abort\"."));
436 else
437 BUG("unexpected pick action in print_advice()");
441 static int write_message(const void *buf, size_t len, const char *filename,
442 int append_eol)
444 struct lock_file msg_file = LOCK_INIT;
446 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
447 if (msg_fd < 0)
448 return error_errno(_("could not lock '%s'"), filename);
449 if (write_in_full(msg_fd, buf, len) < 0) {
450 error_errno(_("could not write to '%s'"), filename);
451 rollback_lock_file(&msg_file);
452 return -1;
454 if (append_eol && write(msg_fd, "\n", 1) < 0) {
455 error_errno(_("could not write eol to '%s'"), filename);
456 rollback_lock_file(&msg_file);
457 return -1;
459 if (commit_lock_file(&msg_file) < 0)
460 return error(_("failed to finalize '%s'"), filename);
462 return 0;
465 int read_oneliner(struct strbuf *buf,
466 const char *path, unsigned flags)
468 int orig_len = buf->len;
470 if (strbuf_read_file(buf, path, 0) < 0) {
471 if ((flags & READ_ONELINER_WARN_MISSING) ||
472 (errno != ENOENT && errno != ENOTDIR))
473 warning_errno(_("could not read '%s'"), path);
474 return 0;
477 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
478 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
479 --buf->len;
480 buf->buf[buf->len] = '\0';
483 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
484 return 0;
486 return 1;
489 static struct tree *empty_tree(struct repository *r)
491 return lookup_tree(r, the_hash_algo->empty_tree);
494 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
496 if (repo_read_index_unmerged(repo))
497 return error_resolve_conflict(_(action_name(opts)));
499 error(_("your local changes would be overwritten by %s."),
500 _(action_name(opts)));
502 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
503 advise(_("commit your changes or stash them to proceed."));
504 return -1;
507 static void update_abort_safety_file(void)
509 struct object_id head;
511 /* Do nothing on a single-pick */
512 if (!file_exists(git_path_seq_dir()))
513 return;
515 if (!get_oid("HEAD", &head))
516 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
517 else
518 write_file(git_path_abort_safety_file(), "%s", "");
521 static int fast_forward_to(struct repository *r,
522 const struct object_id *to,
523 const struct object_id *from,
524 int unborn,
525 struct replay_opts *opts)
527 struct ref_transaction *transaction;
528 struct strbuf sb = STRBUF_INIT;
529 struct strbuf err = STRBUF_INIT;
531 repo_read_index(r);
532 if (checkout_fast_forward(r, from, to, 1))
533 return -1; /* the callee should have complained already */
535 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
537 transaction = ref_transaction_begin(&err);
538 if (!transaction ||
539 ref_transaction_update(transaction, "HEAD",
540 to, unborn && !is_rebase_i(opts) ?
541 null_oid() : from,
542 0, sb.buf, &err) ||
543 ref_transaction_commit(transaction, &err)) {
544 ref_transaction_free(transaction);
545 error("%s", err.buf);
546 strbuf_release(&sb);
547 strbuf_release(&err);
548 return -1;
551 strbuf_release(&sb);
552 strbuf_release(&err);
553 ref_transaction_free(transaction);
554 update_abort_safety_file();
555 return 0;
558 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
559 int use_editor)
561 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
562 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
563 COMMIT_MSG_CLEANUP_SPACE;
564 else if (!strcmp(cleanup_arg, "verbatim"))
565 return COMMIT_MSG_CLEANUP_NONE;
566 else if (!strcmp(cleanup_arg, "whitespace"))
567 return COMMIT_MSG_CLEANUP_SPACE;
568 else if (!strcmp(cleanup_arg, "strip"))
569 return COMMIT_MSG_CLEANUP_ALL;
570 else if (!strcmp(cleanup_arg, "scissors"))
571 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
572 COMMIT_MSG_CLEANUP_SPACE;
573 else
574 die(_("Invalid cleanup mode %s"), cleanup_arg);
578 * NB using int rather than enum cleanup_mode to stop clang's
579 * -Wtautological-constant-out-of-range-compare complaining that the comparison
580 * is always true.
582 static const char *describe_cleanup_mode(int cleanup_mode)
584 static const char *modes[] = { "whitespace",
585 "verbatim",
586 "scissors",
587 "strip" };
589 if (cleanup_mode < ARRAY_SIZE(modes))
590 return modes[cleanup_mode];
592 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
595 void append_conflicts_hint(struct index_state *istate,
596 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
598 int i;
600 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
601 strbuf_addch(msgbuf, '\n');
602 wt_status_append_cut_line(msgbuf);
603 strbuf_addch(msgbuf, comment_line_char);
606 strbuf_addch(msgbuf, '\n');
607 strbuf_commented_addf(msgbuf, "Conflicts:\n");
608 for (i = 0; i < istate->cache_nr;) {
609 const struct cache_entry *ce = istate->cache[i++];
610 if (ce_stage(ce)) {
611 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
612 while (i < istate->cache_nr &&
613 !strcmp(ce->name, istate->cache[i]->name))
614 i++;
619 static int do_recursive_merge(struct repository *r,
620 struct commit *base, struct commit *next,
621 const char *base_label, const char *next_label,
622 struct object_id *head, struct strbuf *msgbuf,
623 struct replay_opts *opts)
625 struct merge_options o;
626 struct merge_result result;
627 struct tree *next_tree, *base_tree, *head_tree;
628 int clean, show_output;
629 int i;
630 struct lock_file index_lock = LOCK_INIT;
632 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
633 return -1;
635 repo_read_index(r);
637 init_merge_options(&o, r);
638 o.ancestor = base ? base_label : "(empty tree)";
639 o.branch1 = "HEAD";
640 o.branch2 = next ? next_label : "(empty tree)";
641 if (is_rebase_i(opts))
642 o.buffer_output = 2;
643 o.show_rename_progress = 1;
645 head_tree = parse_tree_indirect(head);
646 next_tree = next ? get_commit_tree(next) : empty_tree(r);
647 base_tree = base ? get_commit_tree(base) : empty_tree(r);
649 for (i = 0; i < opts->xopts_nr; i++)
650 parse_merge_opt(&o, opts->xopts[i]);
652 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
653 memset(&result, 0, sizeof(result));
654 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
655 &result);
656 show_output = !is_rebase_i(opts) || !result.clean;
658 * TODO: merge_switch_to_result will update index/working tree;
659 * we only really want to do that if !result.clean || this is
660 * the final patch to be picked. But determining this is the
661 * final patch would take some work, and "head_tree" would need
662 * to be replace with the tree the index matched before we
663 * started doing any picks.
665 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
666 clean = result.clean;
667 } else {
668 ensure_full_index(r->index);
669 clean = merge_trees(&o, head_tree, next_tree, base_tree);
670 if (is_rebase_i(opts) && clean <= 0)
671 fputs(o.obuf.buf, stdout);
672 strbuf_release(&o.obuf);
674 if (clean < 0) {
675 rollback_lock_file(&index_lock);
676 return clean;
679 if (write_locked_index(r->index, &index_lock,
680 COMMIT_LOCK | SKIP_IF_UNCHANGED))
682 * TRANSLATORS: %s will be "revert", "cherry-pick" or
683 * "rebase".
685 return error(_("%s: Unable to write new index file"),
686 _(action_name(opts)));
688 if (!clean)
689 append_conflicts_hint(r->index, msgbuf,
690 opts->default_msg_cleanup);
692 return !clean;
695 static struct object_id *get_cache_tree_oid(struct index_state *istate)
697 if (!cache_tree_fully_valid(istate->cache_tree))
698 if (cache_tree_update(istate, 0)) {
699 error(_("unable to update cache tree"));
700 return NULL;
703 return &istate->cache_tree->oid;
706 static int is_index_unchanged(struct repository *r)
708 struct object_id head_oid, *cache_tree_oid;
709 struct commit *head_commit;
710 struct index_state *istate = r->index;
712 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
713 return error(_("could not resolve HEAD commit"));
715 head_commit = lookup_commit(r, &head_oid);
718 * If head_commit is NULL, check_commit, called from
719 * lookup_commit, would have indicated that head_commit is not
720 * a commit object already. parse_commit() will return failure
721 * without further complaints in such a case. Otherwise, if
722 * the commit is invalid, parse_commit() will complain. So
723 * there is nothing for us to say here. Just return failure.
725 if (parse_commit(head_commit))
726 return -1;
728 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
729 return -1;
731 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
734 static int write_author_script(const char *message)
736 struct strbuf buf = STRBUF_INIT;
737 const char *eol;
738 int res;
740 for (;;)
741 if (!*message || starts_with(message, "\n")) {
742 missing_author:
743 /* Missing 'author' line? */
744 unlink(rebase_path_author_script());
745 return 0;
746 } else if (skip_prefix(message, "author ", &message))
747 break;
748 else if ((eol = strchr(message, '\n')))
749 message = eol + 1;
750 else
751 goto missing_author;
753 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
754 while (*message && *message != '\n' && *message != '\r')
755 if (skip_prefix(message, " <", &message))
756 break;
757 else if (*message != '\'')
758 strbuf_addch(&buf, *(message++));
759 else
760 strbuf_addf(&buf, "'\\%c'", *(message++));
761 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
762 while (*message && *message != '\n' && *message != '\r')
763 if (skip_prefix(message, "> ", &message))
764 break;
765 else if (*message != '\'')
766 strbuf_addch(&buf, *(message++));
767 else
768 strbuf_addf(&buf, "'\\%c'", *(message++));
769 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
770 while (*message && *message != '\n' && *message != '\r')
771 if (*message != '\'')
772 strbuf_addch(&buf, *(message++));
773 else
774 strbuf_addf(&buf, "'\\%c'", *(message++));
775 strbuf_addch(&buf, '\'');
776 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
777 strbuf_release(&buf);
778 return res;
782 * Take a series of KEY='VALUE' lines where VALUE part is
783 * sq-quoted, and append <KEY, VALUE> at the end of the string list
785 static int parse_key_value_squoted(char *buf, struct string_list *list)
787 while (*buf) {
788 struct string_list_item *item;
789 char *np;
790 char *cp = strchr(buf, '=');
791 if (!cp) {
792 np = strchrnul(buf, '\n');
793 return error(_("no key present in '%.*s'"),
794 (int) (np - buf), buf);
796 np = strchrnul(cp, '\n');
797 *cp++ = '\0';
798 item = string_list_append(list, buf);
800 buf = np + (*np == '\n');
801 *np = '\0';
802 cp = sq_dequote(cp);
803 if (!cp)
804 return error(_("unable to dequote value of '%s'"),
805 item->string);
806 item->util = xstrdup(cp);
808 return 0;
812 * Reads and parses the state directory's "author-script" file, and sets name,
813 * email and date accordingly.
814 * Returns 0 on success, -1 if the file could not be parsed.
816 * The author script is of the format:
818 * GIT_AUTHOR_NAME='$author_name'
819 * GIT_AUTHOR_EMAIL='$author_email'
820 * GIT_AUTHOR_DATE='$author_date'
822 * where $author_name, $author_email and $author_date are quoted. We are strict
823 * with our parsing, as the file was meant to be eval'd in the now-removed
824 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
825 * from what this function expects, it is better to bail out than to do
826 * something that the user does not expect.
828 int read_author_script(const char *path, char **name, char **email, char **date,
829 int allow_missing)
831 struct strbuf buf = STRBUF_INIT;
832 struct string_list kv = STRING_LIST_INIT_DUP;
833 int retval = -1; /* assume failure */
834 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
836 if (strbuf_read_file(&buf, path, 256) <= 0) {
837 strbuf_release(&buf);
838 if (errno == ENOENT && allow_missing)
839 return 0;
840 else
841 return error_errno(_("could not open '%s' for reading"),
842 path);
845 if (parse_key_value_squoted(buf.buf, &kv))
846 goto finish;
848 for (i = 0; i < kv.nr; i++) {
849 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
850 if (name_i != -2)
851 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
852 else
853 name_i = i;
854 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
855 if (email_i != -2)
856 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
857 else
858 email_i = i;
859 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
860 if (date_i != -2)
861 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
862 else
863 date_i = i;
864 } else {
865 err = error(_("unknown variable '%s'"),
866 kv.items[i].string);
869 if (name_i == -2)
870 error(_("missing 'GIT_AUTHOR_NAME'"));
871 if (email_i == -2)
872 error(_("missing 'GIT_AUTHOR_EMAIL'"));
873 if (date_i == -2)
874 error(_("missing 'GIT_AUTHOR_DATE'"));
875 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
876 goto finish;
877 *name = kv.items[name_i].util;
878 *email = kv.items[email_i].util;
879 *date = kv.items[date_i].util;
880 retval = 0;
881 finish:
882 string_list_clear(&kv, !!retval);
883 strbuf_release(&buf);
884 return retval;
888 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
889 * file with shell quoting into struct strvec. Returns -1 on
890 * error, 0 otherwise.
892 static int read_env_script(struct strvec *env)
894 char *name, *email, *date;
896 if (read_author_script(rebase_path_author_script(),
897 &name, &email, &date, 0))
898 return -1;
900 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
901 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
902 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
903 free(name);
904 free(email);
905 free(date);
907 return 0;
910 static char *get_author(const char *message)
912 size_t len;
913 const char *a;
915 a = find_commit_header(message, "author", &len);
916 if (a)
917 return xmemdupz(a, len);
919 return NULL;
922 static const char *author_date_from_env_array(const struct strvec *env)
924 int i;
925 const char *date;
927 for (i = 0; i < env->nr; i++)
928 if (skip_prefix(env->v[i],
929 "GIT_AUTHOR_DATE=", &date))
930 return date;
932 * If GIT_AUTHOR_DATE is missing we should have already errored out when
933 * reading the script
935 BUG("GIT_AUTHOR_DATE missing from author script");
938 static const char staged_changes_advice[] =
939 N_("you have staged changes in your working tree\n"
940 "If these changes are meant to be squashed into the previous commit, run:\n"
941 "\n"
942 " git commit --amend %s\n"
943 "\n"
944 "If they are meant to go into a new commit, run:\n"
945 "\n"
946 " git commit %s\n"
947 "\n"
948 "In both cases, once you're done, continue with:\n"
949 "\n"
950 " git rebase --continue\n");
952 #define ALLOW_EMPTY (1<<0)
953 #define EDIT_MSG (1<<1)
954 #define AMEND_MSG (1<<2)
955 #define CLEANUP_MSG (1<<3)
956 #define VERIFY_MSG (1<<4)
957 #define CREATE_ROOT_COMMIT (1<<5)
958 #define VERBATIM_MSG (1<<6)
960 static int run_command_silent_on_success(struct child_process *cmd)
962 struct strbuf buf = STRBUF_INIT;
963 int rc;
965 cmd->stdout_to_stderr = 1;
966 rc = pipe_command(cmd,
967 NULL, 0,
968 NULL, 0,
969 &buf, 0);
971 if (rc)
972 fputs(buf.buf, stderr);
973 strbuf_release(&buf);
974 return rc;
978 * If we are cherry-pick, and if the merge did not result in
979 * hand-editing, we will hit this commit and inherit the original
980 * author date and name.
982 * If we are revert, or if our cherry-pick results in a hand merge,
983 * we had better say that the current user is responsible for that.
985 * An exception is when run_git_commit() is called during an
986 * interactive rebase: in that case, we will want to retain the
987 * author metadata.
989 static int run_git_commit(const char *defmsg,
990 struct replay_opts *opts,
991 unsigned int flags)
993 struct child_process cmd = CHILD_PROCESS_INIT;
995 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
996 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
998 cmd.git_cmd = 1;
1000 if (is_rebase_i(opts) &&
1001 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1002 !(!defmsg && (flags & AMEND_MSG))) &&
1003 read_env_script(&cmd.env_array)) {
1004 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1006 return error(_(staged_changes_advice),
1007 gpg_opt, gpg_opt);
1010 if (opts->committer_date_is_author_date)
1011 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1012 opts->ignore_date ?
1013 "" :
1014 author_date_from_env_array(&cmd.env_array));
1015 if (opts->ignore_date)
1016 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1018 strvec_push(&cmd.args, "commit");
1020 if (!(flags & VERIFY_MSG))
1021 strvec_push(&cmd.args, "-n");
1022 if ((flags & AMEND_MSG))
1023 strvec_push(&cmd.args, "--amend");
1024 if (opts->gpg_sign)
1025 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1026 else
1027 strvec_push(&cmd.args, "--no-gpg-sign");
1028 if (defmsg)
1029 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1030 else if (!(flags & EDIT_MSG))
1031 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1032 if ((flags & CLEANUP_MSG))
1033 strvec_push(&cmd.args, "--cleanup=strip");
1034 if ((flags & VERBATIM_MSG))
1035 strvec_push(&cmd.args, "--cleanup=verbatim");
1036 if ((flags & EDIT_MSG))
1037 strvec_push(&cmd.args, "-e");
1038 else if (!(flags & CLEANUP_MSG) &&
1039 !opts->signoff && !opts->record_origin &&
1040 !opts->explicit_cleanup)
1041 strvec_push(&cmd.args, "--cleanup=verbatim");
1043 if ((flags & ALLOW_EMPTY))
1044 strvec_push(&cmd.args, "--allow-empty");
1046 if (!(flags & EDIT_MSG))
1047 strvec_push(&cmd.args, "--allow-empty-message");
1049 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1050 return run_command_silent_on_success(&cmd);
1051 else
1052 return run_command(&cmd);
1055 static int rest_is_empty(const struct strbuf *sb, int start)
1057 int i, eol;
1058 const char *nl;
1060 /* Check if the rest is just whitespace and Signed-off-by's. */
1061 for (i = start; i < sb->len; i++) {
1062 nl = memchr(sb->buf + i, '\n', sb->len - i);
1063 if (nl)
1064 eol = nl - sb->buf;
1065 else
1066 eol = sb->len;
1068 if (strlen(sign_off_header) <= eol - i &&
1069 starts_with(sb->buf + i, sign_off_header)) {
1070 i = eol;
1071 continue;
1073 while (i < eol)
1074 if (!isspace(sb->buf[i++]))
1075 return 0;
1078 return 1;
1081 void cleanup_message(struct strbuf *msgbuf,
1082 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1084 if (verbose || /* Truncate the message just before the diff, if any. */
1085 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1086 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1087 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1088 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1092 * Find out if the message in the strbuf contains only whitespace and
1093 * Signed-off-by lines.
1095 int message_is_empty(const struct strbuf *sb,
1096 enum commit_msg_cleanup_mode cleanup_mode)
1098 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1099 return 0;
1100 return rest_is_empty(sb, 0);
1104 * See if the user edited the message in the editor or left what
1105 * was in the template intact
1107 int template_untouched(const struct strbuf *sb, const char *template_file,
1108 enum commit_msg_cleanup_mode cleanup_mode)
1110 struct strbuf tmpl = STRBUF_INIT;
1111 const char *start;
1113 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1114 return 0;
1116 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1117 return 0;
1119 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1120 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1121 start = sb->buf;
1122 strbuf_release(&tmpl);
1123 return rest_is_empty(sb, start - sb->buf);
1126 int update_head_with_reflog(const struct commit *old_head,
1127 const struct object_id *new_head,
1128 const char *action, const struct strbuf *msg,
1129 struct strbuf *err)
1131 struct ref_transaction *transaction;
1132 struct strbuf sb = STRBUF_INIT;
1133 const char *nl;
1134 int ret = 0;
1136 if (action) {
1137 strbuf_addstr(&sb, action);
1138 strbuf_addstr(&sb, ": ");
1141 nl = strchr(msg->buf, '\n');
1142 if (nl) {
1143 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1144 } else {
1145 strbuf_addbuf(&sb, msg);
1146 strbuf_addch(&sb, '\n');
1149 transaction = ref_transaction_begin(err);
1150 if (!transaction ||
1151 ref_transaction_update(transaction, "HEAD", new_head,
1152 old_head ? &old_head->object.oid : null_oid(),
1153 0, sb.buf, err) ||
1154 ref_transaction_commit(transaction, err)) {
1155 ret = -1;
1157 ref_transaction_free(transaction);
1158 strbuf_release(&sb);
1160 return ret;
1163 static int run_rewrite_hook(const struct object_id *oldoid,
1164 const struct object_id *newoid)
1166 struct child_process proc = CHILD_PROCESS_INIT;
1167 int code;
1168 struct strbuf sb = STRBUF_INIT;
1169 const char *hook_path = find_hook("post-rewrite");
1171 if (!hook_path)
1172 return 0;
1174 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1175 proc.in = -1;
1176 proc.stdout_to_stderr = 1;
1177 proc.trace2_hook_name = "post-rewrite";
1179 code = start_command(&proc);
1180 if (code)
1181 return code;
1182 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1183 sigchain_push(SIGPIPE, SIG_IGN);
1184 write_in_full(proc.in, sb.buf, sb.len);
1185 close(proc.in);
1186 strbuf_release(&sb);
1187 sigchain_pop(SIGPIPE);
1188 return finish_command(&proc);
1191 void commit_post_rewrite(struct repository *r,
1192 const struct commit *old_head,
1193 const struct object_id *new_head)
1195 struct notes_rewrite_cfg *cfg;
1197 cfg = init_copy_notes_for_rewrite("amend");
1198 if (cfg) {
1199 /* we are amending, so old_head is not NULL */
1200 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1201 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1203 run_rewrite_hook(&old_head->object.oid, new_head);
1206 static int run_prepare_commit_msg_hook(struct repository *r,
1207 struct strbuf *msg,
1208 const char *commit)
1210 int ret = 0;
1211 const char *name, *arg1 = NULL, *arg2 = NULL;
1213 name = git_path_commit_editmsg();
1214 if (write_message(msg->buf, msg->len, name, 0))
1215 return -1;
1217 if (commit) {
1218 arg1 = "commit";
1219 arg2 = commit;
1220 } else {
1221 arg1 = "message";
1223 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1224 arg1, arg2, NULL))
1225 ret = error(_("'prepare-commit-msg' hook failed"));
1227 return ret;
1230 static const char implicit_ident_advice_noconfig[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly. Run the\n"
1234 "following command and follow the instructions in your editor to edit\n"
1235 "your configuration file:\n"
1236 "\n"
1237 " git config --global --edit\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 " git commit --amend --reset-author\n");
1243 static const char implicit_ident_advice_config[] =
1244 N_("Your name and email address were configured automatically based\n"
1245 "on your username and hostname. Please check that they are accurate.\n"
1246 "You can suppress this message by setting them explicitly:\n"
1247 "\n"
1248 " git config --global user.name \"Your Name\"\n"
1249 " git config --global user.email you@example.com\n"
1250 "\n"
1251 "After doing this, you may fix the identity used for this commit with:\n"
1252 "\n"
1253 " git commit --amend --reset-author\n");
1255 static const char *implicit_ident_advice(void)
1257 char *user_config = interpolate_path("~/.gitconfig", 0);
1258 char *xdg_config = xdg_config_home("config");
1259 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1261 free(user_config);
1262 free(xdg_config);
1264 if (config_exists)
1265 return _(implicit_ident_advice_config);
1266 else
1267 return _(implicit_ident_advice_noconfig);
1271 void print_commit_summary(struct repository *r,
1272 const char *prefix,
1273 const struct object_id *oid,
1274 unsigned int flags)
1276 struct rev_info rev;
1277 struct commit *commit;
1278 struct strbuf format = STRBUF_INIT;
1279 const char *head;
1280 struct pretty_print_context pctx = {0};
1281 struct strbuf author_ident = STRBUF_INIT;
1282 struct strbuf committer_ident = STRBUF_INIT;
1283 struct ref_store *refs;
1285 commit = lookup_commit(r, oid);
1286 if (!commit)
1287 die(_("couldn't look up newly created commit"));
1288 if (parse_commit(commit))
1289 die(_("could not parse newly created commit"));
1291 strbuf_addstr(&format, "format:%h] %s");
1293 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1294 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1295 if (strbuf_cmp(&author_ident, &committer_ident)) {
1296 strbuf_addstr(&format, "\n Author: ");
1297 strbuf_addbuf_percentquote(&format, &author_ident);
1299 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1300 struct strbuf date = STRBUF_INIT;
1302 format_commit_message(commit, "%ad", &date, &pctx);
1303 strbuf_addstr(&format, "\n Date: ");
1304 strbuf_addbuf_percentquote(&format, &date);
1305 strbuf_release(&date);
1307 if (!committer_ident_sufficiently_given()) {
1308 strbuf_addstr(&format, "\n Committer: ");
1309 strbuf_addbuf_percentquote(&format, &committer_ident);
1310 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1311 strbuf_addch(&format, '\n');
1312 strbuf_addstr(&format, implicit_ident_advice());
1315 strbuf_release(&author_ident);
1316 strbuf_release(&committer_ident);
1318 repo_init_revisions(r, &rev, prefix);
1319 setup_revisions(0, NULL, &rev, NULL);
1321 rev.diff = 1;
1322 rev.diffopt.output_format =
1323 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1325 rev.verbose_header = 1;
1326 rev.show_root_diff = 1;
1327 get_commit_format(format.buf, &rev);
1328 rev.always_show_header = 0;
1329 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1330 rev.diffopt.break_opt = 0;
1331 diff_setup_done(&rev.diffopt);
1333 refs = get_main_ref_store(the_repository);
1334 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1335 if (!head)
1336 die(_("unable to resolve HEAD after creating commit"));
1337 if (!strcmp(head, "HEAD"))
1338 head = _("detached HEAD");
1339 else
1340 skip_prefix(head, "refs/heads/", &head);
1341 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1342 _(" (root-commit)") : "");
1344 if (!log_tree_commit(&rev, commit)) {
1345 rev.always_show_header = 1;
1346 rev.use_terminator = 1;
1347 log_tree_commit(&rev, commit);
1350 release_revisions(&rev);
1351 strbuf_release(&format);
1354 static int parse_head(struct repository *r, struct commit **head)
1356 struct commit *current_head;
1357 struct object_id oid;
1359 if (get_oid("HEAD", &oid)) {
1360 current_head = NULL;
1361 } else {
1362 current_head = lookup_commit_reference(r, &oid);
1363 if (!current_head)
1364 return error(_("could not parse HEAD"));
1365 if (!oideq(&oid, &current_head->object.oid)) {
1366 warning(_("HEAD %s is not a commit!"),
1367 oid_to_hex(&oid));
1369 if (parse_commit(current_head))
1370 return error(_("could not parse HEAD commit"));
1372 *head = current_head;
1374 return 0;
1378 * Try to commit without forking 'git commit'. In some cases we need
1379 * to run 'git commit' to display an error message
1381 * Returns:
1382 * -1 - error unable to commit
1383 * 0 - success
1384 * 1 - run 'git commit'
1386 static int try_to_commit(struct repository *r,
1387 struct strbuf *msg, const char *author,
1388 struct replay_opts *opts, unsigned int flags,
1389 struct object_id *oid)
1391 struct object_id tree;
1392 struct commit *current_head = NULL;
1393 struct commit_list *parents = NULL;
1394 struct commit_extra_header *extra = NULL;
1395 struct strbuf err = STRBUF_INIT;
1396 struct strbuf commit_msg = STRBUF_INIT;
1397 char *amend_author = NULL;
1398 const char *committer = NULL;
1399 const char *hook_commit = NULL;
1400 enum commit_msg_cleanup_mode cleanup;
1401 int res = 0;
1403 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1404 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1406 if (parse_head(r, &current_head))
1407 return -1;
1409 if (flags & AMEND_MSG) {
1410 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1411 const char *out_enc = get_commit_output_encoding();
1412 const char *message = logmsg_reencode(current_head, NULL,
1413 out_enc);
1415 if (!msg) {
1416 const char *orig_message = NULL;
1418 find_commit_subject(message, &orig_message);
1419 msg = &commit_msg;
1420 strbuf_addstr(msg, orig_message);
1421 hook_commit = "HEAD";
1423 author = amend_author = get_author(message);
1424 unuse_commit_buffer(current_head, message);
1425 if (!author) {
1426 res = error(_("unable to parse commit author"));
1427 goto out;
1429 parents = copy_commit_list(current_head->parents);
1430 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1431 } else if (current_head &&
1432 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1433 commit_list_insert(current_head, &parents);
1436 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1437 res = error(_("git write-tree failed to write a tree"));
1438 goto out;
1441 if (!(flags & ALLOW_EMPTY)) {
1442 struct commit *first_parent = current_head;
1444 if (flags & AMEND_MSG) {
1445 if (current_head->parents) {
1446 first_parent = current_head->parents->item;
1447 if (repo_parse_commit(r, first_parent)) {
1448 res = error(_("could not parse HEAD commit"));
1449 goto out;
1451 } else {
1452 first_parent = NULL;
1455 if (oideq(first_parent
1456 ? get_commit_tree_oid(first_parent)
1457 : the_hash_algo->empty_tree,
1458 &tree)) {
1459 res = 1; /* run 'git commit' to display error message */
1460 goto out;
1464 if (hook_exists("prepare-commit-msg")) {
1465 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1466 if (res)
1467 goto out;
1468 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1469 2048) < 0) {
1470 res = error_errno(_("unable to read commit message "
1471 "from '%s'"),
1472 git_path_commit_editmsg());
1473 goto out;
1475 msg = &commit_msg;
1478 if (flags & CLEANUP_MSG)
1479 cleanup = COMMIT_MSG_CLEANUP_ALL;
1480 else if (flags & VERBATIM_MSG)
1481 cleanup = COMMIT_MSG_CLEANUP_NONE;
1482 else if ((opts->signoff || opts->record_origin) &&
1483 !opts->explicit_cleanup)
1484 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1485 else
1486 cleanup = opts->default_msg_cleanup;
1488 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1489 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1490 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1491 res = 1; /* run 'git commit' to display error message */
1492 goto out;
1495 if (opts->committer_date_is_author_date) {
1496 struct ident_split id;
1497 struct strbuf date = STRBUF_INIT;
1499 if (!opts->ignore_date) {
1500 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1501 res = error(_("invalid author identity '%s'"),
1502 author);
1503 goto out;
1505 if (!id.date_begin) {
1506 res = error(_(
1507 "corrupt author: missing date information"));
1508 goto out;
1510 strbuf_addf(&date, "@%.*s %.*s",
1511 (int)(id.date_end - id.date_begin),
1512 id.date_begin,
1513 (int)(id.tz_end - id.tz_begin),
1514 id.tz_begin);
1515 } else {
1516 reset_ident_date();
1518 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1519 getenv("GIT_COMMITTER_EMAIL"),
1520 WANT_COMMITTER_IDENT,
1521 opts->ignore_date ? NULL : date.buf,
1522 IDENT_STRICT);
1523 strbuf_release(&date);
1524 } else {
1525 reset_ident_date();
1528 if (opts->ignore_date) {
1529 struct ident_split id;
1530 char *name, *email;
1532 if (split_ident_line(&id, author, strlen(author)) < 0) {
1533 error(_("invalid author identity '%s'"), author);
1534 goto out;
1536 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1537 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1538 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1539 IDENT_STRICT);
1540 free(name);
1541 free(email);
1544 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1545 author, committer, opts->gpg_sign, extra)) {
1546 res = error(_("failed to write commit object"));
1547 goto out;
1550 if (update_head_with_reflog(current_head, oid,
1551 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1552 res = error("%s", err.buf);
1553 goto out;
1556 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1557 if (flags & AMEND_MSG)
1558 commit_post_rewrite(r, current_head, oid);
1560 out:
1561 free_commit_extra_headers(extra);
1562 strbuf_release(&err);
1563 strbuf_release(&commit_msg);
1564 free(amend_author);
1566 return res;
1569 static int write_rebase_head(struct object_id *oid)
1571 if (update_ref("rebase", "REBASE_HEAD", oid,
1572 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1573 return error(_("could not update %s"), "REBASE_HEAD");
1575 return 0;
1578 static int do_commit(struct repository *r,
1579 const char *msg_file, const char *author,
1580 struct replay_opts *opts, unsigned int flags,
1581 struct object_id *oid)
1583 int res = 1;
1585 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1586 struct object_id oid;
1587 struct strbuf sb = STRBUF_INIT;
1589 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1590 return error_errno(_("unable to read commit message "
1591 "from '%s'"),
1592 msg_file);
1594 res = try_to_commit(r, msg_file ? &sb : NULL,
1595 author, opts, flags, &oid);
1596 strbuf_release(&sb);
1597 if (!res) {
1598 refs_delete_ref(get_main_ref_store(r), "",
1599 "CHERRY_PICK_HEAD", NULL, 0);
1600 unlink(git_path_merge_msg(r));
1601 if (!is_rebase_i(opts))
1602 print_commit_summary(r, NULL, &oid,
1603 SUMMARY_SHOW_AUTHOR_DATE);
1604 return res;
1607 if (res == 1) {
1608 if (is_rebase_i(opts) && oid)
1609 if (write_rebase_head(oid))
1610 return -1;
1611 return run_git_commit(msg_file, opts, flags);
1614 return res;
1617 static int is_original_commit_empty(struct commit *commit)
1619 const struct object_id *ptree_oid;
1621 if (parse_commit(commit))
1622 return error(_("could not parse commit %s"),
1623 oid_to_hex(&commit->object.oid));
1624 if (commit->parents) {
1625 struct commit *parent = commit->parents->item;
1626 if (parse_commit(parent))
1627 return error(_("could not parse parent commit %s"),
1628 oid_to_hex(&parent->object.oid));
1629 ptree_oid = get_commit_tree_oid(parent);
1630 } else {
1631 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1634 return oideq(ptree_oid, get_commit_tree_oid(commit));
1638 * Should empty commits be allowed? Return status:
1639 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1640 * 0: Halt on empty commit
1641 * 1: Allow empty commit
1642 * 2: Drop empty commit
1644 static int allow_empty(struct repository *r,
1645 struct replay_opts *opts,
1646 struct commit *commit)
1648 int index_unchanged, originally_empty;
1651 * Four cases:
1653 * (1) we do not allow empty at all and error out.
1655 * (2) we allow ones that were initially empty, and
1656 * just drop the ones that become empty
1658 * (3) we allow ones that were initially empty, but
1659 * halt for the ones that become empty;
1661 * (4) we allow both.
1663 if (!opts->allow_empty)
1664 return 0; /* let "git commit" barf as necessary */
1666 index_unchanged = is_index_unchanged(r);
1667 if (index_unchanged < 0)
1668 return index_unchanged;
1669 if (!index_unchanged)
1670 return 0; /* we do not have to say --allow-empty */
1672 if (opts->keep_redundant_commits)
1673 return 1;
1675 originally_empty = is_original_commit_empty(commit);
1676 if (originally_empty < 0)
1677 return originally_empty;
1678 if (originally_empty)
1679 return 1;
1680 else if (opts->drop_redundant_commits)
1681 return 2;
1682 else
1683 return 0;
1686 static struct {
1687 char c;
1688 const char *str;
1689 } todo_command_info[] = {
1690 { 'p', "pick" },
1691 { 0, "revert" },
1692 { 'e', "edit" },
1693 { 'r', "reword" },
1694 { 'f', "fixup" },
1695 { 's', "squash" },
1696 { 'x', "exec" },
1697 { 'b', "break" },
1698 { 'l', "label" },
1699 { 't', "reset" },
1700 { 'm', "merge" },
1701 { 0, "noop" },
1702 { 'd', "drop" },
1703 { 0, NULL }
1706 static const char *command_to_string(const enum todo_command command)
1708 if (command < TODO_COMMENT)
1709 return todo_command_info[command].str;
1710 die(_("unknown command: %d"), command);
1713 static char command_to_char(const enum todo_command command)
1715 if (command < TODO_COMMENT)
1716 return todo_command_info[command].c;
1717 return comment_line_char;
1720 static int is_noop(const enum todo_command command)
1722 return TODO_NOOP <= command;
1725 static int is_fixup(enum todo_command command)
1727 return command == TODO_FIXUP || command == TODO_SQUASH;
1730 /* Does this command create a (non-merge) commit? */
1731 static int is_pick_or_similar(enum todo_command command)
1733 switch (command) {
1734 case TODO_PICK:
1735 case TODO_REVERT:
1736 case TODO_EDIT:
1737 case TODO_REWORD:
1738 case TODO_FIXUP:
1739 case TODO_SQUASH:
1740 return 1;
1741 default:
1742 return 0;
1746 enum todo_item_flags {
1747 TODO_EDIT_MERGE_MSG = (1 << 0),
1748 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1749 TODO_EDIT_FIXUP_MSG = (1 << 2),
1752 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1753 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1754 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1755 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1756 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1758 static int is_fixup_flag(enum todo_command command, unsigned flag)
1760 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1761 (flag & TODO_EDIT_FIXUP_MSG));
1765 * Wrapper around strbuf_add_commented_lines() which avoids double
1766 * commenting commit subjects.
1768 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1770 const char *s = str;
1771 while (len > 0 && s[0] == comment_line_char) {
1772 size_t count;
1773 const char *n = memchr(s, '\n', len);
1774 if (!n)
1775 count = len;
1776 else
1777 count = n - s + 1;
1778 strbuf_add(buf, s, count);
1779 s += count;
1780 len -= count;
1782 strbuf_add_commented_lines(buf, s, len);
1785 /* Does the current fixup chain contain a squash command? */
1786 static int seen_squash(struct replay_opts *opts)
1788 return starts_with(opts->current_fixups.buf, "squash") ||
1789 strstr(opts->current_fixups.buf, "\nsquash");
1792 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1794 strbuf_setlen(buf1, 2);
1795 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1796 strbuf_addch(buf1, '\n');
1797 strbuf_setlen(buf2, 2);
1798 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1799 strbuf_addch(buf2, '\n');
1803 * Comment out any un-commented commit messages, updating the message comments
1804 * to say they will be skipped but do not comment out the empty lines that
1805 * surround commit messages and their comments.
1807 static void update_squash_message_for_fixup(struct strbuf *msg)
1809 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1810 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1811 const char *s, *start;
1812 char *orig_msg;
1813 size_t orig_msg_len;
1814 int i = 1;
1816 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1817 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1818 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1819 while (s) {
1820 const char *next;
1821 size_t off;
1822 if (skip_prefix(s, buf1.buf, &next)) {
1824 * Copy the last message, preserving the blank line
1825 * preceding the current line
1827 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1828 copy_lines(msg, start, s - start - off);
1829 if (off)
1830 strbuf_addch(msg, '\n');
1832 * The next message needs to be commented out but the
1833 * message header is already commented out so just copy
1834 * it and the blank line that follows it.
1836 strbuf_addbuf(msg, &buf2);
1837 if (*next == '\n')
1838 strbuf_addch(msg, *next++);
1839 start = s = next;
1840 copy_lines = add_commented_lines;
1841 update_comment_bufs(&buf1, &buf2, ++i);
1842 } else if (skip_prefix(s, buf2.buf, &next)) {
1843 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1844 copy_lines(msg, start, s - start - off);
1845 start = s - off;
1846 s = next;
1847 copy_lines = strbuf_add;
1848 update_comment_bufs(&buf1, &buf2, ++i);
1849 } else {
1850 s = strchr(s, '\n');
1851 if (s)
1852 s++;
1855 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1856 free(orig_msg);
1857 strbuf_release(&buf1);
1858 strbuf_release(&buf2);
1861 static int append_squash_message(struct strbuf *buf, const char *body,
1862 enum todo_command command, struct replay_opts *opts,
1863 unsigned flag)
1865 const char *fixup_msg;
1866 size_t commented_len = 0, fixup_off;
1868 * amend is non-interactive and not normally used with fixup!
1869 * or squash! commits, so only comment out those subjects when
1870 * squashing commit messages.
1872 if (starts_with(body, "amend!") ||
1873 ((command == TODO_SQUASH || seen_squash(opts)) &&
1874 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1875 commented_len = commit_subject_length(body);
1877 strbuf_addf(buf, "\n%c ", comment_line_char);
1878 strbuf_addf(buf, _(nth_commit_msg_fmt),
1879 ++opts->current_fixup_count + 1);
1880 strbuf_addstr(buf, "\n\n");
1881 strbuf_add_commented_lines(buf, body, commented_len);
1882 /* buf->buf may be reallocated so store an offset into the buffer */
1883 fixup_off = buf->len;
1884 strbuf_addstr(buf, body + commented_len);
1886 /* fixup -C after squash behaves like squash */
1887 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1889 * We're replacing the commit message so we need to
1890 * append the Signed-off-by: trailer if the user
1891 * requested '--signoff'.
1893 if (opts->signoff)
1894 append_signoff(buf, 0, 0);
1896 if ((command == TODO_FIXUP) &&
1897 (flag & TODO_REPLACE_FIXUP_MSG) &&
1898 (file_exists(rebase_path_fixup_msg()) ||
1899 !file_exists(rebase_path_squash_msg()))) {
1900 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1901 if (write_message(fixup_msg, strlen(fixup_msg),
1902 rebase_path_fixup_msg(), 0) < 0)
1903 return error(_("cannot write '%s'"),
1904 rebase_path_fixup_msg());
1905 } else {
1906 unlink(rebase_path_fixup_msg());
1908 } else {
1909 unlink(rebase_path_fixup_msg());
1912 return 0;
1915 static int update_squash_messages(struct repository *r,
1916 enum todo_command command,
1917 struct commit *commit,
1918 struct replay_opts *opts,
1919 unsigned flag)
1921 struct strbuf buf = STRBUF_INIT;
1922 int res = 0;
1923 const char *message, *body;
1924 const char *encoding = get_commit_output_encoding();
1926 if (opts->current_fixup_count > 0) {
1927 struct strbuf header = STRBUF_INIT;
1928 char *eol;
1930 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1931 return error(_("could not read '%s'"),
1932 rebase_path_squash_msg());
1934 eol = buf.buf[0] != comment_line_char ?
1935 buf.buf : strchrnul(buf.buf, '\n');
1937 strbuf_addf(&header, "%c ", comment_line_char);
1938 strbuf_addf(&header, _(combined_commit_msg_fmt),
1939 opts->current_fixup_count + 2);
1940 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1941 strbuf_release(&header);
1942 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1943 update_squash_message_for_fixup(&buf);
1944 } else {
1945 struct object_id head;
1946 struct commit *head_commit;
1947 const char *head_message, *body;
1949 if (get_oid("HEAD", &head))
1950 return error(_("need a HEAD to fixup"));
1951 if (!(head_commit = lookup_commit_reference(r, &head)))
1952 return error(_("could not read HEAD"));
1953 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1954 return error(_("could not read HEAD's commit message"));
1956 find_commit_subject(head_message, &body);
1957 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1958 rebase_path_fixup_msg(), 0) < 0) {
1959 unuse_commit_buffer(head_commit, head_message);
1960 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1962 strbuf_addf(&buf, "%c ", comment_line_char);
1963 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1964 strbuf_addf(&buf, "\n%c ", comment_line_char);
1965 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1966 _(skip_first_commit_msg_str) :
1967 _(first_commit_msg_str));
1968 strbuf_addstr(&buf, "\n\n");
1969 if (is_fixup_flag(command, flag))
1970 strbuf_add_commented_lines(&buf, body, strlen(body));
1971 else
1972 strbuf_addstr(&buf, body);
1974 unuse_commit_buffer(head_commit, head_message);
1977 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1978 return error(_("could not read commit message of %s"),
1979 oid_to_hex(&commit->object.oid));
1980 find_commit_subject(message, &body);
1982 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1983 res = append_squash_message(&buf, body, command, opts, flag);
1984 } else if (command == TODO_FIXUP) {
1985 strbuf_addf(&buf, "\n%c ", comment_line_char);
1986 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1987 ++opts->current_fixup_count + 1);
1988 strbuf_addstr(&buf, "\n\n");
1989 strbuf_add_commented_lines(&buf, body, strlen(body));
1990 } else
1991 return error(_("unknown command: %d"), command);
1992 unuse_commit_buffer(commit, message);
1994 if (!res)
1995 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1997 strbuf_release(&buf);
1999 if (!res) {
2000 strbuf_addf(&opts->current_fixups, "%s%s %s",
2001 opts->current_fixups.len ? "\n" : "",
2002 command_to_string(command),
2003 oid_to_hex(&commit->object.oid));
2004 res = write_message(opts->current_fixups.buf,
2005 opts->current_fixups.len,
2006 rebase_path_current_fixups(), 0);
2009 return res;
2012 static void flush_rewritten_pending(void)
2014 struct strbuf buf = STRBUF_INIT;
2015 struct object_id newoid;
2016 FILE *out;
2018 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2019 !get_oid("HEAD", &newoid) &&
2020 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2021 char *bol = buf.buf, *eol;
2023 while (*bol) {
2024 eol = strchrnul(bol, '\n');
2025 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2026 bol, oid_to_hex(&newoid));
2027 if (!*eol)
2028 break;
2029 bol = eol + 1;
2031 fclose(out);
2032 unlink(rebase_path_rewritten_pending());
2034 strbuf_release(&buf);
2037 static void record_in_rewritten(struct object_id *oid,
2038 enum todo_command next_command)
2040 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2042 if (!out)
2043 return;
2045 fprintf(out, "%s\n", oid_to_hex(oid));
2046 fclose(out);
2048 if (!is_fixup(next_command))
2049 flush_rewritten_pending();
2052 static int should_edit(struct replay_opts *opts) {
2053 if (opts->edit < 0)
2055 * Note that we only handle the case of non-conflicted
2056 * commits; continue_single_pick() handles the conflicted
2057 * commits itself instead of calling this function.
2059 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2060 return opts->edit;
2063 static int do_pick_commit(struct repository *r,
2064 struct todo_item *item,
2065 struct replay_opts *opts,
2066 int final_fixup, int *check_todo)
2068 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2069 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2070 struct object_id head;
2071 struct commit *base, *next, *parent;
2072 const char *base_label, *next_label;
2073 char *author = NULL;
2074 struct commit_message msg = { NULL, NULL, NULL, NULL };
2075 struct strbuf msgbuf = STRBUF_INIT;
2076 int res, unborn = 0, reword = 0, allow, drop_commit;
2077 enum todo_command command = item->command;
2078 struct commit *commit = item->commit;
2080 if (opts->no_commit) {
2082 * We do not intend to commit immediately. We just want to
2083 * merge the differences in, so let's compute the tree
2084 * that represents the "current" state for the merge machinery
2085 * to work on.
2087 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2088 return error(_("your index file is unmerged."));
2089 } else {
2090 unborn = get_oid("HEAD", &head);
2091 /* Do we want to generate a root commit? */
2092 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2093 oideq(&head, &opts->squash_onto)) {
2094 if (is_fixup(command))
2095 return error(_("cannot fixup root commit"));
2096 flags |= CREATE_ROOT_COMMIT;
2097 unborn = 1;
2098 } else if (unborn)
2099 oidcpy(&head, the_hash_algo->empty_tree);
2100 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2101 NULL, 0))
2102 return error_dirty_index(r, opts);
2104 discard_index(r->index);
2106 if (!commit->parents)
2107 parent = NULL;
2108 else if (commit->parents->next) {
2109 /* Reverting or cherry-picking a merge commit */
2110 int cnt;
2111 struct commit_list *p;
2113 if (!opts->mainline)
2114 return error(_("commit %s is a merge but no -m option was given."),
2115 oid_to_hex(&commit->object.oid));
2117 for (cnt = 1, p = commit->parents;
2118 cnt != opts->mainline && p;
2119 cnt++)
2120 p = p->next;
2121 if (cnt != opts->mainline || !p)
2122 return error(_("commit %s does not have parent %d"),
2123 oid_to_hex(&commit->object.oid), opts->mainline);
2124 parent = p->item;
2125 } else if (1 < opts->mainline)
2127 * Non-first parent explicitly specified as mainline for
2128 * non-merge commit
2130 return error(_("commit %s does not have parent %d"),
2131 oid_to_hex(&commit->object.oid), opts->mainline);
2132 else
2133 parent = commit->parents->item;
2135 if (get_message(commit, &msg) != 0)
2136 return error(_("cannot get commit message for %s"),
2137 oid_to_hex(&commit->object.oid));
2139 if (opts->allow_ff && !is_fixup(command) &&
2140 ((parent && oideq(&parent->object.oid, &head)) ||
2141 (!parent && unborn))) {
2142 if (is_rebase_i(opts))
2143 write_author_script(msg.message);
2144 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2145 opts);
2146 if (res || command != TODO_REWORD)
2147 goto leave;
2148 reword = 1;
2149 msg_file = NULL;
2150 goto fast_forward_edit;
2152 if (parent && parse_commit(parent) < 0)
2153 /* TRANSLATORS: The first %s will be a "todo" command like
2154 "revert" or "pick", the second %s a SHA1. */
2155 return error(_("%s: cannot parse parent commit %s"),
2156 command_to_string(command),
2157 oid_to_hex(&parent->object.oid));
2160 * "commit" is an existing commit. We would want to apply
2161 * the difference it introduces since its first parent "prev"
2162 * on top of the current HEAD if we are cherry-pick. Or the
2163 * reverse of it if we are revert.
2166 if (command == TODO_REVERT) {
2167 base = commit;
2168 base_label = msg.label;
2169 next = parent;
2170 next_label = msg.parent_label;
2171 strbuf_addstr(&msgbuf, "Revert \"");
2172 strbuf_addstr(&msgbuf, msg.subject);
2173 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2174 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2176 if (commit->parents && commit->parents->next) {
2177 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2178 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2180 strbuf_addstr(&msgbuf, ".\n");
2181 } else {
2182 const char *p;
2184 base = parent;
2185 base_label = msg.parent_label;
2186 next = commit;
2187 next_label = msg.label;
2189 /* Append the commit log message to msgbuf. */
2190 if (find_commit_subject(msg.message, &p))
2191 strbuf_addstr(&msgbuf, p);
2193 if (opts->record_origin) {
2194 strbuf_complete_line(&msgbuf);
2195 if (!has_conforming_footer(&msgbuf, NULL, 0))
2196 strbuf_addch(&msgbuf, '\n');
2197 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2198 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2199 strbuf_addstr(&msgbuf, ")\n");
2201 if (!is_fixup(command))
2202 author = get_author(msg.message);
2205 if (command == TODO_REWORD)
2206 reword = 1;
2207 else if (is_fixup(command)) {
2208 if (update_squash_messages(r, command, commit,
2209 opts, item->flags))
2210 return -1;
2211 flags |= AMEND_MSG;
2212 if (!final_fixup)
2213 msg_file = rebase_path_squash_msg();
2214 else if (file_exists(rebase_path_fixup_msg())) {
2215 flags |= VERBATIM_MSG;
2216 msg_file = rebase_path_fixup_msg();
2217 } else {
2218 const char *dest = git_path_squash_msg(r);
2219 unlink(dest);
2220 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2221 return error(_("could not rename '%s' to '%s'"),
2222 rebase_path_squash_msg(), dest);
2223 unlink(git_path_merge_msg(r));
2224 msg_file = dest;
2225 flags |= EDIT_MSG;
2229 if (opts->signoff && !is_fixup(command))
2230 append_signoff(&msgbuf, 0, 0);
2232 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2233 res = -1;
2234 else if (!opts->strategy ||
2235 !strcmp(opts->strategy, "recursive") ||
2236 !strcmp(opts->strategy, "ort") ||
2237 command == TODO_REVERT) {
2238 res = do_recursive_merge(r, base, next, base_label, next_label,
2239 &head, &msgbuf, opts);
2240 if (res < 0)
2241 goto leave;
2243 res |= write_message(msgbuf.buf, msgbuf.len,
2244 git_path_merge_msg(r), 0);
2245 } else {
2246 struct commit_list *common = NULL;
2247 struct commit_list *remotes = NULL;
2249 res = write_message(msgbuf.buf, msgbuf.len,
2250 git_path_merge_msg(r), 0);
2252 commit_list_insert(base, &common);
2253 commit_list_insert(next, &remotes);
2254 res |= try_merge_command(r, opts->strategy,
2255 opts->xopts_nr, (const char **)opts->xopts,
2256 common, oid_to_hex(&head), remotes);
2257 free_commit_list(common);
2258 free_commit_list(remotes);
2260 strbuf_release(&msgbuf);
2263 * If the merge was clean or if it failed due to conflict, we write
2264 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2265 * However, if the merge did not even start, then we don't want to
2266 * write it at all.
2268 if ((command == TODO_PICK || command == TODO_REWORD ||
2269 command == TODO_EDIT) && !opts->no_commit &&
2270 (res == 0 || res == 1) &&
2271 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2272 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2273 res = -1;
2274 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2275 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2276 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2277 res = -1;
2279 if (res) {
2280 error(command == TODO_REVERT
2281 ? _("could not revert %s... %s")
2282 : _("could not apply %s... %s"),
2283 short_commit_name(commit), msg.subject);
2284 print_advice(r, res == 1, opts);
2285 repo_rerere(r, opts->allow_rerere_auto);
2286 goto leave;
2289 drop_commit = 0;
2290 allow = allow_empty(r, opts, commit);
2291 if (allow < 0) {
2292 res = allow;
2293 goto leave;
2294 } else if (allow == 1) {
2295 flags |= ALLOW_EMPTY;
2296 } else if (allow == 2) {
2297 drop_commit = 1;
2298 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2299 NULL, 0);
2300 unlink(git_path_merge_msg(r));
2301 unlink(git_path_auto_merge(r));
2302 fprintf(stderr,
2303 _("dropping %s %s -- patch contents already upstream\n"),
2304 oid_to_hex(&commit->object.oid), msg.subject);
2305 } /* else allow == 0 and there's nothing special to do */
2306 if (!opts->no_commit && !drop_commit) {
2307 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2308 res = do_commit(r, msg_file, author, opts, flags,
2309 commit? &commit->object.oid : NULL);
2310 else
2311 res = error(_("unable to parse commit author"));
2312 *check_todo = !!(flags & EDIT_MSG);
2313 if (!res && reword) {
2314 fast_forward_edit:
2315 res = run_git_commit(NULL, opts, EDIT_MSG |
2316 VERIFY_MSG | AMEND_MSG |
2317 (flags & ALLOW_EMPTY));
2318 *check_todo = 1;
2323 if (!res && final_fixup) {
2324 unlink(rebase_path_fixup_msg());
2325 unlink(rebase_path_squash_msg());
2326 unlink(rebase_path_current_fixups());
2327 strbuf_reset(&opts->current_fixups);
2328 opts->current_fixup_count = 0;
2331 leave:
2332 free_message(commit, &msg);
2333 free(author);
2334 update_abort_safety_file();
2336 return res;
2339 static int prepare_revs(struct replay_opts *opts)
2342 * picking (but not reverting) ranges (but not individual revisions)
2343 * should be done in reverse
2345 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2346 opts->revs->reverse ^= 1;
2348 if (prepare_revision_walk(opts->revs))
2349 return error(_("revision walk setup failed"));
2351 return 0;
2354 static int read_and_refresh_cache(struct repository *r,
2355 struct replay_opts *opts)
2357 struct lock_file index_lock = LOCK_INIT;
2358 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2359 if (repo_read_index(r) < 0) {
2360 rollback_lock_file(&index_lock);
2361 return error(_("git %s: failed to read the index"),
2362 _(action_name(opts)));
2364 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2366 if (index_fd >= 0) {
2367 if (write_locked_index(r->index, &index_lock,
2368 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2369 return error(_("git %s: failed to refresh the index"),
2370 _(action_name(opts)));
2375 * If we are resolving merges in any way other than "ort", then
2376 * expand the sparse index.
2378 if (opts->strategy && strcmp(opts->strategy, "ort"))
2379 ensure_full_index(r->index);
2380 return 0;
2383 void todo_list_release(struct todo_list *todo_list)
2385 strbuf_release(&todo_list->buf);
2386 FREE_AND_NULL(todo_list->items);
2387 todo_list->nr = todo_list->alloc = 0;
2390 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2392 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2393 todo_list->total_nr++;
2394 return todo_list->items + todo_list->nr++;
2397 const char *todo_item_get_arg(struct todo_list *todo_list,
2398 struct todo_item *item)
2400 return todo_list->buf.buf + item->arg_offset;
2403 static int is_command(enum todo_command command, const char **bol)
2405 const char *str = todo_command_info[command].str;
2406 const char nick = todo_command_info[command].c;
2407 const char *p = *bol + 1;
2409 return skip_prefix(*bol, str, bol) ||
2410 ((nick && **bol == nick) &&
2411 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2412 (*bol = p));
2415 static int parse_insn_line(struct repository *r, struct todo_item *item,
2416 const char *buf, const char *bol, char *eol)
2418 struct object_id commit_oid;
2419 char *end_of_object_name;
2420 int i, saved, status, padding;
2422 item->flags = 0;
2424 /* left-trim */
2425 bol += strspn(bol, " \t");
2427 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2428 item->command = TODO_COMMENT;
2429 item->commit = NULL;
2430 item->arg_offset = bol - buf;
2431 item->arg_len = eol - bol;
2432 return 0;
2435 for (i = 0; i < TODO_COMMENT; i++)
2436 if (is_command(i, &bol)) {
2437 item->command = i;
2438 break;
2440 if (i >= TODO_COMMENT)
2441 return -1;
2443 /* Eat up extra spaces/ tabs before object name */
2444 padding = strspn(bol, " \t");
2445 bol += padding;
2447 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2448 if (bol != eol)
2449 return error(_("%s does not accept arguments: '%s'"),
2450 command_to_string(item->command), bol);
2451 item->commit = NULL;
2452 item->arg_offset = bol - buf;
2453 item->arg_len = eol - bol;
2454 return 0;
2457 if (!padding)
2458 return error(_("missing arguments for %s"),
2459 command_to_string(item->command));
2461 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2462 item->command == TODO_RESET) {
2463 item->commit = NULL;
2464 item->arg_offset = bol - buf;
2465 item->arg_len = (int)(eol - bol);
2466 return 0;
2469 if (item->command == TODO_FIXUP) {
2470 if (skip_prefix(bol, "-C", &bol) &&
2471 (*bol == ' ' || *bol == '\t')) {
2472 bol += strspn(bol, " \t");
2473 item->flags |= TODO_REPLACE_FIXUP_MSG;
2474 } else if (skip_prefix(bol, "-c", &bol) &&
2475 (*bol == ' ' || *bol == '\t')) {
2476 bol += strspn(bol, " \t");
2477 item->flags |= TODO_EDIT_FIXUP_MSG;
2481 if (item->command == TODO_MERGE) {
2482 if (skip_prefix(bol, "-C", &bol))
2483 bol += strspn(bol, " \t");
2484 else if (skip_prefix(bol, "-c", &bol)) {
2485 bol += strspn(bol, " \t");
2486 item->flags |= TODO_EDIT_MERGE_MSG;
2487 } else {
2488 item->flags |= TODO_EDIT_MERGE_MSG;
2489 item->commit = NULL;
2490 item->arg_offset = bol - buf;
2491 item->arg_len = (int)(eol - bol);
2492 return 0;
2496 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2497 saved = *end_of_object_name;
2498 *end_of_object_name = '\0';
2499 status = get_oid(bol, &commit_oid);
2500 if (status < 0)
2501 error(_("could not parse '%s'"), bol); /* return later */
2502 *end_of_object_name = saved;
2504 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2505 item->arg_offset = bol - buf;
2506 item->arg_len = (int)(eol - bol);
2508 if (status < 0)
2509 return status;
2511 item->commit = lookup_commit_reference(r, &commit_oid);
2512 return item->commit ? 0 : -1;
2515 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2517 const char *todo_file, *bol;
2518 struct strbuf buf = STRBUF_INIT;
2519 int ret = 0;
2521 todo_file = git_path_todo_file();
2522 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2523 if (errno == ENOENT || errno == ENOTDIR)
2524 return -1;
2525 else
2526 return error_errno("unable to open '%s'", todo_file);
2528 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2529 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2530 *action = REPLAY_PICK;
2531 else if (is_command(TODO_REVERT, &bol) &&
2532 (*bol == ' ' || *bol == '\t'))
2533 *action = REPLAY_REVERT;
2534 else
2535 ret = -1;
2537 strbuf_release(&buf);
2539 return ret;
2542 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2543 struct todo_list *todo_list)
2545 struct todo_item *item;
2546 char *p = buf, *next_p;
2547 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2549 todo_list->current = todo_list->nr = 0;
2551 for (i = 1; *p; i++, p = next_p) {
2552 char *eol = strchrnul(p, '\n');
2554 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2556 if (p != eol && eol[-1] == '\r')
2557 eol--; /* strip Carriage Return */
2559 item = append_new_todo(todo_list);
2560 item->offset_in_buf = p - todo_list->buf.buf;
2561 if (parse_insn_line(r, item, buf, p, eol)) {
2562 res = error(_("invalid line %d: %.*s"),
2563 i, (int)(eol - p), p);
2564 item->command = TODO_COMMENT + 1;
2565 item->arg_offset = p - buf;
2566 item->arg_len = (int)(eol - p);
2567 item->commit = NULL;
2570 if (fixup_okay)
2571 ; /* do nothing */
2572 else if (is_fixup(item->command))
2573 return error(_("cannot '%s' without a previous commit"),
2574 command_to_string(item->command));
2575 else if (!is_noop(item->command))
2576 fixup_okay = 1;
2579 return res;
2582 static int count_commands(struct todo_list *todo_list)
2584 int count = 0, i;
2586 for (i = 0; i < todo_list->nr; i++)
2587 if (todo_list->items[i].command != TODO_COMMENT)
2588 count++;
2590 return count;
2593 static int get_item_line_offset(struct todo_list *todo_list, int index)
2595 return index < todo_list->nr ?
2596 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2599 static const char *get_item_line(struct todo_list *todo_list, int index)
2601 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2604 static int get_item_line_length(struct todo_list *todo_list, int index)
2606 return get_item_line_offset(todo_list, index + 1)
2607 - get_item_line_offset(todo_list, index);
2610 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2612 int fd;
2613 ssize_t len;
2615 fd = open(path, O_RDONLY);
2616 if (fd < 0)
2617 return error_errno(_("could not open '%s'"), path);
2618 len = strbuf_read(sb, fd, 0);
2619 close(fd);
2620 if (len < 0)
2621 return error(_("could not read '%s'."), path);
2622 return len;
2625 static int have_finished_the_last_pick(void)
2627 struct strbuf buf = STRBUF_INIT;
2628 const char *eol;
2629 const char *todo_path = git_path_todo_file();
2630 int ret = 0;
2632 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2633 if (errno == ENOENT) {
2634 return 0;
2635 } else {
2636 error_errno("unable to open '%s'", todo_path);
2637 return 0;
2640 /* If there is only one line then we are done */
2641 eol = strchr(buf.buf, '\n');
2642 if (!eol || !eol[1])
2643 ret = 1;
2645 strbuf_release(&buf);
2647 return ret;
2650 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2652 struct replay_opts opts = REPLAY_OPTS_INIT;
2653 int need_cleanup = 0;
2655 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2656 if (!refs_delete_ref(get_main_ref_store(r), "",
2657 "CHERRY_PICK_HEAD", NULL, 0) &&
2658 verbose)
2659 warning(_("cancelling a cherry picking in progress"));
2660 opts.action = REPLAY_PICK;
2661 need_cleanup = 1;
2664 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2665 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2666 NULL, 0) &&
2667 verbose)
2668 warning(_("cancelling a revert in progress"));
2669 opts.action = REPLAY_REVERT;
2670 need_cleanup = 1;
2673 unlink(git_path_auto_merge(r));
2675 if (!need_cleanup)
2676 return;
2678 if (!have_finished_the_last_pick())
2679 return;
2681 sequencer_remove_state(&opts);
2684 static void todo_list_write_total_nr(struct todo_list *todo_list)
2686 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2688 if (f) {
2689 fprintf(f, "%d\n", todo_list->total_nr);
2690 fclose(f);
2694 static int read_populate_todo(struct repository *r,
2695 struct todo_list *todo_list,
2696 struct replay_opts *opts)
2698 const char *todo_file = get_todo_path(opts);
2699 int res;
2701 strbuf_reset(&todo_list->buf);
2702 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2703 return -1;
2705 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2706 if (res) {
2707 if (is_rebase_i(opts))
2708 return error(_("please fix this using "
2709 "'git rebase --edit-todo'."));
2710 return error(_("unusable instruction sheet: '%s'"), todo_file);
2713 if (!todo_list->nr &&
2714 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2715 return error(_("no commits parsed."));
2717 if (!is_rebase_i(opts)) {
2718 enum todo_command valid =
2719 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2720 int i;
2722 for (i = 0; i < todo_list->nr; i++)
2723 if (valid == todo_list->items[i].command)
2724 continue;
2725 else if (valid == TODO_PICK)
2726 return error(_("cannot cherry-pick during a revert."));
2727 else
2728 return error(_("cannot revert during a cherry-pick."));
2731 if (is_rebase_i(opts)) {
2732 struct todo_list done = TODO_LIST_INIT;
2734 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2735 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2736 todo_list->done_nr = count_commands(&done);
2737 else
2738 todo_list->done_nr = 0;
2740 todo_list->total_nr = todo_list->done_nr
2741 + count_commands(todo_list);
2742 todo_list_release(&done);
2744 todo_list_write_total_nr(todo_list);
2747 return 0;
2750 static int git_config_string_dup(char **dest,
2751 const char *var, const char *value)
2753 if (!value)
2754 return config_error_nonbool(var);
2755 free(*dest);
2756 *dest = xstrdup(value);
2757 return 0;
2760 static int populate_opts_cb(const char *key, const char *value, void *data)
2762 struct replay_opts *opts = data;
2763 int error_flag = 1;
2765 if (!value)
2766 error_flag = 0;
2767 else if (!strcmp(key, "options.no-commit"))
2768 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2769 else if (!strcmp(key, "options.edit"))
2770 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2771 else if (!strcmp(key, "options.allow-empty"))
2772 opts->allow_empty =
2773 git_config_bool_or_int(key, value, &error_flag);
2774 else if (!strcmp(key, "options.allow-empty-message"))
2775 opts->allow_empty_message =
2776 git_config_bool_or_int(key, value, &error_flag);
2777 else if (!strcmp(key, "options.keep-redundant-commits"))
2778 opts->keep_redundant_commits =
2779 git_config_bool_or_int(key, value, &error_flag);
2780 else if (!strcmp(key, "options.signoff"))
2781 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2782 else if (!strcmp(key, "options.record-origin"))
2783 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2784 else if (!strcmp(key, "options.allow-ff"))
2785 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2786 else if (!strcmp(key, "options.mainline"))
2787 opts->mainline = git_config_int(key, value);
2788 else if (!strcmp(key, "options.strategy"))
2789 git_config_string_dup(&opts->strategy, key, value);
2790 else if (!strcmp(key, "options.gpg-sign"))
2791 git_config_string_dup(&opts->gpg_sign, key, value);
2792 else if (!strcmp(key, "options.strategy-option")) {
2793 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2794 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2795 } else if (!strcmp(key, "options.allow-rerere-auto"))
2796 opts->allow_rerere_auto =
2797 git_config_bool_or_int(key, value, &error_flag) ?
2798 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2799 else if (!strcmp(key, "options.default-msg-cleanup")) {
2800 opts->explicit_cleanup = 1;
2801 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2802 } else
2803 return error(_("invalid key: %s"), key);
2805 if (!error_flag)
2806 return error(_("invalid value for '%s': '%s'"), key, value);
2808 return 0;
2811 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2813 int i;
2814 char *strategy_opts_string = raw_opts;
2816 if (*strategy_opts_string == ' ')
2817 strategy_opts_string++;
2819 opts->xopts_nr = split_cmdline(strategy_opts_string,
2820 (const char ***)&opts->xopts);
2821 for (i = 0; i < opts->xopts_nr; i++) {
2822 const char *arg = opts->xopts[i];
2824 skip_prefix(arg, "--", &arg);
2825 opts->xopts[i] = xstrdup(arg);
2829 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2831 strbuf_reset(buf);
2832 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2833 return;
2834 opts->strategy = strbuf_detach(buf, NULL);
2835 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2836 return;
2838 parse_strategy_opts(opts, buf->buf);
2841 static int read_populate_opts(struct replay_opts *opts)
2843 if (is_rebase_i(opts)) {
2844 struct strbuf buf = STRBUF_INIT;
2845 int ret = 0;
2847 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2848 READ_ONELINER_SKIP_IF_EMPTY)) {
2849 if (!starts_with(buf.buf, "-S"))
2850 strbuf_reset(&buf);
2851 else {
2852 free(opts->gpg_sign);
2853 opts->gpg_sign = xstrdup(buf.buf + 2);
2855 strbuf_reset(&buf);
2858 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2859 READ_ONELINER_SKIP_IF_EMPTY)) {
2860 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2861 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2862 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2863 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2864 strbuf_reset(&buf);
2867 if (file_exists(rebase_path_verbose()))
2868 opts->verbose = 1;
2870 if (file_exists(rebase_path_quiet()))
2871 opts->quiet = 1;
2873 if (file_exists(rebase_path_signoff())) {
2874 opts->allow_ff = 0;
2875 opts->signoff = 1;
2878 if (file_exists(rebase_path_cdate_is_adate())) {
2879 opts->allow_ff = 0;
2880 opts->committer_date_is_author_date = 1;
2883 if (file_exists(rebase_path_ignore_date())) {
2884 opts->allow_ff = 0;
2885 opts->ignore_date = 1;
2888 if (file_exists(rebase_path_reschedule_failed_exec()))
2889 opts->reschedule_failed_exec = 1;
2890 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2891 opts->reschedule_failed_exec = 0;
2893 if (file_exists(rebase_path_drop_redundant_commits()))
2894 opts->drop_redundant_commits = 1;
2896 if (file_exists(rebase_path_keep_redundant_commits()))
2897 opts->keep_redundant_commits = 1;
2899 read_strategy_opts(opts, &buf);
2900 strbuf_reset(&buf);
2902 if (read_oneliner(&opts->current_fixups,
2903 rebase_path_current_fixups(),
2904 READ_ONELINER_SKIP_IF_EMPTY)) {
2905 const char *p = opts->current_fixups.buf;
2906 opts->current_fixup_count = 1;
2907 while ((p = strchr(p, '\n'))) {
2908 opts->current_fixup_count++;
2909 p++;
2913 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2914 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2915 ret = error(_("unusable squash-onto"));
2916 goto done_rebase_i;
2918 opts->have_squash_onto = 1;
2921 done_rebase_i:
2922 strbuf_release(&buf);
2923 return ret;
2926 if (!file_exists(git_path_opts_file()))
2927 return 0;
2929 * The function git_parse_source(), called from git_config_from_file(),
2930 * may die() in case of a syntactically incorrect file. We do not care
2931 * about this case, though, because we wrote that file ourselves, so we
2932 * are pretty certain that it is syntactically correct.
2934 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2935 return error(_("malformed options sheet: '%s'"),
2936 git_path_opts_file());
2937 return 0;
2940 static void write_strategy_opts(struct replay_opts *opts)
2942 int i;
2943 struct strbuf buf = STRBUF_INIT;
2945 for (i = 0; i < opts->xopts_nr; ++i)
2946 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2948 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2949 strbuf_release(&buf);
2952 int write_basic_state(struct replay_opts *opts, const char *head_name,
2953 struct commit *onto, const struct object_id *orig_head)
2955 if (head_name)
2956 write_file(rebase_path_head_name(), "%s\n", head_name);
2957 if (onto)
2958 write_file(rebase_path_onto(), "%s\n",
2959 oid_to_hex(&onto->object.oid));
2960 if (orig_head)
2961 write_file(rebase_path_orig_head(), "%s\n",
2962 oid_to_hex(orig_head));
2964 if (opts->quiet)
2965 write_file(rebase_path_quiet(), "%s", "");
2966 if (opts->verbose)
2967 write_file(rebase_path_verbose(), "%s", "");
2968 if (opts->strategy)
2969 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2970 if (opts->xopts_nr > 0)
2971 write_strategy_opts(opts);
2973 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2974 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2975 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2976 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2978 if (opts->gpg_sign)
2979 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2980 if (opts->signoff)
2981 write_file(rebase_path_signoff(), "--signoff\n");
2982 if (opts->drop_redundant_commits)
2983 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2984 if (opts->keep_redundant_commits)
2985 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2986 if (opts->committer_date_is_author_date)
2987 write_file(rebase_path_cdate_is_adate(), "%s", "");
2988 if (opts->ignore_date)
2989 write_file(rebase_path_ignore_date(), "%s", "");
2990 if (opts->reschedule_failed_exec)
2991 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2992 else
2993 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2995 return 0;
2998 static int walk_revs_populate_todo(struct todo_list *todo_list,
2999 struct replay_opts *opts)
3001 enum todo_command command = opts->action == REPLAY_PICK ?
3002 TODO_PICK : TODO_REVERT;
3003 const char *command_string = todo_command_info[command].str;
3004 const char *encoding;
3005 struct commit *commit;
3007 if (prepare_revs(opts))
3008 return -1;
3010 encoding = get_log_output_encoding();
3012 while ((commit = get_revision(opts->revs))) {
3013 struct todo_item *item = append_new_todo(todo_list);
3014 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3015 const char *subject;
3016 int subject_len;
3018 item->command = command;
3019 item->commit = commit;
3020 item->arg_offset = 0;
3021 item->arg_len = 0;
3022 item->offset_in_buf = todo_list->buf.len;
3023 subject_len = find_commit_subject(commit_buffer, &subject);
3024 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3025 short_commit_name(commit), subject_len, subject);
3026 unuse_commit_buffer(commit, commit_buffer);
3029 if (!todo_list->nr)
3030 return error(_("empty commit set passed"));
3032 return 0;
3035 static int create_seq_dir(struct repository *r)
3037 enum replay_action action;
3038 const char *in_progress_error = NULL;
3039 const char *in_progress_advice = NULL;
3040 unsigned int advise_skip =
3041 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3042 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3044 if (!sequencer_get_last_command(r, &action)) {
3045 switch (action) {
3046 case REPLAY_REVERT:
3047 in_progress_error = _("revert is already in progress");
3048 in_progress_advice =
3049 _("try \"git revert (--continue | %s--abort | --quit)\"");
3050 break;
3051 case REPLAY_PICK:
3052 in_progress_error = _("cherry-pick is already in progress");
3053 in_progress_advice =
3054 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3055 break;
3056 default:
3057 BUG("unexpected action in create_seq_dir");
3060 if (in_progress_error) {
3061 error("%s", in_progress_error);
3062 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3063 advise(in_progress_advice,
3064 advise_skip ? "--skip | " : "");
3065 return -1;
3067 if (mkdir(git_path_seq_dir(), 0777) < 0)
3068 return error_errno(_("could not create sequencer directory '%s'"),
3069 git_path_seq_dir());
3071 return 0;
3074 static int save_head(const char *head)
3076 struct lock_file head_lock = LOCK_INIT;
3077 struct strbuf buf = STRBUF_INIT;
3078 int fd;
3079 ssize_t written;
3081 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3082 if (fd < 0)
3083 return error_errno(_("could not lock HEAD"));
3084 strbuf_addf(&buf, "%s\n", head);
3085 written = write_in_full(fd, buf.buf, buf.len);
3086 strbuf_release(&buf);
3087 if (written < 0) {
3088 error_errno(_("could not write to '%s'"), git_path_head_file());
3089 rollback_lock_file(&head_lock);
3090 return -1;
3092 if (commit_lock_file(&head_lock) < 0)
3093 return error(_("failed to finalize '%s'"), git_path_head_file());
3094 return 0;
3097 static int rollback_is_safe(void)
3099 struct strbuf sb = STRBUF_INIT;
3100 struct object_id expected_head, actual_head;
3102 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3103 strbuf_trim(&sb);
3104 if (get_oid_hex(sb.buf, &expected_head)) {
3105 strbuf_release(&sb);
3106 die(_("could not parse %s"), git_path_abort_safety_file());
3108 strbuf_release(&sb);
3110 else if (errno == ENOENT)
3111 oidclr(&expected_head);
3112 else
3113 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3115 if (get_oid("HEAD", &actual_head))
3116 oidclr(&actual_head);
3118 return oideq(&actual_head, &expected_head);
3121 static int reset_merge(const struct object_id *oid)
3123 int ret;
3124 struct strvec argv = STRVEC_INIT;
3126 strvec_pushl(&argv, "reset", "--merge", NULL);
3128 if (!is_null_oid(oid))
3129 strvec_push(&argv, oid_to_hex(oid));
3131 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3132 strvec_clear(&argv);
3134 return ret;
3137 static int rollback_single_pick(struct repository *r)
3139 struct object_id head_oid;
3141 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3142 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3143 return error(_("no cherry-pick or revert in progress"));
3144 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3145 return error(_("cannot resolve HEAD"));
3146 if (is_null_oid(&head_oid))
3147 return error(_("cannot abort from a branch yet to be born"));
3148 return reset_merge(&head_oid);
3151 static int skip_single_pick(void)
3153 struct object_id head;
3155 if (read_ref_full("HEAD", 0, &head, NULL))
3156 return error(_("cannot resolve HEAD"));
3157 return reset_merge(&head);
3160 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3162 FILE *f;
3163 struct object_id oid;
3164 struct strbuf buf = STRBUF_INIT;
3165 const char *p;
3167 f = fopen(git_path_head_file(), "r");
3168 if (!f && errno == ENOENT) {
3170 * There is no multiple-cherry-pick in progress.
3171 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3172 * a single-cherry-pick in progress, abort that.
3174 return rollback_single_pick(r);
3176 if (!f)
3177 return error_errno(_("cannot open '%s'"), git_path_head_file());
3178 if (strbuf_getline_lf(&buf, f)) {
3179 error(_("cannot read '%s': %s"), git_path_head_file(),
3180 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3181 fclose(f);
3182 goto fail;
3184 fclose(f);
3185 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3186 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3187 git_path_head_file());
3188 goto fail;
3190 if (is_null_oid(&oid)) {
3191 error(_("cannot abort from a branch yet to be born"));
3192 goto fail;
3195 if (!rollback_is_safe()) {
3196 /* Do not error, just do not rollback */
3197 warning(_("You seem to have moved HEAD. "
3198 "Not rewinding, check your HEAD!"));
3199 } else
3200 if (reset_merge(&oid))
3201 goto fail;
3202 strbuf_release(&buf);
3203 return sequencer_remove_state(opts);
3204 fail:
3205 strbuf_release(&buf);
3206 return -1;
3209 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3211 enum replay_action action = -1;
3212 sequencer_get_last_command(r, &action);
3215 * Check whether the subcommand requested to skip the commit is actually
3216 * in progress and that it's safe to skip the commit.
3218 * opts->action tells us which subcommand requested to skip the commit.
3219 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3220 * action is in progress and we can skip the commit.
3222 * Otherwise we check that the last instruction was related to the
3223 * particular subcommand we're trying to execute and barf if that's not
3224 * the case.
3226 * Finally we check that the rollback is "safe", i.e., has the HEAD
3227 * moved? In this case, it doesn't make sense to "reset the merge" and
3228 * "skip the commit" as the user already handled this by committing. But
3229 * we'd not want to barf here, instead give advice on how to proceed. We
3230 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3231 * it gets removed when the user commits, so if it still exists we're
3232 * sure the user can't have committed before.
3234 switch (opts->action) {
3235 case REPLAY_REVERT:
3236 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3237 if (action != REPLAY_REVERT)
3238 return error(_("no revert in progress"));
3239 if (!rollback_is_safe())
3240 goto give_advice;
3242 break;
3243 case REPLAY_PICK:
3244 if (!refs_ref_exists(get_main_ref_store(r),
3245 "CHERRY_PICK_HEAD")) {
3246 if (action != REPLAY_PICK)
3247 return error(_("no cherry-pick in progress"));
3248 if (!rollback_is_safe())
3249 goto give_advice;
3251 break;
3252 default:
3253 BUG("unexpected action in sequencer_skip");
3256 if (skip_single_pick())
3257 return error(_("failed to skip the commit"));
3258 if (!is_directory(git_path_seq_dir()))
3259 return 0;
3261 return sequencer_continue(r, opts);
3263 give_advice:
3264 error(_("there is nothing to skip"));
3266 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3267 advise(_("have you committed already?\n"
3268 "try \"git %s --continue\""),
3269 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3271 return -1;
3274 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3276 struct lock_file todo_lock = LOCK_INIT;
3277 const char *todo_path = get_todo_path(opts);
3278 int next = todo_list->current, offset, fd;
3281 * rebase -i writes "git-rebase-todo" without the currently executing
3282 * command, appending it to "done" instead.
3284 if (is_rebase_i(opts))
3285 next++;
3287 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3288 if (fd < 0)
3289 return error_errno(_("could not lock '%s'"), todo_path);
3290 offset = get_item_line_offset(todo_list, next);
3291 if (write_in_full(fd, todo_list->buf.buf + offset,
3292 todo_list->buf.len - offset) < 0)
3293 return error_errno(_("could not write to '%s'"), todo_path);
3294 if (commit_lock_file(&todo_lock) < 0)
3295 return error(_("failed to finalize '%s'"), todo_path);
3297 if (is_rebase_i(opts) && next > 0) {
3298 const char *done = rebase_path_done();
3299 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3300 int ret = 0;
3302 if (fd < 0)
3303 return 0;
3304 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3305 get_item_line_length(todo_list, next - 1))
3306 < 0)
3307 ret = error_errno(_("could not write to '%s'"), done);
3308 if (close(fd) < 0)
3309 ret = error_errno(_("failed to finalize '%s'"), done);
3310 return ret;
3312 return 0;
3315 static int save_opts(struct replay_opts *opts)
3317 const char *opts_file = git_path_opts_file();
3318 int res = 0;
3320 if (opts->no_commit)
3321 res |= git_config_set_in_file_gently(opts_file,
3322 "options.no-commit", "true");
3323 if (opts->edit >= 0)
3324 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3325 opts->edit ? "true" : "false");
3326 if (opts->allow_empty)
3327 res |= git_config_set_in_file_gently(opts_file,
3328 "options.allow-empty", "true");
3329 if (opts->allow_empty_message)
3330 res |= git_config_set_in_file_gently(opts_file,
3331 "options.allow-empty-message", "true");
3332 if (opts->keep_redundant_commits)
3333 res |= git_config_set_in_file_gently(opts_file,
3334 "options.keep-redundant-commits", "true");
3335 if (opts->signoff)
3336 res |= git_config_set_in_file_gently(opts_file,
3337 "options.signoff", "true");
3338 if (opts->record_origin)
3339 res |= git_config_set_in_file_gently(opts_file,
3340 "options.record-origin", "true");
3341 if (opts->allow_ff)
3342 res |= git_config_set_in_file_gently(opts_file,
3343 "options.allow-ff", "true");
3344 if (opts->mainline) {
3345 struct strbuf buf = STRBUF_INIT;
3346 strbuf_addf(&buf, "%d", opts->mainline);
3347 res |= git_config_set_in_file_gently(opts_file,
3348 "options.mainline", buf.buf);
3349 strbuf_release(&buf);
3351 if (opts->strategy)
3352 res |= git_config_set_in_file_gently(opts_file,
3353 "options.strategy", opts->strategy);
3354 if (opts->gpg_sign)
3355 res |= git_config_set_in_file_gently(opts_file,
3356 "options.gpg-sign", opts->gpg_sign);
3357 if (opts->xopts) {
3358 int i;
3359 for (i = 0; i < opts->xopts_nr; i++)
3360 res |= git_config_set_multivar_in_file_gently(opts_file,
3361 "options.strategy-option",
3362 opts->xopts[i], "^$", 0);
3364 if (opts->allow_rerere_auto)
3365 res |= git_config_set_in_file_gently(opts_file,
3366 "options.allow-rerere-auto",
3367 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3368 "true" : "false");
3370 if (opts->explicit_cleanup)
3371 res |= git_config_set_in_file_gently(opts_file,
3372 "options.default-msg-cleanup",
3373 describe_cleanup_mode(opts->default_msg_cleanup));
3374 return res;
3377 static int make_patch(struct repository *r,
3378 struct commit *commit,
3379 struct replay_opts *opts)
3381 struct strbuf buf = STRBUF_INIT;
3382 struct rev_info log_tree_opt;
3383 const char *subject;
3384 char hex[GIT_MAX_HEXSZ + 1];
3385 int res = 0;
3387 oid_to_hex_r(hex, &commit->object.oid);
3388 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3389 return -1;
3390 res |= write_rebase_head(&commit->object.oid);
3392 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3393 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3394 repo_init_revisions(r, &log_tree_opt, NULL);
3395 log_tree_opt.abbrev = 0;
3396 log_tree_opt.diff = 1;
3397 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3398 log_tree_opt.disable_stdin = 1;
3399 log_tree_opt.no_commit_id = 1;
3400 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3401 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3402 if (!log_tree_opt.diffopt.file)
3403 res |= error_errno(_("could not open '%s'"), buf.buf);
3404 else {
3405 res |= log_tree_commit(&log_tree_opt, commit);
3406 fclose(log_tree_opt.diffopt.file);
3408 strbuf_reset(&buf);
3410 strbuf_addf(&buf, "%s/message", get_dir(opts));
3411 if (!file_exists(buf.buf)) {
3412 const char *encoding = get_commit_output_encoding();
3413 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3414 find_commit_subject(commit_buffer, &subject);
3415 res |= write_message(subject, strlen(subject), buf.buf, 1);
3416 unuse_commit_buffer(commit, commit_buffer);
3418 strbuf_release(&buf);
3419 release_revisions(&log_tree_opt);
3421 return res;
3424 static int intend_to_amend(void)
3426 struct object_id head;
3427 char *p;
3429 if (get_oid("HEAD", &head))
3430 return error(_("cannot read HEAD"));
3432 p = oid_to_hex(&head);
3433 return write_message(p, strlen(p), rebase_path_amend(), 1);
3436 static int error_with_patch(struct repository *r,
3437 struct commit *commit,
3438 const char *subject, int subject_len,
3439 struct replay_opts *opts,
3440 int exit_code, int to_amend)
3442 if (commit) {
3443 if (make_patch(r, commit, opts))
3444 return -1;
3445 } else if (copy_file(rebase_path_message(),
3446 git_path_merge_msg(r), 0666))
3447 return error(_("unable to copy '%s' to '%s'"),
3448 git_path_merge_msg(r), rebase_path_message());
3450 if (to_amend) {
3451 if (intend_to_amend())
3452 return -1;
3454 fprintf(stderr,
3455 _("You can amend the commit now, with\n"
3456 "\n"
3457 " git commit --amend %s\n"
3458 "\n"
3459 "Once you are satisfied with your changes, run\n"
3460 "\n"
3461 " git rebase --continue\n"),
3462 gpg_sign_opt_quoted(opts));
3463 } else if (exit_code) {
3464 if (commit)
3465 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3466 short_commit_name(commit), subject_len, subject);
3467 else
3469 * We don't have the hash of the parent so
3470 * just print the line from the todo file.
3472 fprintf_ln(stderr, _("Could not merge %.*s"),
3473 subject_len, subject);
3476 return exit_code;
3479 static int error_failed_squash(struct repository *r,
3480 struct commit *commit,
3481 struct replay_opts *opts,
3482 int subject_len,
3483 const char *subject)
3485 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3486 return error(_("could not copy '%s' to '%s'"),
3487 rebase_path_squash_msg(), rebase_path_message());
3488 unlink(git_path_merge_msg(r));
3489 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3490 return error(_("could not copy '%s' to '%s'"),
3491 rebase_path_message(),
3492 git_path_merge_msg(r));
3493 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3496 static int do_exec(struct repository *r, const char *command_line)
3498 const char *child_argv[] = { NULL, NULL };
3499 int dirty, status;
3501 fprintf(stderr, _("Executing: %s\n"), command_line);
3502 child_argv[0] = command_line;
3503 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
3505 /* force re-reading of the cache */
3506 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3507 return error(_("could not read index"));
3509 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3511 if (status) {
3512 warning(_("execution failed: %s\n%s"
3513 "You can fix the problem, and then run\n"
3514 "\n"
3515 " git rebase --continue\n"
3516 "\n"),
3517 command_line,
3518 dirty ? N_("and made changes to the index and/or the "
3519 "working tree\n") : "");
3520 if (status == 127)
3521 /* command not found */
3522 status = 1;
3523 } else if (dirty) {
3524 warning(_("execution succeeded: %s\nbut "
3525 "left changes to the index and/or the working tree\n"
3526 "Commit or stash your changes, and then run\n"
3527 "\n"
3528 " git rebase --continue\n"
3529 "\n"), command_line);
3530 status = 1;
3533 return status;
3536 __attribute__((format (printf, 2, 3)))
3537 static int safe_append(const char *filename, const char *fmt, ...)
3539 va_list ap;
3540 struct lock_file lock = LOCK_INIT;
3541 int fd = hold_lock_file_for_update(&lock, filename,
3542 LOCK_REPORT_ON_ERROR);
3543 struct strbuf buf = STRBUF_INIT;
3545 if (fd < 0)
3546 return -1;
3548 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3549 error_errno(_("could not read '%s'"), filename);
3550 rollback_lock_file(&lock);
3551 return -1;
3553 strbuf_complete(&buf, '\n');
3554 va_start(ap, fmt);
3555 strbuf_vaddf(&buf, fmt, ap);
3556 va_end(ap);
3558 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3559 error_errno(_("could not write to '%s'"), filename);
3560 strbuf_release(&buf);
3561 rollback_lock_file(&lock);
3562 return -1;
3564 if (commit_lock_file(&lock) < 0) {
3565 strbuf_release(&buf);
3566 rollback_lock_file(&lock);
3567 return error(_("failed to finalize '%s'"), filename);
3570 strbuf_release(&buf);
3571 return 0;
3574 static int do_label(struct repository *r, const char *name, int len)
3576 struct ref_store *refs = get_main_ref_store(r);
3577 struct ref_transaction *transaction;
3578 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3579 struct strbuf msg = STRBUF_INIT;
3580 int ret = 0;
3581 struct object_id head_oid;
3583 if (len == 1 && *name == '#')
3584 return error(_("illegal label name: '%.*s'"), len, name);
3586 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3587 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3589 transaction = ref_store_transaction_begin(refs, 0, &err);
3590 if (!transaction) {
3591 error("%s", err.buf);
3592 ret = -1;
3593 } else if (get_oid("HEAD", &head_oid)) {
3594 error(_("could not read HEAD"));
3595 ret = -1;
3596 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3597 NULL, 0, msg.buf, &err) < 0 ||
3598 ref_transaction_commit(transaction, &err)) {
3599 error("%s", err.buf);
3600 ret = -1;
3602 ref_transaction_free(transaction);
3603 strbuf_release(&err);
3604 strbuf_release(&msg);
3606 if (!ret)
3607 ret = safe_append(rebase_path_refs_to_delete(),
3608 "%s\n", ref_name.buf);
3609 strbuf_release(&ref_name);
3611 return ret;
3614 __attribute__((format (printf, 3, 4)))
3615 static const char *reflog_message(struct replay_opts *opts,
3616 const char *sub_action, const char *fmt, ...)
3618 va_list ap;
3619 static struct strbuf buf = STRBUF_INIT;
3620 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3622 va_start(ap, fmt);
3623 strbuf_reset(&buf);
3624 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3625 if (sub_action)
3626 strbuf_addf(&buf, " (%s)", sub_action);
3627 if (fmt) {
3628 strbuf_addstr(&buf, ": ");
3629 strbuf_vaddf(&buf, fmt, ap);
3631 va_end(ap);
3633 return buf.buf;
3636 static int do_reset(struct repository *r,
3637 const char *name, int len,
3638 struct replay_opts *opts)
3640 struct strbuf ref_name = STRBUF_INIT;
3641 struct object_id oid;
3642 struct lock_file lock = LOCK_INIT;
3643 struct tree_desc desc = { 0 };
3644 struct tree *tree;
3645 struct unpack_trees_options unpack_tree_opts = { 0 };
3646 int ret = 0;
3648 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3649 return -1;
3651 if (len == 10 && !strncmp("[new root]", name, len)) {
3652 if (!opts->have_squash_onto) {
3653 const char *hex;
3654 if (commit_tree("", 0, the_hash_algo->empty_tree,
3655 NULL, &opts->squash_onto,
3656 NULL, NULL))
3657 return error(_("writing fake root commit"));
3658 opts->have_squash_onto = 1;
3659 hex = oid_to_hex(&opts->squash_onto);
3660 if (write_message(hex, strlen(hex),
3661 rebase_path_squash_onto(), 0))
3662 return error(_("writing squash-onto"));
3664 oidcpy(&oid, &opts->squash_onto);
3665 } else {
3666 int i;
3668 /* Determine the length of the label */
3669 for (i = 0; i < len; i++)
3670 if (isspace(name[i]))
3671 break;
3672 len = i;
3674 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3675 if (get_oid(ref_name.buf, &oid) &&
3676 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3677 ret = error(_("could not read '%s'"), ref_name.buf);
3678 goto cleanup;
3682 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3683 unpack_tree_opts.head_idx = 1;
3684 unpack_tree_opts.src_index = r->index;
3685 unpack_tree_opts.dst_index = r->index;
3686 unpack_tree_opts.fn = oneway_merge;
3687 unpack_tree_opts.merge = 1;
3688 unpack_tree_opts.update = 1;
3689 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3690 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3692 if (repo_read_index_unmerged(r)) {
3693 ret = error_resolve_conflict(_(action_name(opts)));
3694 goto cleanup;
3697 if (!fill_tree_descriptor(r, &desc, &oid)) {
3698 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3699 goto cleanup;
3702 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3703 ret = -1;
3704 goto cleanup;
3707 tree = parse_tree_indirect(&oid);
3708 prime_cache_tree(r, r->index, tree);
3710 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3711 ret = error(_("could not write index"));
3713 if (!ret)
3714 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3715 len, name), "HEAD", &oid,
3716 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3717 cleanup:
3718 free((void *)desc.buffer);
3719 if (ret < 0)
3720 rollback_lock_file(&lock);
3721 strbuf_release(&ref_name);
3722 clear_unpack_trees_porcelain(&unpack_tree_opts);
3723 return ret;
3726 static struct commit *lookup_label(const char *label, int len,
3727 struct strbuf *buf)
3729 struct commit *commit;
3731 strbuf_reset(buf);
3732 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3733 commit = lookup_commit_reference_by_name(buf->buf);
3734 if (!commit) {
3735 /* fall back to non-rewritten ref or commit */
3736 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3737 commit = lookup_commit_reference_by_name(buf->buf);
3740 if (!commit)
3741 error(_("could not resolve '%s'"), buf->buf);
3743 return commit;
3746 static int do_merge(struct repository *r,
3747 struct commit *commit,
3748 const char *arg, int arg_len,
3749 int flags, int *check_todo, struct replay_opts *opts)
3751 int run_commit_flags = 0;
3752 struct strbuf ref_name = STRBUF_INIT;
3753 struct commit *head_commit, *merge_commit, *i;
3754 struct commit_list *bases, *j;
3755 struct commit_list *to_merge = NULL, **tail = &to_merge;
3756 const char *strategy = !opts->xopts_nr &&
3757 (!opts->strategy ||
3758 !strcmp(opts->strategy, "recursive") ||
3759 !strcmp(opts->strategy, "ort")) ?
3760 NULL : opts->strategy;
3761 struct merge_options o;
3762 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3763 static struct lock_file lock;
3764 const char *p;
3766 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3767 ret = -1;
3768 goto leave_merge;
3771 head_commit = lookup_commit_reference_by_name("HEAD");
3772 if (!head_commit) {
3773 ret = error(_("cannot merge without a current revision"));
3774 goto leave_merge;
3778 * For octopus merges, the arg starts with the list of revisions to be
3779 * merged. The list is optionally followed by '#' and the oneline.
3781 merge_arg_len = oneline_offset = arg_len;
3782 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3783 if (!*p)
3784 break;
3785 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3786 p += 1 + strspn(p + 1, " \t\n");
3787 oneline_offset = p - arg;
3788 break;
3790 k = strcspn(p, " \t\n");
3791 if (!k)
3792 continue;
3793 merge_commit = lookup_label(p, k, &ref_name);
3794 if (!merge_commit) {
3795 ret = error(_("unable to parse '%.*s'"), k, p);
3796 goto leave_merge;
3798 tail = &commit_list_insert(merge_commit, tail)->next;
3799 p += k;
3800 merge_arg_len = p - arg;
3803 if (!to_merge) {
3804 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3805 goto leave_merge;
3808 if (opts->have_squash_onto &&
3809 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3811 * When the user tells us to "merge" something into a
3812 * "[new root]", let's simply fast-forward to the merge head.
3814 rollback_lock_file(&lock);
3815 if (to_merge->next)
3816 ret = error(_("octopus merge cannot be executed on "
3817 "top of a [new root]"));
3818 else
3819 ret = fast_forward_to(r, &to_merge->item->object.oid,
3820 &head_commit->object.oid, 0,
3821 opts);
3822 goto leave_merge;
3826 * If HEAD is not identical to the first parent of the original merge
3827 * commit, we cannot fast-forward.
3829 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3830 oideq(&commit->parents->item->object.oid,
3831 &head_commit->object.oid);
3834 * If any merge head is different from the original one, we cannot
3835 * fast-forward.
3837 if (can_fast_forward) {
3838 struct commit_list *p = commit->parents->next;
3840 for (j = to_merge; j && p; j = j->next, p = p->next)
3841 if (!oideq(&j->item->object.oid,
3842 &p->item->object.oid)) {
3843 can_fast_forward = 0;
3844 break;
3847 * If the number of merge heads differs from the original merge
3848 * commit, we cannot fast-forward.
3850 if (j || p)
3851 can_fast_forward = 0;
3854 if (can_fast_forward) {
3855 rollback_lock_file(&lock);
3856 ret = fast_forward_to(r, &commit->object.oid,
3857 &head_commit->object.oid, 0, opts);
3858 if (flags & TODO_EDIT_MERGE_MSG)
3859 goto fast_forward_edit;
3861 goto leave_merge;
3864 if (commit) {
3865 const char *encoding = get_commit_output_encoding();
3866 const char *message = logmsg_reencode(commit, NULL, encoding);
3867 const char *body;
3868 int len;
3870 if (!message) {
3871 ret = error(_("could not get commit message of '%s'"),
3872 oid_to_hex(&commit->object.oid));
3873 goto leave_merge;
3875 write_author_script(message);
3876 find_commit_subject(message, &body);
3877 len = strlen(body);
3878 ret = write_message(body, len, git_path_merge_msg(r), 0);
3879 unuse_commit_buffer(commit, message);
3880 if (ret) {
3881 error_errno(_("could not write '%s'"),
3882 git_path_merge_msg(r));
3883 goto leave_merge;
3885 } else {
3886 struct strbuf buf = STRBUF_INIT;
3887 int len;
3889 strbuf_addf(&buf, "author %s", git_author_info(0));
3890 write_author_script(buf.buf);
3891 strbuf_reset(&buf);
3893 if (oneline_offset < arg_len) {
3894 p = arg + oneline_offset;
3895 len = arg_len - oneline_offset;
3896 } else {
3897 strbuf_addf(&buf, "Merge %s '%.*s'",
3898 to_merge->next ? "branches" : "branch",
3899 merge_arg_len, arg);
3900 p = buf.buf;
3901 len = buf.len;
3904 ret = write_message(p, len, git_path_merge_msg(r), 0);
3905 strbuf_release(&buf);
3906 if (ret) {
3907 error_errno(_("could not write '%s'"),
3908 git_path_merge_msg(r));
3909 goto leave_merge;
3913 if (strategy || to_merge->next) {
3914 /* Octopus merge */
3915 struct child_process cmd = CHILD_PROCESS_INIT;
3917 if (read_env_script(&cmd.env_array)) {
3918 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3920 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3921 goto leave_merge;
3924 if (opts->committer_date_is_author_date)
3925 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3926 opts->ignore_date ?
3927 "" :
3928 author_date_from_env_array(&cmd.env_array));
3929 if (opts->ignore_date)
3930 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3932 cmd.git_cmd = 1;
3933 strvec_push(&cmd.args, "merge");
3934 strvec_push(&cmd.args, "-s");
3935 if (!strategy)
3936 strvec_push(&cmd.args, "octopus");
3937 else {
3938 strvec_push(&cmd.args, strategy);
3939 for (k = 0; k < opts->xopts_nr; k++)
3940 strvec_pushf(&cmd.args,
3941 "-X%s", opts->xopts[k]);
3943 if (!(flags & TODO_EDIT_MERGE_MSG))
3944 strvec_push(&cmd.args, "--no-edit");
3945 else
3946 strvec_push(&cmd.args, "--edit");
3947 strvec_push(&cmd.args, "--no-ff");
3948 strvec_push(&cmd.args, "--no-log");
3949 strvec_push(&cmd.args, "--no-stat");
3950 strvec_push(&cmd.args, "-F");
3951 strvec_push(&cmd.args, git_path_merge_msg(r));
3952 if (opts->gpg_sign)
3953 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3954 else
3955 strvec_push(&cmd.args, "--no-gpg-sign");
3957 /* Add the tips to be merged */
3958 for (j = to_merge; j; j = j->next)
3959 strvec_push(&cmd.args,
3960 oid_to_hex(&j->item->object.oid));
3962 strbuf_release(&ref_name);
3963 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3964 NULL, 0);
3965 rollback_lock_file(&lock);
3967 ret = run_command(&cmd);
3969 /* force re-reading of the cache */
3970 if (!ret && (discard_index(r->index) < 0 ||
3971 repo_read_index(r) < 0))
3972 ret = error(_("could not read index"));
3973 goto leave_merge;
3976 merge_commit = to_merge->item;
3977 bases = get_merge_bases(head_commit, merge_commit);
3978 if (bases && oideq(&merge_commit->object.oid,
3979 &bases->item->object.oid)) {
3980 ret = 0;
3981 /* skip merging an ancestor of HEAD */
3982 goto leave_merge;
3985 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3986 git_path_merge_head(r), 0);
3987 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3989 bases = reverse_commit_list(bases);
3991 repo_read_index(r);
3992 init_merge_options(&o, r);
3993 o.branch1 = "HEAD";
3994 o.branch2 = ref_name.buf;
3995 o.buffer_output = 2;
3997 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
3999 * TODO: Should use merge_incore_recursive() and
4000 * merge_switch_to_result(), skipping the call to
4001 * merge_switch_to_result() when we don't actually need to
4002 * update the index and working copy immediately.
4004 ret = merge_ort_recursive(&o,
4005 head_commit, merge_commit, bases,
4006 &i);
4007 } else {
4008 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4009 &i);
4011 if (ret <= 0)
4012 fputs(o.obuf.buf, stdout);
4013 strbuf_release(&o.obuf);
4014 if (ret < 0) {
4015 error(_("could not even attempt to merge '%.*s'"),
4016 merge_arg_len, arg);
4017 goto leave_merge;
4020 * The return value of merge_recursive() is 1 on clean, and 0 on
4021 * unclean merge.
4023 * Let's reverse that, so that do_merge() returns 0 upon success and
4024 * 1 upon failed merge (keeping the return value -1 for the cases where
4025 * we will want to reschedule the `merge` command).
4027 ret = !ret;
4029 if (r->index->cache_changed &&
4030 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4031 ret = error(_("merge: Unable to write new index file"));
4032 goto leave_merge;
4035 rollback_lock_file(&lock);
4036 if (ret)
4037 repo_rerere(r, opts->allow_rerere_auto);
4038 else
4040 * In case of problems, we now want to return a positive
4041 * value (a negative one would indicate that the `merge`
4042 * command needs to be rescheduled).
4044 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4045 run_commit_flags);
4047 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4048 fast_forward_edit:
4049 *check_todo = 1;
4050 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4051 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4055 leave_merge:
4056 strbuf_release(&ref_name);
4057 rollback_lock_file(&lock);
4058 free_commit_list(to_merge);
4059 return ret;
4062 static int is_final_fixup(struct todo_list *todo_list)
4064 int i = todo_list->current;
4066 if (!is_fixup(todo_list->items[i].command))
4067 return 0;
4069 while (++i < todo_list->nr)
4070 if (is_fixup(todo_list->items[i].command))
4071 return 0;
4072 else if (!is_noop(todo_list->items[i].command))
4073 break;
4074 return 1;
4077 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4079 int i;
4081 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4082 if (!is_noop(todo_list->items[i].command))
4083 return todo_list->items[i].command;
4085 return -1;
4088 void create_autostash(struct repository *r, const char *path)
4090 struct strbuf buf = STRBUF_INIT;
4091 struct lock_file lock_file = LOCK_INIT;
4092 int fd;
4094 fd = repo_hold_locked_index(r, &lock_file, 0);
4095 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4096 if (0 <= fd)
4097 repo_update_index_if_able(r, &lock_file);
4098 rollback_lock_file(&lock_file);
4100 if (has_unstaged_changes(r, 1) ||
4101 has_uncommitted_changes(r, 1)) {
4102 struct child_process stash = CHILD_PROCESS_INIT;
4103 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4104 struct object_id oid;
4106 strvec_pushl(&stash.args,
4107 "stash", "create", "autostash", NULL);
4108 stash.git_cmd = 1;
4109 stash.no_stdin = 1;
4110 strbuf_reset(&buf);
4111 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4112 die(_("Cannot autostash"));
4113 strbuf_trim_trailing_newline(&buf);
4114 if (get_oid(buf.buf, &oid))
4115 die(_("Unexpected stash response: '%s'"),
4116 buf.buf);
4117 strbuf_reset(&buf);
4118 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4120 if (safe_create_leading_directories_const(path))
4121 die(_("Could not create directory for '%s'"),
4122 path);
4123 write_file(path, "%s", oid_to_hex(&oid));
4124 printf(_("Created autostash: %s\n"), buf.buf);
4125 if (reset_head(r, &ropts) < 0)
4126 die(_("could not reset --hard"));
4127 if (discard_index(r->index) < 0 ||
4128 repo_read_index(r) < 0)
4129 die(_("could not read index"));
4131 strbuf_release(&buf);
4134 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4136 struct child_process child = CHILD_PROCESS_INIT;
4137 int ret = 0;
4139 if (attempt_apply) {
4140 child.git_cmd = 1;
4141 child.no_stdout = 1;
4142 child.no_stderr = 1;
4143 strvec_push(&child.args, "stash");
4144 strvec_push(&child.args, "apply");
4145 strvec_push(&child.args, stash_oid);
4146 ret = run_command(&child);
4149 if (attempt_apply && !ret)
4150 fprintf(stderr, _("Applied autostash.\n"));
4151 else {
4152 struct child_process store = CHILD_PROCESS_INIT;
4154 store.git_cmd = 1;
4155 strvec_push(&store.args, "stash");
4156 strvec_push(&store.args, "store");
4157 strvec_push(&store.args, "-m");
4158 strvec_push(&store.args, "autostash");
4159 strvec_push(&store.args, "-q");
4160 strvec_push(&store.args, stash_oid);
4161 if (run_command(&store))
4162 ret = error(_("cannot store %s"), stash_oid);
4163 else
4164 fprintf(stderr,
4165 _("%s\n"
4166 "Your changes are safe in the stash.\n"
4167 "You can run \"git stash pop\" or"
4168 " \"git stash drop\" at any time.\n"),
4169 attempt_apply ?
4170 _("Applying autostash resulted in conflicts.") :
4171 _("Autostash exists; creating a new stash entry."));
4174 return ret;
4177 static int apply_save_autostash(const char *path, int attempt_apply)
4179 struct strbuf stash_oid = STRBUF_INIT;
4180 int ret = 0;
4182 if (!read_oneliner(&stash_oid, path,
4183 READ_ONELINER_SKIP_IF_EMPTY)) {
4184 strbuf_release(&stash_oid);
4185 return 0;
4187 strbuf_trim(&stash_oid);
4189 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4191 unlink(path);
4192 strbuf_release(&stash_oid);
4193 return ret;
4196 int save_autostash(const char *path)
4198 return apply_save_autostash(path, 0);
4201 int apply_autostash(const char *path)
4203 return apply_save_autostash(path, 1);
4206 int apply_autostash_oid(const char *stash_oid)
4208 return apply_save_autostash_oid(stash_oid, 1);
4211 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4212 const char *onto_name, const struct object_id *onto,
4213 const struct object_id *orig_head)
4215 struct reset_head_opts ropts = {
4216 .oid = onto,
4217 .orig_head = orig_head,
4218 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4219 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4220 .head_msg = reflog_message(opts, "start", "checkout %s",
4221 onto_name),
4222 .default_reflog_action = "rebase"
4224 if (reset_head(r, &ropts)) {
4225 apply_autostash(rebase_path_autostash());
4226 sequencer_remove_state(opts);
4227 return error(_("could not detach HEAD"));
4230 return 0;
4233 static int stopped_at_head(struct repository *r)
4235 struct object_id head;
4236 struct commit *commit;
4237 struct commit_message message;
4239 if (get_oid("HEAD", &head) ||
4240 !(commit = lookup_commit(r, &head)) ||
4241 parse_commit(commit) || get_message(commit, &message))
4242 fprintf(stderr, _("Stopped at HEAD\n"));
4243 else {
4244 fprintf(stderr, _("Stopped at %s\n"), message.label);
4245 free_message(commit, &message);
4247 return 0;
4251 static int reread_todo_if_changed(struct repository *r,
4252 struct todo_list *todo_list,
4253 struct replay_opts *opts)
4255 int offset;
4256 struct strbuf buf = STRBUF_INIT;
4258 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4259 return -1;
4260 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4261 if (buf.len != todo_list->buf.len - offset ||
4262 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4263 /* Reread the todo file if it has changed. */
4264 todo_list_release(todo_list);
4265 if (read_populate_todo(r, todo_list, opts))
4266 return -1; /* message was printed */
4267 /* `current` will be incremented on return */
4268 todo_list->current = -1;
4270 strbuf_release(&buf);
4272 return 0;
4275 static const char rescheduled_advice[] =
4276 N_("Could not execute the todo command\n"
4277 "\n"
4278 " %.*s"
4279 "\n"
4280 "It has been rescheduled; To edit the command before continuing, please\n"
4281 "edit the todo list first:\n"
4282 "\n"
4283 " git rebase --edit-todo\n"
4284 " git rebase --continue\n");
4286 static int pick_commits(struct repository *r,
4287 struct todo_list *todo_list,
4288 struct replay_opts *opts)
4290 int res = 0, reschedule = 0;
4291 char *prev_reflog_action;
4293 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4294 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4295 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4296 if (opts->allow_ff)
4297 assert(!(opts->signoff || opts->no_commit ||
4298 opts->record_origin || should_edit(opts) ||
4299 opts->committer_date_is_author_date ||
4300 opts->ignore_date));
4301 if (read_and_refresh_cache(r, opts))
4302 return -1;
4304 while (todo_list->current < todo_list->nr) {
4305 struct todo_item *item = todo_list->items + todo_list->current;
4306 const char *arg = todo_item_get_arg(todo_list, item);
4307 int check_todo = 0;
4309 if (save_todo(todo_list, opts))
4310 return -1;
4311 if (is_rebase_i(opts)) {
4312 if (item->command != TODO_COMMENT) {
4313 FILE *f = fopen(rebase_path_msgnum(), "w");
4315 todo_list->done_nr++;
4317 if (f) {
4318 fprintf(f, "%d\n", todo_list->done_nr);
4319 fclose(f);
4321 if (!opts->quiet)
4322 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4323 todo_list->done_nr,
4324 todo_list->total_nr,
4325 opts->verbose ? "\n" : "\r");
4327 unlink(rebase_path_message());
4328 unlink(rebase_path_author_script());
4329 unlink(rebase_path_stopped_sha());
4330 unlink(rebase_path_amend());
4331 unlink(git_path_merge_head(r));
4332 unlink(git_path_auto_merge(r));
4333 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4335 if (item->command == TODO_BREAK) {
4336 if (!opts->verbose)
4337 term_clear_line();
4338 return stopped_at_head(r);
4341 if (item->command <= TODO_SQUASH) {
4342 if (is_rebase_i(opts))
4343 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4344 command_to_string(item->command), NULL),
4346 res = do_pick_commit(r, item, opts,
4347 is_final_fixup(todo_list),
4348 &check_todo);
4349 if (is_rebase_i(opts))
4350 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4351 if (is_rebase_i(opts) && res < 0) {
4352 /* Reschedule */
4353 advise(_(rescheduled_advice),
4354 get_item_line_length(todo_list,
4355 todo_list->current),
4356 get_item_line(todo_list,
4357 todo_list->current));
4358 todo_list->current--;
4359 if (save_todo(todo_list, opts))
4360 return -1;
4362 if (item->command == TODO_EDIT) {
4363 struct commit *commit = item->commit;
4364 if (!res) {
4365 if (!opts->verbose)
4366 term_clear_line();
4367 fprintf(stderr,
4368 _("Stopped at %s... %.*s\n"),
4369 short_commit_name(commit),
4370 item->arg_len, arg);
4372 return error_with_patch(r, commit,
4373 arg, item->arg_len, opts, res, !res);
4375 if (is_rebase_i(opts) && !res)
4376 record_in_rewritten(&item->commit->object.oid,
4377 peek_command(todo_list, 1));
4378 if (res && is_fixup(item->command)) {
4379 if (res == 1)
4380 intend_to_amend();
4381 return error_failed_squash(r, item->commit, opts,
4382 item->arg_len, arg);
4383 } else if (res && is_rebase_i(opts) && item->commit) {
4384 int to_amend = 0;
4385 struct object_id oid;
4388 * If we are rewording and have either
4389 * fast-forwarded already, or are about to
4390 * create a new root commit, we want to amend,
4391 * otherwise we do not.
4393 if (item->command == TODO_REWORD &&
4394 !get_oid("HEAD", &oid) &&
4395 (oideq(&item->commit->object.oid, &oid) ||
4396 (opts->have_squash_onto &&
4397 oideq(&opts->squash_onto, &oid))))
4398 to_amend = 1;
4400 return res | error_with_patch(r, item->commit,
4401 arg, item->arg_len, opts,
4402 res, to_amend);
4404 } else if (item->command == TODO_EXEC) {
4405 char *end_of_arg = (char *)(arg + item->arg_len);
4406 int saved = *end_of_arg;
4408 if (!opts->verbose)
4409 term_clear_line();
4410 *end_of_arg = '\0';
4411 res = do_exec(r, arg);
4412 *end_of_arg = saved;
4414 if (res) {
4415 if (opts->reschedule_failed_exec)
4416 reschedule = 1;
4418 check_todo = 1;
4419 } else if (item->command == TODO_LABEL) {
4420 if ((res = do_label(r, arg, item->arg_len)))
4421 reschedule = 1;
4422 } else if (item->command == TODO_RESET) {
4423 if ((res = do_reset(r, arg, item->arg_len, opts)))
4424 reschedule = 1;
4425 } else if (item->command == TODO_MERGE) {
4426 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4427 item->flags, &check_todo, opts)) < 0)
4428 reschedule = 1;
4429 else if (item->commit)
4430 record_in_rewritten(&item->commit->object.oid,
4431 peek_command(todo_list, 1));
4432 if (res > 0)
4433 /* failed with merge conflicts */
4434 return error_with_patch(r, item->commit,
4435 arg, item->arg_len,
4436 opts, res, 0);
4437 } else if (!is_noop(item->command))
4438 return error(_("unknown command %d"), item->command);
4440 if (reschedule) {
4441 advise(_(rescheduled_advice),
4442 get_item_line_length(todo_list,
4443 todo_list->current),
4444 get_item_line(todo_list, todo_list->current));
4445 todo_list->current--;
4446 if (save_todo(todo_list, opts))
4447 return -1;
4448 if (item->commit)
4449 return error_with_patch(r,
4450 item->commit,
4451 arg, item->arg_len,
4452 opts, res, 0);
4453 } else if (is_rebase_i(opts) && check_todo && !res &&
4454 reread_todo_if_changed(r, todo_list, opts)) {
4455 return -1;
4458 todo_list->current++;
4459 if (res)
4460 return res;
4463 if (is_rebase_i(opts)) {
4464 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4465 struct stat st;
4467 /* Stopped in the middle, as planned? */
4468 if (todo_list->current < todo_list->nr)
4469 return 0;
4471 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4472 starts_with(head_ref.buf, "refs/")) {
4473 const char *msg;
4474 struct object_id head, orig;
4475 int res;
4477 if (get_oid("HEAD", &head)) {
4478 res = error(_("cannot read HEAD"));
4479 cleanup_head_ref:
4480 strbuf_release(&head_ref);
4481 strbuf_release(&buf);
4482 return res;
4484 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4485 get_oid_hex(buf.buf, &orig)) {
4486 res = error(_("could not read orig-head"));
4487 goto cleanup_head_ref;
4489 strbuf_reset(&buf);
4490 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4491 res = error(_("could not read 'onto'"));
4492 goto cleanup_head_ref;
4494 msg = reflog_message(opts, "finish", "%s onto %s",
4495 head_ref.buf, buf.buf);
4496 if (update_ref(msg, head_ref.buf, &head, &orig,
4497 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4498 res = error(_("could not update %s"),
4499 head_ref.buf);
4500 goto cleanup_head_ref;
4502 msg = reflog_message(opts, "finish", "returning to %s",
4503 head_ref.buf);
4504 if (create_symref("HEAD", head_ref.buf, msg)) {
4505 res = error(_("could not update HEAD to %s"),
4506 head_ref.buf);
4507 goto cleanup_head_ref;
4509 strbuf_reset(&buf);
4512 if (opts->verbose) {
4513 struct rev_info log_tree_opt;
4514 struct object_id orig, head;
4516 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4517 repo_init_revisions(r, &log_tree_opt, NULL);
4518 log_tree_opt.diff = 1;
4519 log_tree_opt.diffopt.output_format =
4520 DIFF_FORMAT_DIFFSTAT;
4521 log_tree_opt.disable_stdin = 1;
4523 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4524 !get_oid(buf.buf, &orig) &&
4525 !get_oid("HEAD", &head)) {
4526 diff_tree_oid(&orig, &head, "",
4527 &log_tree_opt.diffopt);
4528 log_tree_diff_flush(&log_tree_opt);
4530 release_revisions(&log_tree_opt);
4532 flush_rewritten_pending();
4533 if (!stat(rebase_path_rewritten_list(), &st) &&
4534 st.st_size > 0) {
4535 struct child_process child = CHILD_PROCESS_INIT;
4536 const char *post_rewrite_hook =
4537 find_hook("post-rewrite");
4539 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4540 child.git_cmd = 1;
4541 strvec_push(&child.args, "notes");
4542 strvec_push(&child.args, "copy");
4543 strvec_push(&child.args, "--for-rewrite=rebase");
4544 /* we don't care if this copying failed */
4545 run_command(&child);
4547 if (post_rewrite_hook) {
4548 struct child_process hook = CHILD_PROCESS_INIT;
4550 hook.in = open(rebase_path_rewritten_list(),
4551 O_RDONLY);
4552 hook.stdout_to_stderr = 1;
4553 hook.trace2_hook_name = "post-rewrite";
4554 strvec_push(&hook.args, post_rewrite_hook);
4555 strvec_push(&hook.args, "rebase");
4556 /* we don't care if this hook failed */
4557 run_command(&hook);
4560 apply_autostash(rebase_path_autostash());
4562 if (!opts->quiet) {
4563 if (!opts->verbose)
4564 term_clear_line();
4565 fprintf(stderr,
4566 _("Successfully rebased and updated %s.\n"),
4567 head_ref.buf);
4570 strbuf_release(&buf);
4571 strbuf_release(&head_ref);
4575 * Sequence of picks finished successfully; cleanup by
4576 * removing the .git/sequencer directory
4578 return sequencer_remove_state(opts);
4581 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4583 struct strvec argv = STRVEC_INIT;
4584 int ret;
4586 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4587 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4588 return error(_("no cherry-pick or revert in progress"));
4590 strvec_push(&argv, "commit");
4593 * continue_single_pick() handles the case of recovering from a
4594 * conflict. should_edit() doesn't handle that case; for a conflict,
4595 * we want to edit if the user asked for it, or if they didn't specify
4596 * and stdin is a tty.
4598 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4600 * Include --cleanup=strip as well because we don't want the
4601 * "# Conflicts:" messages.
4603 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4605 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4606 strvec_clear(&argv);
4607 return ret;
4610 static int commit_staged_changes(struct repository *r,
4611 struct replay_opts *opts,
4612 struct todo_list *todo_list)
4614 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4615 unsigned int final_fixup = 0, is_clean;
4617 if (has_unstaged_changes(r, 1))
4618 return error(_("cannot rebase: You have unstaged changes."));
4620 is_clean = !has_uncommitted_changes(r, 0);
4622 if (file_exists(rebase_path_amend())) {
4623 struct strbuf rev = STRBUF_INIT;
4624 struct object_id head, to_amend;
4626 if (get_oid("HEAD", &head))
4627 return error(_("cannot amend non-existing commit"));
4628 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4629 return error(_("invalid file: '%s'"), rebase_path_amend());
4630 if (get_oid_hex(rev.buf, &to_amend))
4631 return error(_("invalid contents: '%s'"),
4632 rebase_path_amend());
4633 if (!is_clean && !oideq(&head, &to_amend))
4634 return error(_("\nYou have uncommitted changes in your "
4635 "working tree. Please, commit them\n"
4636 "first and then run 'git rebase "
4637 "--continue' again."));
4639 * When skipping a failed fixup/squash, we need to edit the
4640 * commit message, the current fixup list and count, and if it
4641 * was the last fixup/squash in the chain, we need to clean up
4642 * the commit message and if there was a squash, let the user
4643 * edit it.
4645 if (!is_clean || !opts->current_fixup_count)
4646 ; /* this is not the final fixup */
4647 else if (!oideq(&head, &to_amend) ||
4648 !file_exists(rebase_path_stopped_sha())) {
4649 /* was a final fixup or squash done manually? */
4650 if (!is_fixup(peek_command(todo_list, 0))) {
4651 unlink(rebase_path_fixup_msg());
4652 unlink(rebase_path_squash_msg());
4653 unlink(rebase_path_current_fixups());
4654 strbuf_reset(&opts->current_fixups);
4655 opts->current_fixup_count = 0;
4657 } else {
4658 /* we are in a fixup/squash chain */
4659 const char *p = opts->current_fixups.buf;
4660 int len = opts->current_fixups.len;
4662 opts->current_fixup_count--;
4663 if (!len)
4664 BUG("Incorrect current_fixups:\n%s", p);
4665 while (len && p[len - 1] != '\n')
4666 len--;
4667 strbuf_setlen(&opts->current_fixups, len);
4668 if (write_message(p, len, rebase_path_current_fixups(),
4669 0) < 0)
4670 return error(_("could not write file: '%s'"),
4671 rebase_path_current_fixups());
4674 * If a fixup/squash in a fixup/squash chain failed, the
4675 * commit message is already correct, no need to commit
4676 * it again.
4678 * Only if it is the final command in the fixup/squash
4679 * chain, and only if the chain is longer than a single
4680 * fixup/squash command (which was just skipped), do we
4681 * actually need to re-commit with a cleaned up commit
4682 * message.
4684 if (opts->current_fixup_count > 0 &&
4685 !is_fixup(peek_command(todo_list, 0))) {
4686 final_fixup = 1;
4688 * If there was not a single "squash" in the
4689 * chain, we only need to clean up the commit
4690 * message, no need to bother the user with
4691 * opening the commit message in the editor.
4693 if (!starts_with(p, "squash ") &&
4694 !strstr(p, "\nsquash "))
4695 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4696 } else if (is_fixup(peek_command(todo_list, 0))) {
4698 * We need to update the squash message to skip
4699 * the latest commit message.
4701 struct commit *commit;
4702 const char *path = rebase_path_squash_msg();
4703 const char *encoding = get_commit_output_encoding();
4705 if (parse_head(r, &commit) ||
4706 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4707 write_message(p, strlen(p), path, 0)) {
4708 unuse_commit_buffer(commit, p);
4709 return error(_("could not write file: "
4710 "'%s'"), path);
4712 unuse_commit_buffer(commit, p);
4716 strbuf_release(&rev);
4717 flags |= AMEND_MSG;
4720 if (is_clean) {
4721 if (refs_ref_exists(get_main_ref_store(r),
4722 "CHERRY_PICK_HEAD") &&
4723 refs_delete_ref(get_main_ref_store(r), "",
4724 "CHERRY_PICK_HEAD", NULL, 0))
4725 return error(_("could not remove CHERRY_PICK_HEAD"));
4726 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4727 return error_errno(_("could not remove '%s'"),
4728 git_path_merge_msg(r));
4729 if (!final_fixup)
4730 return 0;
4733 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4734 opts, flags))
4735 return error(_("could not commit staged changes."));
4736 unlink(rebase_path_amend());
4737 unlink(git_path_merge_head(r));
4738 unlink(git_path_auto_merge(r));
4739 if (final_fixup) {
4740 unlink(rebase_path_fixup_msg());
4741 unlink(rebase_path_squash_msg());
4743 if (opts->current_fixup_count > 0) {
4745 * Whether final fixup or not, we just cleaned up the commit
4746 * message...
4748 unlink(rebase_path_current_fixups());
4749 strbuf_reset(&opts->current_fixups);
4750 opts->current_fixup_count = 0;
4752 return 0;
4755 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4757 struct todo_list todo_list = TODO_LIST_INIT;
4758 int res;
4760 if (read_and_refresh_cache(r, opts))
4761 return -1;
4763 if (read_populate_opts(opts))
4764 return -1;
4765 if (is_rebase_i(opts)) {
4766 if ((res = read_populate_todo(r, &todo_list, opts)))
4767 goto release_todo_list;
4769 if (file_exists(rebase_path_dropped())) {
4770 if ((res = todo_list_check_against_backup(r, &todo_list)))
4771 goto release_todo_list;
4773 unlink(rebase_path_dropped());
4776 if (commit_staged_changes(r, opts, &todo_list)) {
4777 res = -1;
4778 goto release_todo_list;
4780 } else if (!file_exists(get_todo_path(opts)))
4781 return continue_single_pick(r, opts);
4782 else if ((res = read_populate_todo(r, &todo_list, opts)))
4783 goto release_todo_list;
4785 if (!is_rebase_i(opts)) {
4786 /* Verify that the conflict has been resolved */
4787 if (refs_ref_exists(get_main_ref_store(r),
4788 "CHERRY_PICK_HEAD") ||
4789 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4790 res = continue_single_pick(r, opts);
4791 if (res)
4792 goto release_todo_list;
4794 if (index_differs_from(r, "HEAD", NULL, 0)) {
4795 res = error_dirty_index(r, opts);
4796 goto release_todo_list;
4798 todo_list.current++;
4799 } else if (file_exists(rebase_path_stopped_sha())) {
4800 struct strbuf buf = STRBUF_INIT;
4801 struct object_id oid;
4803 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4804 READ_ONELINER_SKIP_IF_EMPTY) &&
4805 !get_oid_hex(buf.buf, &oid))
4806 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4807 strbuf_release(&buf);
4810 res = pick_commits(r, &todo_list, opts);
4811 release_todo_list:
4812 todo_list_release(&todo_list);
4813 return res;
4816 static int single_pick(struct repository *r,
4817 struct commit *cmit,
4818 struct replay_opts *opts)
4820 int check_todo;
4821 struct todo_item item;
4823 item.command = opts->action == REPLAY_PICK ?
4824 TODO_PICK : TODO_REVERT;
4825 item.commit = cmit;
4827 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4828 return do_pick_commit(r, &item, opts, 0, &check_todo);
4831 int sequencer_pick_revisions(struct repository *r,
4832 struct replay_opts *opts)
4834 struct todo_list todo_list = TODO_LIST_INIT;
4835 struct object_id oid;
4836 int i, res;
4838 assert(opts->revs);
4839 if (read_and_refresh_cache(r, opts))
4840 return -1;
4842 for (i = 0; i < opts->revs->pending.nr; i++) {
4843 struct object_id oid;
4844 const char *name = opts->revs->pending.objects[i].name;
4846 /* This happens when using --stdin. */
4847 if (!strlen(name))
4848 continue;
4850 if (!get_oid(name, &oid)) {
4851 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4852 enum object_type type = oid_object_info(r,
4853 &oid,
4854 NULL);
4855 return error(_("%s: can't cherry-pick a %s"),
4856 name, type_name(type));
4858 } else
4859 return error(_("%s: bad revision"), name);
4863 * If we were called as "git cherry-pick <commit>", just
4864 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4865 * REVERT_HEAD, and don't touch the sequencer state.
4866 * This means it is possible to cherry-pick in the middle
4867 * of a cherry-pick sequence.
4869 if (opts->revs->cmdline.nr == 1 &&
4870 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4871 opts->revs->no_walk &&
4872 !opts->revs->cmdline.rev->flags) {
4873 struct commit *cmit;
4874 if (prepare_revision_walk(opts->revs))
4875 return error(_("revision walk setup failed"));
4876 cmit = get_revision(opts->revs);
4877 if (!cmit)
4878 return error(_("empty commit set passed"));
4879 if (get_revision(opts->revs))
4880 BUG("unexpected extra commit from walk");
4881 return single_pick(r, cmit, opts);
4885 * Start a new cherry-pick/ revert sequence; but
4886 * first, make sure that an existing one isn't in
4887 * progress
4890 if (walk_revs_populate_todo(&todo_list, opts) ||
4891 create_seq_dir(r) < 0)
4892 return -1;
4893 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4894 return error(_("can't revert as initial commit"));
4895 if (save_head(oid_to_hex(&oid)))
4896 return -1;
4897 if (save_opts(opts))
4898 return -1;
4899 update_abort_safety_file();
4900 res = pick_commits(r, &todo_list, opts);
4901 todo_list_release(&todo_list);
4902 return res;
4905 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4907 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4908 struct strbuf sob = STRBUF_INIT;
4909 int has_footer;
4911 strbuf_addstr(&sob, sign_off_header);
4912 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4913 strbuf_addch(&sob, '\n');
4915 if (!ignore_footer)
4916 strbuf_complete_line(msgbuf);
4919 * If the whole message buffer is equal to the sob, pretend that we
4920 * found a conforming footer with a matching sob
4922 if (msgbuf->len - ignore_footer == sob.len &&
4923 !strncmp(msgbuf->buf, sob.buf, sob.len))
4924 has_footer = 3;
4925 else
4926 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4928 if (!has_footer) {
4929 const char *append_newlines = NULL;
4930 size_t len = msgbuf->len - ignore_footer;
4932 if (!len) {
4934 * The buffer is completely empty. Leave foom for
4935 * the title and body to be filled in by the user.
4937 append_newlines = "\n\n";
4938 } else if (len == 1) {
4940 * Buffer contains a single newline. Add another
4941 * so that we leave room for the title and body.
4943 append_newlines = "\n";
4944 } else if (msgbuf->buf[len - 2] != '\n') {
4946 * Buffer ends with a single newline. Add another
4947 * so that there is an empty line between the message
4948 * body and the sob.
4950 append_newlines = "\n";
4951 } /* else, the buffer already ends with two newlines. */
4953 if (append_newlines)
4954 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4955 append_newlines, strlen(append_newlines));
4958 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4959 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4960 sob.buf, sob.len);
4962 strbuf_release(&sob);
4965 struct labels_entry {
4966 struct hashmap_entry entry;
4967 char label[FLEX_ARRAY];
4970 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4971 const struct hashmap_entry *entry_or_key, const void *key)
4973 const struct labels_entry *a, *b;
4975 a = container_of(eptr, const struct labels_entry, entry);
4976 b = container_of(entry_or_key, const struct labels_entry, entry);
4978 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4981 struct string_entry {
4982 struct oidmap_entry entry;
4983 char string[FLEX_ARRAY];
4986 struct label_state {
4987 struct oidmap commit2label;
4988 struct hashmap labels;
4989 struct strbuf buf;
4992 static const char *label_oid(struct object_id *oid, const char *label,
4993 struct label_state *state)
4995 struct labels_entry *labels_entry;
4996 struct string_entry *string_entry;
4997 struct object_id dummy;
4998 int i;
5000 string_entry = oidmap_get(&state->commit2label, oid);
5001 if (string_entry)
5002 return string_entry->string;
5005 * For "uninteresting" commits, i.e. commits that are not to be
5006 * rebased, and which can therefore not be labeled, we use a unique
5007 * abbreviation of the commit name. This is slightly more complicated
5008 * than calling find_unique_abbrev() because we also need to make
5009 * sure that the abbreviation does not conflict with any other
5010 * label.
5012 * We disallow "interesting" commits to be labeled by a string that
5013 * is a valid full-length hash, to ensure that we always can find an
5014 * abbreviation for any uninteresting commit's names that does not
5015 * clash with any other label.
5017 strbuf_reset(&state->buf);
5018 if (!label) {
5019 char *p;
5021 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5022 label = p = state->buf.buf;
5024 find_unique_abbrev_r(p, oid, default_abbrev);
5027 * We may need to extend the abbreviated hash so that there is
5028 * no conflicting label.
5030 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5031 size_t i = strlen(p) + 1;
5033 oid_to_hex_r(p, oid);
5034 for (; i < the_hash_algo->hexsz; i++) {
5035 char save = p[i];
5036 p[i] = '\0';
5037 if (!hashmap_get_from_hash(&state->labels,
5038 strihash(p), p))
5039 break;
5040 p[i] = save;
5043 } else {
5044 struct strbuf *buf = &state->buf;
5047 * Sanitize labels by replacing non-alpha-numeric characters
5048 * (including white-space ones) by dashes, as they might be
5049 * illegal in file names (and hence in ref names).
5051 * Note that we retain non-ASCII UTF-8 characters (identified
5052 * via the most significant bit). They should be all acceptable
5053 * in file names. We do not validate the UTF-8 here, that's not
5054 * the job of this function.
5056 for (; *label; label++)
5057 if ((*label & 0x80) || isalnum(*label))
5058 strbuf_addch(buf, *label);
5059 /* avoid leading dash and double-dashes */
5060 else if (buf->len && buf->buf[buf->len - 1] != '-')
5061 strbuf_addch(buf, '-');
5062 if (!buf->len) {
5063 strbuf_addstr(buf, "rev-");
5064 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5066 label = buf->buf;
5068 if ((buf->len == the_hash_algo->hexsz &&
5069 !get_oid_hex(label, &dummy)) ||
5070 (buf->len == 1 && *label == '#') ||
5071 hashmap_get_from_hash(&state->labels,
5072 strihash(label), label)) {
5074 * If the label already exists, or if the label is a
5075 * valid full OID, or the label is a '#' (which we use
5076 * as a separator between merge heads and oneline), we
5077 * append a dash and a number to make it unique.
5079 size_t len = buf->len;
5081 for (i = 2; ; i++) {
5082 strbuf_setlen(buf, len);
5083 strbuf_addf(buf, "-%d", i);
5084 if (!hashmap_get_from_hash(&state->labels,
5085 strihash(buf->buf),
5086 buf->buf))
5087 break;
5090 label = buf->buf;
5094 FLEX_ALLOC_STR(labels_entry, label, label);
5095 hashmap_entry_init(&labels_entry->entry, strihash(label));
5096 hashmap_add(&state->labels, &labels_entry->entry);
5098 FLEX_ALLOC_STR(string_entry, string, label);
5099 oidcpy(&string_entry->entry.oid, oid);
5100 oidmap_put(&state->commit2label, string_entry);
5102 return string_entry->string;
5105 static int make_script_with_merges(struct pretty_print_context *pp,
5106 struct rev_info *revs, struct strbuf *out,
5107 unsigned flags)
5109 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5110 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5111 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5112 int skipped_commit = 0;
5113 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5114 struct strbuf label = STRBUF_INIT;
5115 struct commit_list *commits = NULL, **tail = &commits, *iter;
5116 struct commit_list *tips = NULL, **tips_tail = &tips;
5117 struct commit *commit;
5118 struct oidmap commit2todo = OIDMAP_INIT;
5119 struct string_entry *entry;
5120 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5121 shown = OIDSET_INIT;
5122 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5124 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5125 const char *cmd_pick = abbr ? "p" : "pick",
5126 *cmd_label = abbr ? "l" : "label",
5127 *cmd_reset = abbr ? "t" : "reset",
5128 *cmd_merge = abbr ? "m" : "merge";
5130 oidmap_init(&commit2todo, 0);
5131 oidmap_init(&state.commit2label, 0);
5132 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5133 strbuf_init(&state.buf, 32);
5135 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5136 struct labels_entry *onto_label_entry;
5137 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5138 FLEX_ALLOC_STR(entry, string, "onto");
5139 oidcpy(&entry->entry.oid, oid);
5140 oidmap_put(&state.commit2label, entry);
5142 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5143 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5144 hashmap_add(&state.labels, &onto_label_entry->entry);
5148 * First phase:
5149 * - get onelines for all commits
5150 * - gather all branch tips (i.e. 2nd or later parents of merges)
5151 * - label all branch tips
5153 while ((commit = get_revision(revs))) {
5154 struct commit_list *to_merge;
5155 const char *p1, *p2;
5156 struct object_id *oid;
5157 int is_empty;
5159 tail = &commit_list_insert(commit, tail)->next;
5160 oidset_insert(&interesting, &commit->object.oid);
5162 is_empty = is_original_commit_empty(commit);
5163 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5164 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5165 warning(_("skipped previously applied commit %s"),
5166 short_commit_name(commit));
5167 skipped_commit = 1;
5168 continue;
5170 if (is_empty && !keep_empty)
5171 continue;
5173 strbuf_reset(&oneline);
5174 pretty_print_commit(pp, commit, &oneline);
5176 to_merge = commit->parents ? commit->parents->next : NULL;
5177 if (!to_merge) {
5178 /* non-merge commit: easy case */
5179 strbuf_reset(&buf);
5180 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5181 oid_to_hex(&commit->object.oid),
5182 oneline.buf);
5183 if (is_empty)
5184 strbuf_addf(&buf, " %c empty",
5185 comment_line_char);
5187 FLEX_ALLOC_STR(entry, string, buf.buf);
5188 oidcpy(&entry->entry.oid, &commit->object.oid);
5189 oidmap_put(&commit2todo, entry);
5191 continue;
5194 /* Create a label */
5195 strbuf_reset(&label);
5196 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5197 (p1 = strchr(p1, '\'')) &&
5198 (p2 = strchr(++p1, '\'')))
5199 strbuf_add(&label, p1, p2 - p1);
5200 else if (skip_prefix(oneline.buf, "Merge pull request ",
5201 &p1) &&
5202 (p1 = strstr(p1, " from ")))
5203 strbuf_addstr(&label, p1 + strlen(" from "));
5204 else
5205 strbuf_addbuf(&label, &oneline);
5207 strbuf_reset(&buf);
5208 strbuf_addf(&buf, "%s -C %s",
5209 cmd_merge, oid_to_hex(&commit->object.oid));
5211 /* label the tips of merged branches */
5212 for (; to_merge; to_merge = to_merge->next) {
5213 oid = &to_merge->item->object.oid;
5214 strbuf_addch(&buf, ' ');
5216 if (!oidset_contains(&interesting, oid)) {
5217 strbuf_addstr(&buf, label_oid(oid, NULL,
5218 &state));
5219 continue;
5222 tips_tail = &commit_list_insert(to_merge->item,
5223 tips_tail)->next;
5225 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5227 strbuf_addf(&buf, " # %s", oneline.buf);
5229 FLEX_ALLOC_STR(entry, string, buf.buf);
5230 oidcpy(&entry->entry.oid, &commit->object.oid);
5231 oidmap_put(&commit2todo, entry);
5233 if (skipped_commit)
5234 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5235 _("use --reapply-cherry-picks to include skipped commits"));
5238 * Second phase:
5239 * - label branch points
5240 * - add HEAD to the branch tips
5242 for (iter = commits; iter; iter = iter->next) {
5243 struct commit_list *parent = iter->item->parents;
5244 for (; parent; parent = parent->next) {
5245 struct object_id *oid = &parent->item->object.oid;
5246 if (!oidset_contains(&interesting, oid))
5247 continue;
5248 if (oidset_insert(&child_seen, oid))
5249 label_oid(oid, "branch-point", &state);
5252 /* Add HEAD as implicit "tip of branch" */
5253 if (!iter->next)
5254 tips_tail = &commit_list_insert(iter->item,
5255 tips_tail)->next;
5259 * Third phase: output the todo list. This is a bit tricky, as we
5260 * want to avoid jumping back and forth between revisions. To
5261 * accomplish that goal, we walk backwards from the branch tips,
5262 * gathering commits not yet shown, reversing the list on the fly,
5263 * then outputting that list (labeling revisions as needed).
5265 strbuf_addf(out, "%s onto\n", cmd_label);
5266 for (iter = tips; iter; iter = iter->next) {
5267 struct commit_list *list = NULL, *iter2;
5269 commit = iter->item;
5270 if (oidset_contains(&shown, &commit->object.oid))
5271 continue;
5272 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5274 if (entry)
5275 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5276 else
5277 strbuf_addch(out, '\n');
5279 while (oidset_contains(&interesting, &commit->object.oid) &&
5280 !oidset_contains(&shown, &commit->object.oid)) {
5281 commit_list_insert(commit, &list);
5282 if (!commit->parents) {
5283 commit = NULL;
5284 break;
5286 commit = commit->parents->item;
5289 if (!commit)
5290 strbuf_addf(out, "%s %s\n", cmd_reset,
5291 rebase_cousins || root_with_onto ?
5292 "onto" : "[new root]");
5293 else {
5294 const char *to = NULL;
5296 entry = oidmap_get(&state.commit2label,
5297 &commit->object.oid);
5298 if (entry)
5299 to = entry->string;
5300 else if (!rebase_cousins)
5301 to = label_oid(&commit->object.oid, NULL,
5302 &state);
5304 if (!to || !strcmp(to, "onto"))
5305 strbuf_addf(out, "%s onto\n", cmd_reset);
5306 else {
5307 strbuf_reset(&oneline);
5308 pretty_print_commit(pp, commit, &oneline);
5309 strbuf_addf(out, "%s %s # %s\n",
5310 cmd_reset, to, oneline.buf);
5314 for (iter2 = list; iter2; iter2 = iter2->next) {
5315 struct object_id *oid = &iter2->item->object.oid;
5316 entry = oidmap_get(&commit2todo, oid);
5317 /* only show if not already upstream */
5318 if (entry)
5319 strbuf_addf(out, "%s\n", entry->string);
5320 entry = oidmap_get(&state.commit2label, oid);
5321 if (entry)
5322 strbuf_addf(out, "%s %s\n",
5323 cmd_label, entry->string);
5324 oidset_insert(&shown, oid);
5327 free_commit_list(list);
5330 free_commit_list(commits);
5331 free_commit_list(tips);
5333 strbuf_release(&label);
5334 strbuf_release(&oneline);
5335 strbuf_release(&buf);
5337 oidmap_free(&commit2todo, 1);
5338 oidmap_free(&state.commit2label, 1);
5339 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5340 strbuf_release(&state.buf);
5342 return 0;
5345 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5346 const char **argv, unsigned flags)
5348 char *format = NULL;
5349 struct pretty_print_context pp = {0};
5350 struct rev_info revs;
5351 struct commit *commit;
5352 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5353 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5354 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5355 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5356 int skipped_commit = 0;
5357 int ret = 0;
5359 repo_init_revisions(r, &revs, NULL);
5360 revs.verbose_header = 1;
5361 if (!rebase_merges)
5362 revs.max_parents = 1;
5363 revs.cherry_mark = !reapply_cherry_picks;
5364 revs.limited = 1;
5365 revs.reverse = 1;
5366 revs.right_only = 1;
5367 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5368 revs.topo_order = 1;
5370 revs.pretty_given = 1;
5371 git_config_get_string("rebase.instructionFormat", &format);
5372 if (!format || !*format) {
5373 free(format);
5374 format = xstrdup("%s");
5376 get_commit_format(format, &revs);
5377 free(format);
5378 pp.fmt = revs.commit_format;
5379 pp.output_encoding = get_log_output_encoding();
5381 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5382 ret = error(_("make_script: unhandled options"));
5383 goto cleanup;
5386 if (prepare_revision_walk(&revs) < 0) {
5387 ret = error(_("make_script: error preparing revisions"));
5388 goto cleanup;
5391 if (rebase_merges) {
5392 ret = make_script_with_merges(&pp, &revs, out, flags);
5393 goto cleanup;
5396 while ((commit = get_revision(&revs))) {
5397 int is_empty = is_original_commit_empty(commit);
5399 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5400 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5401 warning(_("skipped previously applied commit %s"),
5402 short_commit_name(commit));
5403 skipped_commit = 1;
5404 continue;
5406 if (is_empty && !keep_empty)
5407 continue;
5408 strbuf_addf(out, "%s %s ", insn,
5409 oid_to_hex(&commit->object.oid));
5410 pretty_print_commit(&pp, commit, out);
5411 if (is_empty)
5412 strbuf_addf(out, " %c empty", comment_line_char);
5413 strbuf_addch(out, '\n');
5415 if (skipped_commit)
5416 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5417 _("use --reapply-cherry-picks to include skipped commits"));
5418 cleanup:
5419 release_revisions(&revs);
5420 return ret;
5424 * Add commands after pick and (series of) squash/fixup commands
5425 * in the todo list.
5427 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5428 struct string_list *commands)
5430 struct strbuf *buf = &todo_list->buf;
5431 size_t base_offset = buf->len;
5432 int i, insert, nr = 0, alloc = 0;
5433 struct todo_item *items = NULL, *base_items = NULL;
5435 CALLOC_ARRAY(base_items, commands->nr);
5436 for (i = 0; i < commands->nr; i++) {
5437 size_t command_len = strlen(commands->items[i].string);
5439 strbuf_addstr(buf, commands->items[i].string);
5440 strbuf_addch(buf, '\n');
5442 base_items[i].command = TODO_EXEC;
5443 base_items[i].offset_in_buf = base_offset;
5444 base_items[i].arg_offset = base_offset + strlen("exec ");
5445 base_items[i].arg_len = command_len - strlen("exec ");
5447 base_offset += command_len + 1;
5451 * Insert <commands> after every pick. Here, fixup/squash chains
5452 * are considered part of the pick, so we insert the commands *after*
5453 * those chains if there are any.
5455 * As we insert the exec commands immediately after rearranging
5456 * any fixups and before the user edits the list, a fixup chain
5457 * can never contain comments (any comments are empty picks that
5458 * have been commented out because the user did not specify
5459 * --keep-empty). So, it is safe to insert an exec command
5460 * without looking at the command following a comment.
5462 insert = 0;
5463 for (i = 0; i < todo_list->nr; i++) {
5464 enum todo_command command = todo_list->items[i].command;
5465 if (insert && !is_fixup(command)) {
5466 ALLOC_GROW(items, nr + commands->nr, alloc);
5467 COPY_ARRAY(items + nr, base_items, commands->nr);
5468 nr += commands->nr;
5470 insert = 0;
5473 ALLOC_GROW(items, nr + 1, alloc);
5474 items[nr++] = todo_list->items[i];
5476 if (command == TODO_PICK || command == TODO_MERGE)
5477 insert = 1;
5480 /* insert or append final <commands> */
5481 if (insert) {
5482 ALLOC_GROW(items, nr + commands->nr, alloc);
5483 COPY_ARRAY(items + nr, base_items, commands->nr);
5484 nr += commands->nr;
5487 free(base_items);
5488 FREE_AND_NULL(todo_list->items);
5489 todo_list->items = items;
5490 todo_list->nr = nr;
5491 todo_list->alloc = alloc;
5494 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5495 struct strbuf *buf, int num, unsigned flags)
5497 struct todo_item *item;
5498 int i, max = todo_list->nr;
5500 if (num > 0 && num < max)
5501 max = num;
5503 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5504 char cmd;
5506 /* if the item is not a command write it and continue */
5507 if (item->command >= TODO_COMMENT) {
5508 strbuf_addf(buf, "%.*s\n", item->arg_len,
5509 todo_item_get_arg(todo_list, item));
5510 continue;
5513 /* add command to the buffer */
5514 cmd = command_to_char(item->command);
5515 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5516 strbuf_addch(buf, cmd);
5517 else
5518 strbuf_addstr(buf, command_to_string(item->command));
5520 /* add commit id */
5521 if (item->commit) {
5522 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5523 short_commit_name(item->commit) :
5524 oid_to_hex(&item->commit->object.oid);
5526 if (item->command == TODO_FIXUP) {
5527 if (item->flags & TODO_EDIT_FIXUP_MSG)
5528 strbuf_addstr(buf, " -c");
5529 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5530 strbuf_addstr(buf, " -C");
5534 if (item->command == TODO_MERGE) {
5535 if (item->flags & TODO_EDIT_MERGE_MSG)
5536 strbuf_addstr(buf, " -c");
5537 else
5538 strbuf_addstr(buf, " -C");
5541 strbuf_addf(buf, " %s", oid);
5544 /* add all the rest */
5545 if (!item->arg_len)
5546 strbuf_addch(buf, '\n');
5547 else
5548 strbuf_addf(buf, " %.*s\n", item->arg_len,
5549 todo_item_get_arg(todo_list, item));
5553 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5554 const char *file, const char *shortrevisions,
5555 const char *shortonto, int num, unsigned flags)
5557 int res;
5558 struct strbuf buf = STRBUF_INIT;
5560 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5561 if (flags & TODO_LIST_APPEND_TODO_HELP)
5562 append_todo_help(count_commands(todo_list),
5563 shortrevisions, shortonto, &buf);
5565 res = write_message(buf.buf, buf.len, file, 0);
5566 strbuf_release(&buf);
5568 return res;
5571 /* skip picking commits whose parents are unchanged */
5572 static int skip_unnecessary_picks(struct repository *r,
5573 struct todo_list *todo_list,
5574 struct object_id *base_oid)
5576 struct object_id *parent_oid;
5577 int i;
5579 for (i = 0; i < todo_list->nr; i++) {
5580 struct todo_item *item = todo_list->items + i;
5582 if (item->command >= TODO_NOOP)
5583 continue;
5584 if (item->command != TODO_PICK)
5585 break;
5586 if (parse_commit(item->commit)) {
5587 return error(_("could not parse commit '%s'"),
5588 oid_to_hex(&item->commit->object.oid));
5590 if (!item->commit->parents)
5591 break; /* root commit */
5592 if (item->commit->parents->next)
5593 break; /* merge commit */
5594 parent_oid = &item->commit->parents->item->object.oid;
5595 if (!oideq(parent_oid, base_oid))
5596 break;
5597 oidcpy(base_oid, &item->commit->object.oid);
5599 if (i > 0) {
5600 const char *done_path = rebase_path_done();
5602 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5603 error_errno(_("could not write to '%s'"), done_path);
5604 return -1;
5607 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5608 todo_list->nr -= i;
5609 todo_list->current = 0;
5610 todo_list->done_nr += i;
5612 if (is_fixup(peek_command(todo_list, 0)))
5613 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5616 return 0;
5619 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5620 const char *shortrevisions, const char *onto_name,
5621 struct commit *onto, const struct object_id *orig_head,
5622 struct string_list *commands, unsigned autosquash,
5623 struct todo_list *todo_list)
5625 char shortonto[GIT_MAX_HEXSZ + 1];
5626 const char *todo_file = rebase_path_todo();
5627 struct todo_list new_todo = TODO_LIST_INIT;
5628 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5629 struct object_id oid = onto->object.oid;
5630 int res;
5632 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5634 if (buf->len == 0) {
5635 struct todo_item *item = append_new_todo(todo_list);
5636 item->command = TODO_NOOP;
5637 item->commit = NULL;
5638 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5641 if (autosquash && todo_list_rearrange_squash(todo_list))
5642 return -1;
5644 if (commands->nr)
5645 todo_list_add_exec_commands(todo_list, commands);
5647 if (count_commands(todo_list) == 0) {
5648 apply_autostash(rebase_path_autostash());
5649 sequencer_remove_state(opts);
5651 return error(_("nothing to do"));
5654 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5655 shortonto, flags);
5656 if (res == -1)
5657 return -1;
5658 else if (res == -2) {
5659 apply_autostash(rebase_path_autostash());
5660 sequencer_remove_state(opts);
5662 return -1;
5663 } else if (res == -3) {
5664 apply_autostash(rebase_path_autostash());
5665 sequencer_remove_state(opts);
5666 todo_list_release(&new_todo);
5668 return error(_("nothing to do"));
5669 } else if (res == -4) {
5670 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5671 todo_list_release(&new_todo);
5673 return -1;
5676 /* Expand the commit IDs */
5677 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5678 strbuf_swap(&new_todo.buf, &buf2);
5679 strbuf_release(&buf2);
5680 new_todo.total_nr -= new_todo.nr;
5681 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5682 BUG("invalid todo list after expanding IDs:\n%s",
5683 new_todo.buf.buf);
5685 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5686 todo_list_release(&new_todo);
5687 return error(_("could not skip unnecessary pick commands"));
5690 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5691 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5692 todo_list_release(&new_todo);
5693 return error_errno(_("could not write '%s'"), todo_file);
5696 res = -1;
5698 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5699 goto cleanup;
5701 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5702 goto cleanup;
5704 todo_list_write_total_nr(&new_todo);
5705 res = pick_commits(r, &new_todo, opts);
5707 cleanup:
5708 todo_list_release(&new_todo);
5710 return res;
5713 struct subject2item_entry {
5714 struct hashmap_entry entry;
5715 int i;
5716 char subject[FLEX_ARRAY];
5719 static int subject2item_cmp(const void *fndata,
5720 const struct hashmap_entry *eptr,
5721 const struct hashmap_entry *entry_or_key,
5722 const void *key)
5724 const struct subject2item_entry *a, *b;
5726 a = container_of(eptr, const struct subject2item_entry, entry);
5727 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5729 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5732 define_commit_slab(commit_todo_item, struct todo_item *);
5734 static int skip_fixupish(const char *subject, const char **p) {
5735 return skip_prefix(subject, "fixup! ", p) ||
5736 skip_prefix(subject, "amend! ", p) ||
5737 skip_prefix(subject, "squash! ", p);
5741 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5742 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5743 * after the former, and change "pick" to "fixup"/"squash".
5745 * Note that if the config has specified a custom instruction format, each log
5746 * message will have to be retrieved from the commit (as the oneline in the
5747 * script cannot be trusted) in order to normalize the autosquash arrangement.
5749 int todo_list_rearrange_squash(struct todo_list *todo_list)
5751 struct hashmap subject2item;
5752 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5753 char **subjects;
5754 struct commit_todo_item commit_todo;
5755 struct todo_item *items = NULL;
5757 init_commit_todo_item(&commit_todo);
5759 * The hashmap maps onelines to the respective todo list index.
5761 * If any items need to be rearranged, the next[i] value will indicate
5762 * which item was moved directly after the i'th.
5764 * In that case, last[i] will indicate the index of the latest item to
5765 * be moved to appear after the i'th.
5767 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5768 ALLOC_ARRAY(next, todo_list->nr);
5769 ALLOC_ARRAY(tail, todo_list->nr);
5770 ALLOC_ARRAY(subjects, todo_list->nr);
5771 for (i = 0; i < todo_list->nr; i++) {
5772 struct strbuf buf = STRBUF_INIT;
5773 struct todo_item *item = todo_list->items + i;
5774 const char *commit_buffer, *subject, *p;
5775 size_t subject_len;
5776 int i2 = -1;
5777 struct subject2item_entry *entry;
5779 next[i] = tail[i] = -1;
5780 if (!item->commit || item->command == TODO_DROP) {
5781 subjects[i] = NULL;
5782 continue;
5785 if (is_fixup(item->command)) {
5786 clear_commit_todo_item(&commit_todo);
5787 return error(_("the script was already rearranged."));
5790 *commit_todo_item_at(&commit_todo, item->commit) = item;
5792 parse_commit(item->commit);
5793 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5794 find_commit_subject(commit_buffer, &subject);
5795 format_subject(&buf, subject, " ");
5796 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5797 unuse_commit_buffer(item->commit, commit_buffer);
5798 if (skip_fixupish(subject, &p)) {
5799 struct commit *commit2;
5801 for (;;) {
5802 while (isspace(*p))
5803 p++;
5804 if (!skip_fixupish(p, &p))
5805 break;
5808 entry = hashmap_get_entry_from_hash(&subject2item,
5809 strhash(p), p,
5810 struct subject2item_entry,
5811 entry);
5812 if (entry)
5813 /* found by title */
5814 i2 = entry->i;
5815 else if (!strchr(p, ' ') &&
5816 (commit2 =
5817 lookup_commit_reference_by_name(p)) &&
5818 *commit_todo_item_at(&commit_todo, commit2))
5819 /* found by commit name */
5820 i2 = *commit_todo_item_at(&commit_todo, commit2)
5821 - todo_list->items;
5822 else {
5823 /* copy can be a prefix of the commit subject */
5824 for (i2 = 0; i2 < i; i2++)
5825 if (subjects[i2] &&
5826 starts_with(subjects[i2], p))
5827 break;
5828 if (i2 == i)
5829 i2 = -1;
5832 if (i2 >= 0) {
5833 rearranged = 1;
5834 if (starts_with(subject, "fixup!")) {
5835 todo_list->items[i].command = TODO_FIXUP;
5836 } else if (starts_with(subject, "amend!")) {
5837 todo_list->items[i].command = TODO_FIXUP;
5838 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5839 } else {
5840 todo_list->items[i].command = TODO_SQUASH;
5842 if (tail[i2] < 0) {
5843 next[i] = next[i2];
5844 next[i2] = i;
5845 } else {
5846 next[i] = next[tail[i2]];
5847 next[tail[i2]] = i;
5849 tail[i2] = i;
5850 } else if (!hashmap_get_from_hash(&subject2item,
5851 strhash(subject), subject)) {
5852 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5853 entry->i = i;
5854 hashmap_entry_init(&entry->entry,
5855 strhash(entry->subject));
5856 hashmap_put(&subject2item, &entry->entry);
5860 if (rearranged) {
5861 for (i = 0; i < todo_list->nr; i++) {
5862 enum todo_command command = todo_list->items[i].command;
5863 int cur = i;
5866 * Initially, all commands are 'pick's. If it is a
5867 * fixup or a squash now, we have rearranged it.
5869 if (is_fixup(command))
5870 continue;
5872 while (cur >= 0) {
5873 ALLOC_GROW(items, nr + 1, alloc);
5874 items[nr++] = todo_list->items[cur];
5875 cur = next[cur];
5879 FREE_AND_NULL(todo_list->items);
5880 todo_list->items = items;
5881 todo_list->nr = nr;
5882 todo_list->alloc = alloc;
5885 free(next);
5886 free(tail);
5887 for (i = 0; i < todo_list->nr; i++)
5888 free(subjects[i]);
5889 free(subjects);
5890 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5892 clear_commit_todo_item(&commit_todo);
5894 return 0;
5897 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5899 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5900 struct object_id cherry_pick_head, rebase_head;
5902 if (file_exists(git_path_seq_dir()))
5903 *whence = FROM_CHERRY_PICK_MULTI;
5904 if (file_exists(rebase_path()) &&
5905 !get_oid("REBASE_HEAD", &rebase_head) &&
5906 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5907 oideq(&rebase_head, &cherry_pick_head))
5908 *whence = FROM_REBASE_PICK;
5909 else
5910 *whence = FROM_CHERRY_PICK_SINGLE;
5912 return 1;
5915 return 0;