refs API: make resolve_ref_unsafe() not set errno
[git/debian.git] / sequencer.c
blob1223dc2d2bf25622c35c21c7d639635dc46e530a
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) && !(!defmsg && (flags & AMEND_MSG)) &&
1001 read_env_script(&cmd.env_array)) {
1002 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1004 return error(_(staged_changes_advice),
1005 gpg_opt, gpg_opt);
1008 if (opts->committer_date_is_author_date)
1009 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1010 opts->ignore_date ?
1011 "" :
1012 author_date_from_env_array(&cmd.env_array));
1013 if (opts->ignore_date)
1014 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1016 strvec_push(&cmd.args, "commit");
1018 if (!(flags & VERIFY_MSG))
1019 strvec_push(&cmd.args, "-n");
1020 if ((flags & AMEND_MSG))
1021 strvec_push(&cmd.args, "--amend");
1022 if (opts->gpg_sign)
1023 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1024 else
1025 strvec_push(&cmd.args, "--no-gpg-sign");
1026 if (defmsg)
1027 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1028 else if (!(flags & EDIT_MSG))
1029 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1030 if ((flags & CLEANUP_MSG))
1031 strvec_push(&cmd.args, "--cleanup=strip");
1032 if ((flags & VERBATIM_MSG))
1033 strvec_push(&cmd.args, "--cleanup=verbatim");
1034 if ((flags & EDIT_MSG))
1035 strvec_push(&cmd.args, "-e");
1036 else if (!(flags & CLEANUP_MSG) &&
1037 !opts->signoff && !opts->record_origin &&
1038 !opts->explicit_cleanup)
1039 strvec_push(&cmd.args, "--cleanup=verbatim");
1041 if ((flags & ALLOW_EMPTY))
1042 strvec_push(&cmd.args, "--allow-empty");
1044 if (!(flags & EDIT_MSG))
1045 strvec_push(&cmd.args, "--allow-empty-message");
1047 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1048 return run_command_silent_on_success(&cmd);
1049 else
1050 return run_command(&cmd);
1053 static int rest_is_empty(const struct strbuf *sb, int start)
1055 int i, eol;
1056 const char *nl;
1058 /* Check if the rest is just whitespace and Signed-off-by's. */
1059 for (i = start; i < sb->len; i++) {
1060 nl = memchr(sb->buf + i, '\n', sb->len - i);
1061 if (nl)
1062 eol = nl - sb->buf;
1063 else
1064 eol = sb->len;
1066 if (strlen(sign_off_header) <= eol - i &&
1067 starts_with(sb->buf + i, sign_off_header)) {
1068 i = eol;
1069 continue;
1071 while (i < eol)
1072 if (!isspace(sb->buf[i++]))
1073 return 0;
1076 return 1;
1079 void cleanup_message(struct strbuf *msgbuf,
1080 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1082 if (verbose || /* Truncate the message just before the diff, if any. */
1083 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1084 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1085 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1086 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1090 * Find out if the message in the strbuf contains only whitespace and
1091 * Signed-off-by lines.
1093 int message_is_empty(const struct strbuf *sb,
1094 enum commit_msg_cleanup_mode cleanup_mode)
1096 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1097 return 0;
1098 return rest_is_empty(sb, 0);
1102 * See if the user edited the message in the editor or left what
1103 * was in the template intact
1105 int template_untouched(const struct strbuf *sb, const char *template_file,
1106 enum commit_msg_cleanup_mode cleanup_mode)
1108 struct strbuf tmpl = STRBUF_INIT;
1109 const char *start;
1111 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1112 return 0;
1114 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1115 return 0;
1117 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1118 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1119 start = sb->buf;
1120 strbuf_release(&tmpl);
1121 return rest_is_empty(sb, start - sb->buf);
1124 int update_head_with_reflog(const struct commit *old_head,
1125 const struct object_id *new_head,
1126 const char *action, const struct strbuf *msg,
1127 struct strbuf *err)
1129 struct ref_transaction *transaction;
1130 struct strbuf sb = STRBUF_INIT;
1131 const char *nl;
1132 int ret = 0;
1134 if (action) {
1135 strbuf_addstr(&sb, action);
1136 strbuf_addstr(&sb, ": ");
1139 nl = strchr(msg->buf, '\n');
1140 if (nl) {
1141 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1142 } else {
1143 strbuf_addbuf(&sb, msg);
1144 strbuf_addch(&sb, '\n');
1147 transaction = ref_transaction_begin(err);
1148 if (!transaction ||
1149 ref_transaction_update(transaction, "HEAD", new_head,
1150 old_head ? &old_head->object.oid : null_oid(),
1151 0, sb.buf, err) ||
1152 ref_transaction_commit(transaction, err)) {
1153 ret = -1;
1155 ref_transaction_free(transaction);
1156 strbuf_release(&sb);
1158 return ret;
1161 static int run_rewrite_hook(const struct object_id *oldoid,
1162 const struct object_id *newoid)
1164 struct child_process proc = CHILD_PROCESS_INIT;
1165 const char *argv[3];
1166 int code;
1167 struct strbuf sb = STRBUF_INIT;
1169 argv[0] = find_hook("post-rewrite");
1170 if (!argv[0])
1171 return 0;
1173 argv[1] = "amend";
1174 argv[2] = NULL;
1176 proc.argv = argv;
1177 proc.in = -1;
1178 proc.stdout_to_stderr = 1;
1179 proc.trace2_hook_name = "post-rewrite";
1181 code = start_command(&proc);
1182 if (code)
1183 return code;
1184 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1185 sigchain_push(SIGPIPE, SIG_IGN);
1186 write_in_full(proc.in, sb.buf, sb.len);
1187 close(proc.in);
1188 strbuf_release(&sb);
1189 sigchain_pop(SIGPIPE);
1190 return finish_command(&proc);
1193 void commit_post_rewrite(struct repository *r,
1194 const struct commit *old_head,
1195 const struct object_id *new_head)
1197 struct notes_rewrite_cfg *cfg;
1199 cfg = init_copy_notes_for_rewrite("amend");
1200 if (cfg) {
1201 /* we are amending, so old_head is not NULL */
1202 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1203 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1205 run_rewrite_hook(&old_head->object.oid, new_head);
1208 static int run_prepare_commit_msg_hook(struct repository *r,
1209 struct strbuf *msg,
1210 const char *commit)
1212 int ret = 0;
1213 const char *name, *arg1 = NULL, *arg2 = NULL;
1215 name = git_path_commit_editmsg();
1216 if (write_message(msg->buf, msg->len, name, 0))
1217 return -1;
1219 if (commit) {
1220 arg1 = "commit";
1221 arg2 = commit;
1222 } else {
1223 arg1 = "message";
1225 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1226 arg1, arg2, NULL))
1227 ret = error(_("'prepare-commit-msg' hook failed"));
1229 return ret;
1232 static const char implicit_ident_advice_noconfig[] =
1233 N_("Your name and email address were configured automatically based\n"
1234 "on your username and hostname. Please check that they are accurate.\n"
1235 "You can suppress this message by setting them explicitly. Run the\n"
1236 "following command and follow the instructions in your editor to edit\n"
1237 "your configuration file:\n"
1238 "\n"
1239 " git config --global --edit\n"
1240 "\n"
1241 "After doing this, you may fix the identity used for this commit with:\n"
1242 "\n"
1243 " git commit --amend --reset-author\n");
1245 static const char implicit_ident_advice_config[] =
1246 N_("Your name and email address were configured automatically based\n"
1247 "on your username and hostname. Please check that they are accurate.\n"
1248 "You can suppress this message by setting them explicitly:\n"
1249 "\n"
1250 " git config --global user.name \"Your Name\"\n"
1251 " git config --global user.email you@example.com\n"
1252 "\n"
1253 "After doing this, you may fix the identity used for this commit with:\n"
1254 "\n"
1255 " git commit --amend --reset-author\n");
1257 static const char *implicit_ident_advice(void)
1259 char *user_config = interpolate_path("~/.gitconfig", 0);
1260 char *xdg_config = xdg_config_home("config");
1261 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1263 free(user_config);
1264 free(xdg_config);
1266 if (config_exists)
1267 return _(implicit_ident_advice_config);
1268 else
1269 return _(implicit_ident_advice_noconfig);
1273 void print_commit_summary(struct repository *r,
1274 const char *prefix,
1275 const struct object_id *oid,
1276 unsigned int flags)
1278 struct rev_info rev;
1279 struct commit *commit;
1280 struct strbuf format = STRBUF_INIT;
1281 const char *head;
1282 struct pretty_print_context pctx = {0};
1283 struct strbuf author_ident = STRBUF_INIT;
1284 struct strbuf committer_ident = STRBUF_INIT;
1285 struct ref_store *refs;
1286 int resolve_errno;
1288 commit = lookup_commit(r, oid);
1289 if (!commit)
1290 die(_("couldn't look up newly created commit"));
1291 if (parse_commit(commit))
1292 die(_("could not parse newly created commit"));
1294 strbuf_addstr(&format, "format:%h] %s");
1296 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1297 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1298 if (strbuf_cmp(&author_ident, &committer_ident)) {
1299 strbuf_addstr(&format, "\n Author: ");
1300 strbuf_addbuf_percentquote(&format, &author_ident);
1302 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1303 struct strbuf date = STRBUF_INIT;
1305 format_commit_message(commit, "%ad", &date, &pctx);
1306 strbuf_addstr(&format, "\n Date: ");
1307 strbuf_addbuf_percentquote(&format, &date);
1308 strbuf_release(&date);
1310 if (!committer_ident_sufficiently_given()) {
1311 strbuf_addstr(&format, "\n Committer: ");
1312 strbuf_addbuf_percentquote(&format, &committer_ident);
1313 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1314 strbuf_addch(&format, '\n');
1315 strbuf_addstr(&format, implicit_ident_advice());
1318 strbuf_release(&author_ident);
1319 strbuf_release(&committer_ident);
1321 repo_init_revisions(r, &rev, prefix);
1322 setup_revisions(0, NULL, &rev, NULL);
1324 rev.diff = 1;
1325 rev.diffopt.output_format =
1326 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1328 rev.verbose_header = 1;
1329 rev.show_root_diff = 1;
1330 get_commit_format(format.buf, &rev);
1331 rev.always_show_header = 0;
1332 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1333 rev.diffopt.break_opt = 0;
1334 diff_setup_done(&rev.diffopt);
1336 refs = get_main_ref_store(the_repository);
1337 head = refs_werrres_ref_unsafe(refs, "HEAD", 0, NULL, NULL,
1338 &resolve_errno);
1339 if (!head) {
1340 errno = resolve_errno;
1341 die_errno(_("unable to resolve HEAD after creating commit"));
1343 if (!strcmp(head, "HEAD"))
1344 head = _("detached HEAD");
1345 else
1346 skip_prefix(head, "refs/heads/", &head);
1347 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1348 _(" (root-commit)") : "");
1350 if (!log_tree_commit(&rev, commit)) {
1351 rev.always_show_header = 1;
1352 rev.use_terminator = 1;
1353 log_tree_commit(&rev, commit);
1356 strbuf_release(&format);
1359 static int parse_head(struct repository *r, struct commit **head)
1361 struct commit *current_head;
1362 struct object_id oid;
1364 if (get_oid("HEAD", &oid)) {
1365 current_head = NULL;
1366 } else {
1367 current_head = lookup_commit_reference(r, &oid);
1368 if (!current_head)
1369 return error(_("could not parse HEAD"));
1370 if (!oideq(&oid, &current_head->object.oid)) {
1371 warning(_("HEAD %s is not a commit!"),
1372 oid_to_hex(&oid));
1374 if (parse_commit(current_head))
1375 return error(_("could not parse HEAD commit"));
1377 *head = current_head;
1379 return 0;
1383 * Try to commit without forking 'git commit'. In some cases we need
1384 * to run 'git commit' to display an error message
1386 * Returns:
1387 * -1 - error unable to commit
1388 * 0 - success
1389 * 1 - run 'git commit'
1391 static int try_to_commit(struct repository *r,
1392 struct strbuf *msg, const char *author,
1393 struct replay_opts *opts, unsigned int flags,
1394 struct object_id *oid)
1396 struct object_id tree;
1397 struct commit *current_head = NULL;
1398 struct commit_list *parents = NULL;
1399 struct commit_extra_header *extra = NULL;
1400 struct strbuf err = STRBUF_INIT;
1401 struct strbuf commit_msg = STRBUF_INIT;
1402 char *amend_author = NULL;
1403 const char *committer = NULL;
1404 const char *hook_commit = NULL;
1405 enum commit_msg_cleanup_mode cleanup;
1406 int res = 0;
1408 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1409 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1411 if (parse_head(r, &current_head))
1412 return -1;
1414 if (flags & AMEND_MSG) {
1415 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1416 const char *out_enc = get_commit_output_encoding();
1417 const char *message = logmsg_reencode(current_head, NULL,
1418 out_enc);
1420 if (!msg) {
1421 const char *orig_message = NULL;
1423 find_commit_subject(message, &orig_message);
1424 msg = &commit_msg;
1425 strbuf_addstr(msg, orig_message);
1426 hook_commit = "HEAD";
1428 author = amend_author = get_author(message);
1429 unuse_commit_buffer(current_head, message);
1430 if (!author) {
1431 res = error(_("unable to parse commit author"));
1432 goto out;
1434 parents = copy_commit_list(current_head->parents);
1435 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1436 } else if (current_head &&
1437 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1438 commit_list_insert(current_head, &parents);
1441 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1442 res = error(_("git write-tree failed to write a tree"));
1443 goto out;
1446 if (!(flags & ALLOW_EMPTY)) {
1447 struct commit *first_parent = current_head;
1449 if (flags & AMEND_MSG) {
1450 if (current_head->parents) {
1451 first_parent = current_head->parents->item;
1452 if (repo_parse_commit(r, first_parent)) {
1453 res = error(_("could not parse HEAD commit"));
1454 goto out;
1456 } else {
1457 first_parent = NULL;
1460 if (oideq(first_parent
1461 ? get_commit_tree_oid(first_parent)
1462 : the_hash_algo->empty_tree,
1463 &tree)) {
1464 res = 1; /* run 'git commit' to display error message */
1465 goto out;
1469 if (hook_exists("prepare-commit-msg")) {
1470 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1471 if (res)
1472 goto out;
1473 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1474 2048) < 0) {
1475 res = error_errno(_("unable to read commit message "
1476 "from '%s'"),
1477 git_path_commit_editmsg());
1478 goto out;
1480 msg = &commit_msg;
1483 if (flags & CLEANUP_MSG)
1484 cleanup = COMMIT_MSG_CLEANUP_ALL;
1485 else if (flags & VERBATIM_MSG)
1486 cleanup = COMMIT_MSG_CLEANUP_NONE;
1487 else if ((opts->signoff || opts->record_origin) &&
1488 !opts->explicit_cleanup)
1489 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1490 else
1491 cleanup = opts->default_msg_cleanup;
1493 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1494 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1495 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1496 res = 1; /* run 'git commit' to display error message */
1497 goto out;
1500 if (opts->committer_date_is_author_date) {
1501 struct ident_split id;
1502 struct strbuf date = STRBUF_INIT;
1504 if (!opts->ignore_date) {
1505 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1506 res = error(_("invalid author identity '%s'"),
1507 author);
1508 goto out;
1510 if (!id.date_begin) {
1511 res = error(_(
1512 "corrupt author: missing date information"));
1513 goto out;
1515 strbuf_addf(&date, "@%.*s %.*s",
1516 (int)(id.date_end - id.date_begin),
1517 id.date_begin,
1518 (int)(id.tz_end - id.tz_begin),
1519 id.tz_begin);
1520 } else {
1521 reset_ident_date();
1523 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1524 getenv("GIT_COMMITTER_EMAIL"),
1525 WANT_COMMITTER_IDENT,
1526 opts->ignore_date ? NULL : date.buf,
1527 IDENT_STRICT);
1528 strbuf_release(&date);
1529 } else {
1530 reset_ident_date();
1533 if (opts->ignore_date) {
1534 struct ident_split id;
1535 char *name, *email;
1537 if (split_ident_line(&id, author, strlen(author)) < 0) {
1538 error(_("invalid author identity '%s'"), author);
1539 goto out;
1541 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1542 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1543 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1544 IDENT_STRICT);
1545 free(name);
1546 free(email);
1549 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1550 author, committer, opts->gpg_sign, extra)) {
1551 res = error(_("failed to write commit object"));
1552 goto out;
1555 if (update_head_with_reflog(current_head, oid,
1556 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1557 res = error("%s", err.buf);
1558 goto out;
1561 run_commit_hook(0, r->index_file, "post-commit", NULL);
1562 if (flags & AMEND_MSG)
1563 commit_post_rewrite(r, current_head, oid);
1565 out:
1566 free_commit_extra_headers(extra);
1567 strbuf_release(&err);
1568 strbuf_release(&commit_msg);
1569 free(amend_author);
1571 return res;
1574 static int write_rebase_head(struct object_id *oid)
1576 if (update_ref("rebase", "REBASE_HEAD", oid,
1577 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1578 return error(_("could not update %s"), "REBASE_HEAD");
1580 return 0;
1583 static int do_commit(struct repository *r,
1584 const char *msg_file, const char *author,
1585 struct replay_opts *opts, unsigned int flags,
1586 struct object_id *oid)
1588 int res = 1;
1590 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1591 struct object_id oid;
1592 struct strbuf sb = STRBUF_INIT;
1594 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1595 return error_errno(_("unable to read commit message "
1596 "from '%s'"),
1597 msg_file);
1599 res = try_to_commit(r, msg_file ? &sb : NULL,
1600 author, opts, flags, &oid);
1601 strbuf_release(&sb);
1602 if (!res) {
1603 refs_delete_ref(get_main_ref_store(r), "",
1604 "CHERRY_PICK_HEAD", NULL, 0);
1605 unlink(git_path_merge_msg(r));
1606 if (!is_rebase_i(opts))
1607 print_commit_summary(r, NULL, &oid,
1608 SUMMARY_SHOW_AUTHOR_DATE);
1609 return res;
1612 if (res == 1) {
1613 if (is_rebase_i(opts) && oid)
1614 if (write_rebase_head(oid))
1615 return -1;
1616 return run_git_commit(msg_file, opts, flags);
1619 return res;
1622 static int is_original_commit_empty(struct commit *commit)
1624 const struct object_id *ptree_oid;
1626 if (parse_commit(commit))
1627 return error(_("could not parse commit %s"),
1628 oid_to_hex(&commit->object.oid));
1629 if (commit->parents) {
1630 struct commit *parent = commit->parents->item;
1631 if (parse_commit(parent))
1632 return error(_("could not parse parent commit %s"),
1633 oid_to_hex(&parent->object.oid));
1634 ptree_oid = get_commit_tree_oid(parent);
1635 } else {
1636 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1639 return oideq(ptree_oid, get_commit_tree_oid(commit));
1643 * Should empty commits be allowed? Return status:
1644 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1645 * 0: Halt on empty commit
1646 * 1: Allow empty commit
1647 * 2: Drop empty commit
1649 static int allow_empty(struct repository *r,
1650 struct replay_opts *opts,
1651 struct commit *commit)
1653 int index_unchanged, originally_empty;
1656 * Four cases:
1658 * (1) we do not allow empty at all and error out.
1660 * (2) we allow ones that were initially empty, and
1661 * just drop the ones that become empty
1663 * (3) we allow ones that were initially empty, but
1664 * halt for the ones that become empty;
1666 * (4) we allow both.
1668 if (!opts->allow_empty)
1669 return 0; /* let "git commit" barf as necessary */
1671 index_unchanged = is_index_unchanged(r);
1672 if (index_unchanged < 0)
1673 return index_unchanged;
1674 if (!index_unchanged)
1675 return 0; /* we do not have to say --allow-empty */
1677 if (opts->keep_redundant_commits)
1678 return 1;
1680 originally_empty = is_original_commit_empty(commit);
1681 if (originally_empty < 0)
1682 return originally_empty;
1683 if (originally_empty)
1684 return 1;
1685 else if (opts->drop_redundant_commits)
1686 return 2;
1687 else
1688 return 0;
1691 static struct {
1692 char c;
1693 const char *str;
1694 } todo_command_info[] = {
1695 { 'p', "pick" },
1696 { 0, "revert" },
1697 { 'e', "edit" },
1698 { 'r', "reword" },
1699 { 'f', "fixup" },
1700 { 's', "squash" },
1701 { 'x', "exec" },
1702 { 'b', "break" },
1703 { 'l', "label" },
1704 { 't', "reset" },
1705 { 'm', "merge" },
1706 { 0, "noop" },
1707 { 'd', "drop" },
1708 { 0, NULL }
1711 static const char *command_to_string(const enum todo_command command)
1713 if (command < TODO_COMMENT)
1714 return todo_command_info[command].str;
1715 die(_("unknown command: %d"), command);
1718 static char command_to_char(const enum todo_command command)
1720 if (command < TODO_COMMENT)
1721 return todo_command_info[command].c;
1722 return comment_line_char;
1725 static int is_noop(const enum todo_command command)
1727 return TODO_NOOP <= command;
1730 static int is_fixup(enum todo_command command)
1732 return command == TODO_FIXUP || command == TODO_SQUASH;
1735 /* Does this command create a (non-merge) commit? */
1736 static int is_pick_or_similar(enum todo_command command)
1738 switch (command) {
1739 case TODO_PICK:
1740 case TODO_REVERT:
1741 case TODO_EDIT:
1742 case TODO_REWORD:
1743 case TODO_FIXUP:
1744 case TODO_SQUASH:
1745 return 1;
1746 default:
1747 return 0;
1751 enum todo_item_flags {
1752 TODO_EDIT_MERGE_MSG = (1 << 0),
1753 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1754 TODO_EDIT_FIXUP_MSG = (1 << 2),
1757 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1758 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1759 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1760 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1761 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1763 static int is_fixup_flag(enum todo_command command, unsigned flag)
1765 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1766 (flag & TODO_EDIT_FIXUP_MSG));
1770 * Wrapper around strbuf_add_commented_lines() which avoids double
1771 * commenting commit subjects.
1773 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1775 const char *s = str;
1776 while (len > 0 && s[0] == comment_line_char) {
1777 size_t count;
1778 const char *n = memchr(s, '\n', len);
1779 if (!n)
1780 count = len;
1781 else
1782 count = n - s + 1;
1783 strbuf_add(buf, s, count);
1784 s += count;
1785 len -= count;
1787 strbuf_add_commented_lines(buf, s, len);
1790 /* Does the current fixup chain contain a squash command? */
1791 static int seen_squash(struct replay_opts *opts)
1793 return starts_with(opts->current_fixups.buf, "squash") ||
1794 strstr(opts->current_fixups.buf, "\nsquash");
1797 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1799 strbuf_setlen(buf1, 2);
1800 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1801 strbuf_addch(buf1, '\n');
1802 strbuf_setlen(buf2, 2);
1803 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1804 strbuf_addch(buf2, '\n');
1808 * Comment out any un-commented commit messages, updating the message comments
1809 * to say they will be skipped but do not comment out the empty lines that
1810 * surround commit messages and their comments.
1812 static void update_squash_message_for_fixup(struct strbuf *msg)
1814 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1815 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1816 const char *s, *start;
1817 char *orig_msg;
1818 size_t orig_msg_len;
1819 int i = 1;
1821 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1822 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1823 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1824 while (s) {
1825 const char *next;
1826 size_t off;
1827 if (skip_prefix(s, buf1.buf, &next)) {
1829 * Copy the last message, preserving the blank line
1830 * preceding the current line
1832 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1833 copy_lines(msg, start, s - start - off);
1834 if (off)
1835 strbuf_addch(msg, '\n');
1837 * The next message needs to be commented out but the
1838 * message header is already commented out so just copy
1839 * it and the blank line that follows it.
1841 strbuf_addbuf(msg, &buf2);
1842 if (*next == '\n')
1843 strbuf_addch(msg, *next++);
1844 start = s = next;
1845 copy_lines = add_commented_lines;
1846 update_comment_bufs(&buf1, &buf2, ++i);
1847 } else if (skip_prefix(s, buf2.buf, &next)) {
1848 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1849 copy_lines(msg, start, s - start - off);
1850 start = s - off;
1851 s = next;
1852 copy_lines = strbuf_add;
1853 update_comment_bufs(&buf1, &buf2, ++i);
1854 } else {
1855 s = strchr(s, '\n');
1856 if (s)
1857 s++;
1860 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1861 free(orig_msg);
1862 strbuf_release(&buf1);
1863 strbuf_release(&buf2);
1866 static int append_squash_message(struct strbuf *buf, const char *body,
1867 enum todo_command command, struct replay_opts *opts,
1868 unsigned flag)
1870 const char *fixup_msg;
1871 size_t commented_len = 0, fixup_off;
1873 * amend is non-interactive and not normally used with fixup!
1874 * or squash! commits, so only comment out those subjects when
1875 * squashing commit messages.
1877 if (starts_with(body, "amend!") ||
1878 ((command == TODO_SQUASH || seen_squash(opts)) &&
1879 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1880 commented_len = commit_subject_length(body);
1882 strbuf_addf(buf, "\n%c ", comment_line_char);
1883 strbuf_addf(buf, _(nth_commit_msg_fmt),
1884 ++opts->current_fixup_count + 1);
1885 strbuf_addstr(buf, "\n\n");
1886 strbuf_add_commented_lines(buf, body, commented_len);
1887 /* buf->buf may be reallocated so store an offset into the buffer */
1888 fixup_off = buf->len;
1889 strbuf_addstr(buf, body + commented_len);
1891 /* fixup -C after squash behaves like squash */
1892 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1894 * We're replacing the commit message so we need to
1895 * append the Signed-off-by: trailer if the user
1896 * requested '--signoff'.
1898 if (opts->signoff)
1899 append_signoff(buf, 0, 0);
1901 if ((command == TODO_FIXUP) &&
1902 (flag & TODO_REPLACE_FIXUP_MSG) &&
1903 (file_exists(rebase_path_fixup_msg()) ||
1904 !file_exists(rebase_path_squash_msg()))) {
1905 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1906 if (write_message(fixup_msg, strlen(fixup_msg),
1907 rebase_path_fixup_msg(), 0) < 0)
1908 return error(_("cannot write '%s'"),
1909 rebase_path_fixup_msg());
1910 } else {
1911 unlink(rebase_path_fixup_msg());
1913 } else {
1914 unlink(rebase_path_fixup_msg());
1917 return 0;
1920 static int update_squash_messages(struct repository *r,
1921 enum todo_command command,
1922 struct commit *commit,
1923 struct replay_opts *opts,
1924 unsigned flag)
1926 struct strbuf buf = STRBUF_INIT;
1927 int res = 0;
1928 const char *message, *body;
1929 const char *encoding = get_commit_output_encoding();
1931 if (opts->current_fixup_count > 0) {
1932 struct strbuf header = STRBUF_INIT;
1933 char *eol;
1935 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1936 return error(_("could not read '%s'"),
1937 rebase_path_squash_msg());
1939 eol = buf.buf[0] != comment_line_char ?
1940 buf.buf : strchrnul(buf.buf, '\n');
1942 strbuf_addf(&header, "%c ", comment_line_char);
1943 strbuf_addf(&header, _(combined_commit_msg_fmt),
1944 opts->current_fixup_count + 2);
1945 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1946 strbuf_release(&header);
1947 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1948 update_squash_message_for_fixup(&buf);
1949 } else {
1950 struct object_id head;
1951 struct commit *head_commit;
1952 const char *head_message, *body;
1954 if (get_oid("HEAD", &head))
1955 return error(_("need a HEAD to fixup"));
1956 if (!(head_commit = lookup_commit_reference(r, &head)))
1957 return error(_("could not read HEAD"));
1958 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1959 return error(_("could not read HEAD's commit message"));
1961 find_commit_subject(head_message, &body);
1962 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1963 rebase_path_fixup_msg(), 0) < 0) {
1964 unuse_commit_buffer(head_commit, head_message);
1965 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1967 strbuf_addf(&buf, "%c ", comment_line_char);
1968 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1969 strbuf_addf(&buf, "\n%c ", comment_line_char);
1970 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1971 _(skip_first_commit_msg_str) :
1972 _(first_commit_msg_str));
1973 strbuf_addstr(&buf, "\n\n");
1974 if (is_fixup_flag(command, flag))
1975 strbuf_add_commented_lines(&buf, body, strlen(body));
1976 else
1977 strbuf_addstr(&buf, body);
1979 unuse_commit_buffer(head_commit, head_message);
1982 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1983 return error(_("could not read commit message of %s"),
1984 oid_to_hex(&commit->object.oid));
1985 find_commit_subject(message, &body);
1987 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1988 res = append_squash_message(&buf, body, command, opts, flag);
1989 } else if (command == TODO_FIXUP) {
1990 strbuf_addf(&buf, "\n%c ", comment_line_char);
1991 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1992 ++opts->current_fixup_count + 1);
1993 strbuf_addstr(&buf, "\n\n");
1994 strbuf_add_commented_lines(&buf, body, strlen(body));
1995 } else
1996 return error(_("unknown command: %d"), command);
1997 unuse_commit_buffer(commit, message);
1999 if (!res)
2000 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2002 strbuf_release(&buf);
2004 if (!res) {
2005 strbuf_addf(&opts->current_fixups, "%s%s %s",
2006 opts->current_fixups.len ? "\n" : "",
2007 command_to_string(command),
2008 oid_to_hex(&commit->object.oid));
2009 res = write_message(opts->current_fixups.buf,
2010 opts->current_fixups.len,
2011 rebase_path_current_fixups(), 0);
2014 return res;
2017 static void flush_rewritten_pending(void)
2019 struct strbuf buf = STRBUF_INIT;
2020 struct object_id newoid;
2021 FILE *out;
2023 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2024 !get_oid("HEAD", &newoid) &&
2025 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2026 char *bol = buf.buf, *eol;
2028 while (*bol) {
2029 eol = strchrnul(bol, '\n');
2030 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2031 bol, oid_to_hex(&newoid));
2032 if (!*eol)
2033 break;
2034 bol = eol + 1;
2036 fclose(out);
2037 unlink(rebase_path_rewritten_pending());
2039 strbuf_release(&buf);
2042 static void record_in_rewritten(struct object_id *oid,
2043 enum todo_command next_command)
2045 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2047 if (!out)
2048 return;
2050 fprintf(out, "%s\n", oid_to_hex(oid));
2051 fclose(out);
2053 if (!is_fixup(next_command))
2054 flush_rewritten_pending();
2057 static int should_edit(struct replay_opts *opts) {
2058 if (opts->edit < 0)
2060 * Note that we only handle the case of non-conflicted
2061 * commits; continue_single_pick() handles the conflicted
2062 * commits itself instead of calling this function.
2064 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2065 return opts->edit;
2068 static int do_pick_commit(struct repository *r,
2069 struct todo_item *item,
2070 struct replay_opts *opts,
2071 int final_fixup, int *check_todo)
2073 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2074 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2075 struct object_id head;
2076 struct commit *base, *next, *parent;
2077 const char *base_label, *next_label;
2078 char *author = NULL;
2079 struct commit_message msg = { NULL, NULL, NULL, NULL };
2080 struct strbuf msgbuf = STRBUF_INIT;
2081 int res, unborn = 0, reword = 0, allow, drop_commit;
2082 enum todo_command command = item->command;
2083 struct commit *commit = item->commit;
2085 if (opts->no_commit) {
2087 * We do not intend to commit immediately. We just want to
2088 * merge the differences in, so let's compute the tree
2089 * that represents the "current" state for the merge machinery
2090 * to work on.
2092 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2093 return error(_("your index file is unmerged."));
2094 } else {
2095 unborn = get_oid("HEAD", &head);
2096 /* Do we want to generate a root commit? */
2097 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2098 oideq(&head, &opts->squash_onto)) {
2099 if (is_fixup(command))
2100 return error(_("cannot fixup root commit"));
2101 flags |= CREATE_ROOT_COMMIT;
2102 unborn = 1;
2103 } else if (unborn)
2104 oidcpy(&head, the_hash_algo->empty_tree);
2105 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2106 NULL, 0))
2107 return error_dirty_index(r, opts);
2109 discard_index(r->index);
2111 if (!commit->parents)
2112 parent = NULL;
2113 else if (commit->parents->next) {
2114 /* Reverting or cherry-picking a merge commit */
2115 int cnt;
2116 struct commit_list *p;
2118 if (!opts->mainline)
2119 return error(_("commit %s is a merge but no -m option was given."),
2120 oid_to_hex(&commit->object.oid));
2122 for (cnt = 1, p = commit->parents;
2123 cnt != opts->mainline && p;
2124 cnt++)
2125 p = p->next;
2126 if (cnt != opts->mainline || !p)
2127 return error(_("commit %s does not have parent %d"),
2128 oid_to_hex(&commit->object.oid), opts->mainline);
2129 parent = p->item;
2130 } else if (1 < opts->mainline)
2132 * Non-first parent explicitly specified as mainline for
2133 * non-merge commit
2135 return error(_("commit %s does not have parent %d"),
2136 oid_to_hex(&commit->object.oid), opts->mainline);
2137 else
2138 parent = commit->parents->item;
2140 if (get_message(commit, &msg) != 0)
2141 return error(_("cannot get commit message for %s"),
2142 oid_to_hex(&commit->object.oid));
2144 if (opts->allow_ff && !is_fixup(command) &&
2145 ((parent && oideq(&parent->object.oid, &head)) ||
2146 (!parent && unborn))) {
2147 if (is_rebase_i(opts))
2148 write_author_script(msg.message);
2149 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2150 opts);
2151 if (res || command != TODO_REWORD)
2152 goto leave;
2153 reword = 1;
2154 msg_file = NULL;
2155 goto fast_forward_edit;
2157 if (parent && parse_commit(parent) < 0)
2158 /* TRANSLATORS: The first %s will be a "todo" command like
2159 "revert" or "pick", the second %s a SHA1. */
2160 return error(_("%s: cannot parse parent commit %s"),
2161 command_to_string(command),
2162 oid_to_hex(&parent->object.oid));
2165 * "commit" is an existing commit. We would want to apply
2166 * the difference it introduces since its first parent "prev"
2167 * on top of the current HEAD if we are cherry-pick. Or the
2168 * reverse of it if we are revert.
2171 if (command == TODO_REVERT) {
2172 base = commit;
2173 base_label = msg.label;
2174 next = parent;
2175 next_label = msg.parent_label;
2176 strbuf_addstr(&msgbuf, "Revert \"");
2177 strbuf_addstr(&msgbuf, msg.subject);
2178 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2179 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2181 if (commit->parents && commit->parents->next) {
2182 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2183 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2185 strbuf_addstr(&msgbuf, ".\n");
2186 } else {
2187 const char *p;
2189 base = parent;
2190 base_label = msg.parent_label;
2191 next = commit;
2192 next_label = msg.label;
2194 /* Append the commit log message to msgbuf. */
2195 if (find_commit_subject(msg.message, &p))
2196 strbuf_addstr(&msgbuf, p);
2198 if (opts->record_origin) {
2199 strbuf_complete_line(&msgbuf);
2200 if (!has_conforming_footer(&msgbuf, NULL, 0))
2201 strbuf_addch(&msgbuf, '\n');
2202 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2203 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2204 strbuf_addstr(&msgbuf, ")\n");
2206 if (!is_fixup(command))
2207 author = get_author(msg.message);
2210 if (command == TODO_REWORD)
2211 reword = 1;
2212 else if (is_fixup(command)) {
2213 if (update_squash_messages(r, command, commit,
2214 opts, item->flags))
2215 return -1;
2216 flags |= AMEND_MSG;
2217 if (!final_fixup)
2218 msg_file = rebase_path_squash_msg();
2219 else if (file_exists(rebase_path_fixup_msg())) {
2220 flags |= VERBATIM_MSG;
2221 msg_file = rebase_path_fixup_msg();
2222 } else {
2223 const char *dest = git_path_squash_msg(r);
2224 unlink(dest);
2225 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2226 return error(_("could not rename '%s' to '%s'"),
2227 rebase_path_squash_msg(), dest);
2228 unlink(git_path_merge_msg(r));
2229 msg_file = dest;
2230 flags |= EDIT_MSG;
2234 if (opts->signoff && !is_fixup(command))
2235 append_signoff(&msgbuf, 0, 0);
2237 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2238 res = -1;
2239 else if (!opts->strategy ||
2240 !strcmp(opts->strategy, "recursive") ||
2241 !strcmp(opts->strategy, "ort") ||
2242 command == TODO_REVERT) {
2243 res = do_recursive_merge(r, base, next, base_label, next_label,
2244 &head, &msgbuf, opts);
2245 if (res < 0)
2246 goto leave;
2248 res |= write_message(msgbuf.buf, msgbuf.len,
2249 git_path_merge_msg(r), 0);
2250 } else {
2251 struct commit_list *common = NULL;
2252 struct commit_list *remotes = NULL;
2254 res = write_message(msgbuf.buf, msgbuf.len,
2255 git_path_merge_msg(r), 0);
2257 commit_list_insert(base, &common);
2258 commit_list_insert(next, &remotes);
2259 res |= try_merge_command(r, opts->strategy,
2260 opts->xopts_nr, (const char **)opts->xopts,
2261 common, oid_to_hex(&head), remotes);
2262 free_commit_list(common);
2263 free_commit_list(remotes);
2265 strbuf_release(&msgbuf);
2268 * If the merge was clean or if it failed due to conflict, we write
2269 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2270 * However, if the merge did not even start, then we don't want to
2271 * write it at all.
2273 if ((command == TODO_PICK || command == TODO_REWORD ||
2274 command == TODO_EDIT) && !opts->no_commit &&
2275 (res == 0 || res == 1) &&
2276 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2277 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2278 res = -1;
2279 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2280 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2281 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2282 res = -1;
2284 if (res) {
2285 error(command == TODO_REVERT
2286 ? _("could not revert %s... %s")
2287 : _("could not apply %s... %s"),
2288 short_commit_name(commit), msg.subject);
2289 print_advice(r, res == 1, opts);
2290 repo_rerere(r, opts->allow_rerere_auto);
2291 goto leave;
2294 drop_commit = 0;
2295 allow = allow_empty(r, opts, commit);
2296 if (allow < 0) {
2297 res = allow;
2298 goto leave;
2299 } else if (allow == 1) {
2300 flags |= ALLOW_EMPTY;
2301 } else if (allow == 2) {
2302 drop_commit = 1;
2303 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2304 NULL, 0);
2305 unlink(git_path_merge_msg(r));
2306 unlink(git_path_auto_merge(r));
2307 fprintf(stderr,
2308 _("dropping %s %s -- patch contents already upstream\n"),
2309 oid_to_hex(&commit->object.oid), msg.subject);
2310 } /* else allow == 0 and there's nothing special to do */
2311 if (!opts->no_commit && !drop_commit) {
2312 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2313 res = do_commit(r, msg_file, author, opts, flags,
2314 commit? &commit->object.oid : NULL);
2315 else
2316 res = error(_("unable to parse commit author"));
2317 *check_todo = !!(flags & EDIT_MSG);
2318 if (!res && reword) {
2319 fast_forward_edit:
2320 res = run_git_commit(NULL, opts, EDIT_MSG |
2321 VERIFY_MSG | AMEND_MSG |
2322 (flags & ALLOW_EMPTY));
2323 *check_todo = 1;
2328 if (!res && final_fixup) {
2329 unlink(rebase_path_fixup_msg());
2330 unlink(rebase_path_squash_msg());
2331 unlink(rebase_path_current_fixups());
2332 strbuf_reset(&opts->current_fixups);
2333 opts->current_fixup_count = 0;
2336 leave:
2337 free_message(commit, &msg);
2338 free(author);
2339 update_abort_safety_file();
2341 return res;
2344 static int prepare_revs(struct replay_opts *opts)
2347 * picking (but not reverting) ranges (but not individual revisions)
2348 * should be done in reverse
2350 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2351 opts->revs->reverse ^= 1;
2353 if (prepare_revision_walk(opts->revs))
2354 return error(_("revision walk setup failed"));
2356 return 0;
2359 static int read_and_refresh_cache(struct repository *r,
2360 struct replay_opts *opts)
2362 struct lock_file index_lock = LOCK_INIT;
2363 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2364 if (repo_read_index(r) < 0) {
2365 rollback_lock_file(&index_lock);
2366 return error(_("git %s: failed to read the index"),
2367 _(action_name(opts)));
2369 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2371 if (index_fd >= 0) {
2372 if (write_locked_index(r->index, &index_lock,
2373 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2374 return error(_("git %s: failed to refresh the index"),
2375 _(action_name(opts)));
2380 * If we are resolving merges in any way other than "ort", then
2381 * expand the sparse index.
2383 if (opts->strategy && strcmp(opts->strategy, "ort"))
2384 ensure_full_index(r->index);
2385 return 0;
2388 void todo_list_release(struct todo_list *todo_list)
2390 strbuf_release(&todo_list->buf);
2391 FREE_AND_NULL(todo_list->items);
2392 todo_list->nr = todo_list->alloc = 0;
2395 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2397 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2398 todo_list->total_nr++;
2399 return todo_list->items + todo_list->nr++;
2402 const char *todo_item_get_arg(struct todo_list *todo_list,
2403 struct todo_item *item)
2405 return todo_list->buf.buf + item->arg_offset;
2408 static int is_command(enum todo_command command, const char **bol)
2410 const char *str = todo_command_info[command].str;
2411 const char nick = todo_command_info[command].c;
2412 const char *p = *bol + 1;
2414 return skip_prefix(*bol, str, bol) ||
2415 ((nick && **bol == nick) &&
2416 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2417 (*bol = p));
2420 static int parse_insn_line(struct repository *r, struct todo_item *item,
2421 const char *buf, const char *bol, char *eol)
2423 struct object_id commit_oid;
2424 char *end_of_object_name;
2425 int i, saved, status, padding;
2427 item->flags = 0;
2429 /* left-trim */
2430 bol += strspn(bol, " \t");
2432 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2433 item->command = TODO_COMMENT;
2434 item->commit = NULL;
2435 item->arg_offset = bol - buf;
2436 item->arg_len = eol - bol;
2437 return 0;
2440 for (i = 0; i < TODO_COMMENT; i++)
2441 if (is_command(i, &bol)) {
2442 item->command = i;
2443 break;
2445 if (i >= TODO_COMMENT)
2446 return -1;
2448 /* Eat up extra spaces/ tabs before object name */
2449 padding = strspn(bol, " \t");
2450 bol += padding;
2452 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2453 if (bol != eol)
2454 return error(_("%s does not accept arguments: '%s'"),
2455 command_to_string(item->command), bol);
2456 item->commit = NULL;
2457 item->arg_offset = bol - buf;
2458 item->arg_len = eol - bol;
2459 return 0;
2462 if (!padding)
2463 return error(_("missing arguments for %s"),
2464 command_to_string(item->command));
2466 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2467 item->command == TODO_RESET) {
2468 item->commit = NULL;
2469 item->arg_offset = bol - buf;
2470 item->arg_len = (int)(eol - bol);
2471 return 0;
2474 if (item->command == TODO_FIXUP) {
2475 if (skip_prefix(bol, "-C", &bol) &&
2476 (*bol == ' ' || *bol == '\t')) {
2477 bol += strspn(bol, " \t");
2478 item->flags |= TODO_REPLACE_FIXUP_MSG;
2479 } else if (skip_prefix(bol, "-c", &bol) &&
2480 (*bol == ' ' || *bol == '\t')) {
2481 bol += strspn(bol, " \t");
2482 item->flags |= TODO_EDIT_FIXUP_MSG;
2486 if (item->command == TODO_MERGE) {
2487 if (skip_prefix(bol, "-C", &bol))
2488 bol += strspn(bol, " \t");
2489 else if (skip_prefix(bol, "-c", &bol)) {
2490 bol += strspn(bol, " \t");
2491 item->flags |= TODO_EDIT_MERGE_MSG;
2492 } else {
2493 item->flags |= TODO_EDIT_MERGE_MSG;
2494 item->commit = NULL;
2495 item->arg_offset = bol - buf;
2496 item->arg_len = (int)(eol - bol);
2497 return 0;
2501 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2502 saved = *end_of_object_name;
2503 *end_of_object_name = '\0';
2504 status = get_oid(bol, &commit_oid);
2505 if (status < 0)
2506 error(_("could not parse '%s'"), bol); /* return later */
2507 *end_of_object_name = saved;
2509 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2510 item->arg_offset = bol - buf;
2511 item->arg_len = (int)(eol - bol);
2513 if (status < 0)
2514 return status;
2516 item->commit = lookup_commit_reference(r, &commit_oid);
2517 return item->commit ? 0 : -1;
2520 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2522 const char *todo_file, *bol;
2523 struct strbuf buf = STRBUF_INIT;
2524 int ret = 0;
2526 todo_file = git_path_todo_file();
2527 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2528 if (errno == ENOENT || errno == ENOTDIR)
2529 return -1;
2530 else
2531 return error_errno("unable to open '%s'", todo_file);
2533 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2534 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2535 *action = REPLAY_PICK;
2536 else if (is_command(TODO_REVERT, &bol) &&
2537 (*bol == ' ' || *bol == '\t'))
2538 *action = REPLAY_REVERT;
2539 else
2540 ret = -1;
2542 strbuf_release(&buf);
2544 return ret;
2547 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2548 struct todo_list *todo_list)
2550 struct todo_item *item;
2551 char *p = buf, *next_p;
2552 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2554 todo_list->current = todo_list->nr = 0;
2556 for (i = 1; *p; i++, p = next_p) {
2557 char *eol = strchrnul(p, '\n');
2559 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2561 if (p != eol && eol[-1] == '\r')
2562 eol--; /* strip Carriage Return */
2564 item = append_new_todo(todo_list);
2565 item->offset_in_buf = p - todo_list->buf.buf;
2566 if (parse_insn_line(r, item, buf, p, eol)) {
2567 res = error(_("invalid line %d: %.*s"),
2568 i, (int)(eol - p), p);
2569 item->command = TODO_COMMENT + 1;
2570 item->arg_offset = p - buf;
2571 item->arg_len = (int)(eol - p);
2572 item->commit = NULL;
2575 if (fixup_okay)
2576 ; /* do nothing */
2577 else if (is_fixup(item->command))
2578 return error(_("cannot '%s' without a previous commit"),
2579 command_to_string(item->command));
2580 else if (!is_noop(item->command))
2581 fixup_okay = 1;
2584 return res;
2587 static int count_commands(struct todo_list *todo_list)
2589 int count = 0, i;
2591 for (i = 0; i < todo_list->nr; i++)
2592 if (todo_list->items[i].command != TODO_COMMENT)
2593 count++;
2595 return count;
2598 static int get_item_line_offset(struct todo_list *todo_list, int index)
2600 return index < todo_list->nr ?
2601 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2604 static const char *get_item_line(struct todo_list *todo_list, int index)
2606 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2609 static int get_item_line_length(struct todo_list *todo_list, int index)
2611 return get_item_line_offset(todo_list, index + 1)
2612 - get_item_line_offset(todo_list, index);
2615 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2617 int fd;
2618 ssize_t len;
2620 fd = open(path, O_RDONLY);
2621 if (fd < 0)
2622 return error_errno(_("could not open '%s'"), path);
2623 len = strbuf_read(sb, fd, 0);
2624 close(fd);
2625 if (len < 0)
2626 return error(_("could not read '%s'."), path);
2627 return len;
2630 static int have_finished_the_last_pick(void)
2632 struct strbuf buf = STRBUF_INIT;
2633 const char *eol;
2634 const char *todo_path = git_path_todo_file();
2635 int ret = 0;
2637 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2638 if (errno == ENOENT) {
2639 return 0;
2640 } else {
2641 error_errno("unable to open '%s'", todo_path);
2642 return 0;
2645 /* If there is only one line then we are done */
2646 eol = strchr(buf.buf, '\n');
2647 if (!eol || !eol[1])
2648 ret = 1;
2650 strbuf_release(&buf);
2652 return ret;
2655 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2657 struct replay_opts opts = REPLAY_OPTS_INIT;
2658 int need_cleanup = 0;
2660 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2661 if (!refs_delete_ref(get_main_ref_store(r), "",
2662 "CHERRY_PICK_HEAD", NULL, 0) &&
2663 verbose)
2664 warning(_("cancelling a cherry picking in progress"));
2665 opts.action = REPLAY_PICK;
2666 need_cleanup = 1;
2669 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2670 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2671 NULL, 0) &&
2672 verbose)
2673 warning(_("cancelling a revert in progress"));
2674 opts.action = REPLAY_REVERT;
2675 need_cleanup = 1;
2678 unlink(git_path_auto_merge(r));
2680 if (!need_cleanup)
2681 return;
2683 if (!have_finished_the_last_pick())
2684 return;
2686 sequencer_remove_state(&opts);
2689 static void todo_list_write_total_nr(struct todo_list *todo_list)
2691 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2693 if (f) {
2694 fprintf(f, "%d\n", todo_list->total_nr);
2695 fclose(f);
2699 static int read_populate_todo(struct repository *r,
2700 struct todo_list *todo_list,
2701 struct replay_opts *opts)
2703 const char *todo_file = get_todo_path(opts);
2704 int res;
2706 strbuf_reset(&todo_list->buf);
2707 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2708 return -1;
2710 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2711 if (res) {
2712 if (is_rebase_i(opts))
2713 return error(_("please fix this using "
2714 "'git rebase --edit-todo'."));
2715 return error(_("unusable instruction sheet: '%s'"), todo_file);
2718 if (!todo_list->nr &&
2719 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2720 return error(_("no commits parsed."));
2722 if (!is_rebase_i(opts)) {
2723 enum todo_command valid =
2724 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2725 int i;
2727 for (i = 0; i < todo_list->nr; i++)
2728 if (valid == todo_list->items[i].command)
2729 continue;
2730 else if (valid == TODO_PICK)
2731 return error(_("cannot cherry-pick during a revert."));
2732 else
2733 return error(_("cannot revert during a cherry-pick."));
2736 if (is_rebase_i(opts)) {
2737 struct todo_list done = TODO_LIST_INIT;
2739 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2740 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2741 todo_list->done_nr = count_commands(&done);
2742 else
2743 todo_list->done_nr = 0;
2745 todo_list->total_nr = todo_list->done_nr
2746 + count_commands(todo_list);
2747 todo_list_release(&done);
2749 todo_list_write_total_nr(todo_list);
2752 return 0;
2755 static int git_config_string_dup(char **dest,
2756 const char *var, const char *value)
2758 if (!value)
2759 return config_error_nonbool(var);
2760 free(*dest);
2761 *dest = xstrdup(value);
2762 return 0;
2765 static int populate_opts_cb(const char *key, const char *value, void *data)
2767 struct replay_opts *opts = data;
2768 int error_flag = 1;
2770 if (!value)
2771 error_flag = 0;
2772 else if (!strcmp(key, "options.no-commit"))
2773 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2774 else if (!strcmp(key, "options.edit"))
2775 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2776 else if (!strcmp(key, "options.allow-empty"))
2777 opts->allow_empty =
2778 git_config_bool_or_int(key, value, &error_flag);
2779 else if (!strcmp(key, "options.allow-empty-message"))
2780 opts->allow_empty_message =
2781 git_config_bool_or_int(key, value, &error_flag);
2782 else if (!strcmp(key, "options.keep-redundant-commits"))
2783 opts->keep_redundant_commits =
2784 git_config_bool_or_int(key, value, &error_flag);
2785 else if (!strcmp(key, "options.signoff"))
2786 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2787 else if (!strcmp(key, "options.record-origin"))
2788 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2789 else if (!strcmp(key, "options.allow-ff"))
2790 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2791 else if (!strcmp(key, "options.mainline"))
2792 opts->mainline = git_config_int(key, value);
2793 else if (!strcmp(key, "options.strategy"))
2794 git_config_string_dup(&opts->strategy, key, value);
2795 else if (!strcmp(key, "options.gpg-sign"))
2796 git_config_string_dup(&opts->gpg_sign, key, value);
2797 else if (!strcmp(key, "options.strategy-option")) {
2798 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2799 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2800 } else if (!strcmp(key, "options.allow-rerere-auto"))
2801 opts->allow_rerere_auto =
2802 git_config_bool_or_int(key, value, &error_flag) ?
2803 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2804 else if (!strcmp(key, "options.default-msg-cleanup")) {
2805 opts->explicit_cleanup = 1;
2806 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2807 } else
2808 return error(_("invalid key: %s"), key);
2810 if (!error_flag)
2811 return error(_("invalid value for %s: %s"), key, value);
2813 return 0;
2816 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2818 int i;
2819 char *strategy_opts_string = raw_opts;
2821 if (*strategy_opts_string == ' ')
2822 strategy_opts_string++;
2824 opts->xopts_nr = split_cmdline(strategy_opts_string,
2825 (const char ***)&opts->xopts);
2826 for (i = 0; i < opts->xopts_nr; i++) {
2827 const char *arg = opts->xopts[i];
2829 skip_prefix(arg, "--", &arg);
2830 opts->xopts[i] = xstrdup(arg);
2834 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2836 strbuf_reset(buf);
2837 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2838 return;
2839 opts->strategy = strbuf_detach(buf, NULL);
2840 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2841 return;
2843 parse_strategy_opts(opts, buf->buf);
2846 static int read_populate_opts(struct replay_opts *opts)
2848 if (is_rebase_i(opts)) {
2849 struct strbuf buf = STRBUF_INIT;
2850 int ret = 0;
2852 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2853 READ_ONELINER_SKIP_IF_EMPTY)) {
2854 if (!starts_with(buf.buf, "-S"))
2855 strbuf_reset(&buf);
2856 else {
2857 free(opts->gpg_sign);
2858 opts->gpg_sign = xstrdup(buf.buf + 2);
2860 strbuf_reset(&buf);
2863 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2864 READ_ONELINER_SKIP_IF_EMPTY)) {
2865 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2866 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2867 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2868 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2869 strbuf_reset(&buf);
2872 if (file_exists(rebase_path_verbose()))
2873 opts->verbose = 1;
2875 if (file_exists(rebase_path_quiet()))
2876 opts->quiet = 1;
2878 if (file_exists(rebase_path_signoff())) {
2879 opts->allow_ff = 0;
2880 opts->signoff = 1;
2883 if (file_exists(rebase_path_cdate_is_adate())) {
2884 opts->allow_ff = 0;
2885 opts->committer_date_is_author_date = 1;
2888 if (file_exists(rebase_path_ignore_date())) {
2889 opts->allow_ff = 0;
2890 opts->ignore_date = 1;
2893 if (file_exists(rebase_path_reschedule_failed_exec()))
2894 opts->reschedule_failed_exec = 1;
2895 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2896 opts->reschedule_failed_exec = 0;
2898 if (file_exists(rebase_path_drop_redundant_commits()))
2899 opts->drop_redundant_commits = 1;
2901 if (file_exists(rebase_path_keep_redundant_commits()))
2902 opts->keep_redundant_commits = 1;
2904 read_strategy_opts(opts, &buf);
2905 strbuf_reset(&buf);
2907 if (read_oneliner(&opts->current_fixups,
2908 rebase_path_current_fixups(),
2909 READ_ONELINER_SKIP_IF_EMPTY)) {
2910 const char *p = opts->current_fixups.buf;
2911 opts->current_fixup_count = 1;
2912 while ((p = strchr(p, '\n'))) {
2913 opts->current_fixup_count++;
2914 p++;
2918 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2919 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2920 ret = error(_("unusable squash-onto"));
2921 goto done_rebase_i;
2923 opts->have_squash_onto = 1;
2926 done_rebase_i:
2927 strbuf_release(&buf);
2928 return ret;
2931 if (!file_exists(git_path_opts_file()))
2932 return 0;
2934 * The function git_parse_source(), called from git_config_from_file(),
2935 * may die() in case of a syntactically incorrect file. We do not care
2936 * about this case, though, because we wrote that file ourselves, so we
2937 * are pretty certain that it is syntactically correct.
2939 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2940 return error(_("malformed options sheet: '%s'"),
2941 git_path_opts_file());
2942 return 0;
2945 static void write_strategy_opts(struct replay_opts *opts)
2947 int i;
2948 struct strbuf buf = STRBUF_INIT;
2950 for (i = 0; i < opts->xopts_nr; ++i)
2951 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2953 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2954 strbuf_release(&buf);
2957 int write_basic_state(struct replay_opts *opts, const char *head_name,
2958 struct commit *onto, const struct object_id *orig_head)
2960 if (head_name)
2961 write_file(rebase_path_head_name(), "%s\n", head_name);
2962 if (onto)
2963 write_file(rebase_path_onto(), "%s\n",
2964 oid_to_hex(&onto->object.oid));
2965 if (orig_head)
2966 write_file(rebase_path_orig_head(), "%s\n",
2967 oid_to_hex(orig_head));
2969 if (opts->quiet)
2970 write_file(rebase_path_quiet(), "%s", "");
2971 if (opts->verbose)
2972 write_file(rebase_path_verbose(), "%s", "");
2973 if (opts->strategy)
2974 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2975 if (opts->xopts_nr > 0)
2976 write_strategy_opts(opts);
2978 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2979 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2980 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2981 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2983 if (opts->gpg_sign)
2984 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2985 if (opts->signoff)
2986 write_file(rebase_path_signoff(), "--signoff\n");
2987 if (opts->drop_redundant_commits)
2988 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2989 if (opts->keep_redundant_commits)
2990 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2991 if (opts->committer_date_is_author_date)
2992 write_file(rebase_path_cdate_is_adate(), "%s", "");
2993 if (opts->ignore_date)
2994 write_file(rebase_path_ignore_date(), "%s", "");
2995 if (opts->reschedule_failed_exec)
2996 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2997 else
2998 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3000 return 0;
3003 static int walk_revs_populate_todo(struct todo_list *todo_list,
3004 struct replay_opts *opts)
3006 enum todo_command command = opts->action == REPLAY_PICK ?
3007 TODO_PICK : TODO_REVERT;
3008 const char *command_string = todo_command_info[command].str;
3009 const char *encoding;
3010 struct commit *commit;
3012 if (prepare_revs(opts))
3013 return -1;
3015 encoding = get_log_output_encoding();
3017 while ((commit = get_revision(opts->revs))) {
3018 struct todo_item *item = append_new_todo(todo_list);
3019 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3020 const char *subject;
3021 int subject_len;
3023 item->command = command;
3024 item->commit = commit;
3025 item->arg_offset = 0;
3026 item->arg_len = 0;
3027 item->offset_in_buf = todo_list->buf.len;
3028 subject_len = find_commit_subject(commit_buffer, &subject);
3029 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3030 short_commit_name(commit), subject_len, subject);
3031 unuse_commit_buffer(commit, commit_buffer);
3034 if (!todo_list->nr)
3035 return error(_("empty commit set passed"));
3037 return 0;
3040 static int create_seq_dir(struct repository *r)
3042 enum replay_action action;
3043 const char *in_progress_error = NULL;
3044 const char *in_progress_advice = NULL;
3045 unsigned int advise_skip =
3046 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3047 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3049 if (!sequencer_get_last_command(r, &action)) {
3050 switch (action) {
3051 case REPLAY_REVERT:
3052 in_progress_error = _("revert is already in progress");
3053 in_progress_advice =
3054 _("try \"git revert (--continue | %s--abort | --quit)\"");
3055 break;
3056 case REPLAY_PICK:
3057 in_progress_error = _("cherry-pick is already in progress");
3058 in_progress_advice =
3059 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3060 break;
3061 default:
3062 BUG("unexpected action in create_seq_dir");
3065 if (in_progress_error) {
3066 error("%s", in_progress_error);
3067 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3068 advise(in_progress_advice,
3069 advise_skip ? "--skip | " : "");
3070 return -1;
3072 if (mkdir(git_path_seq_dir(), 0777) < 0)
3073 return error_errno(_("could not create sequencer directory '%s'"),
3074 git_path_seq_dir());
3076 return 0;
3079 static int save_head(const char *head)
3081 struct lock_file head_lock = LOCK_INIT;
3082 struct strbuf buf = STRBUF_INIT;
3083 int fd;
3084 ssize_t written;
3086 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3087 if (fd < 0)
3088 return error_errno(_("could not lock HEAD"));
3089 strbuf_addf(&buf, "%s\n", head);
3090 written = write_in_full(fd, buf.buf, buf.len);
3091 strbuf_release(&buf);
3092 if (written < 0) {
3093 error_errno(_("could not write to '%s'"), git_path_head_file());
3094 rollback_lock_file(&head_lock);
3095 return -1;
3097 if (commit_lock_file(&head_lock) < 0)
3098 return error(_("failed to finalize '%s'"), git_path_head_file());
3099 return 0;
3102 static int rollback_is_safe(void)
3104 struct strbuf sb = STRBUF_INIT;
3105 struct object_id expected_head, actual_head;
3107 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3108 strbuf_trim(&sb);
3109 if (get_oid_hex(sb.buf, &expected_head)) {
3110 strbuf_release(&sb);
3111 die(_("could not parse %s"), git_path_abort_safety_file());
3113 strbuf_release(&sb);
3115 else if (errno == ENOENT)
3116 oidclr(&expected_head);
3117 else
3118 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3120 if (get_oid("HEAD", &actual_head))
3121 oidclr(&actual_head);
3123 return oideq(&actual_head, &expected_head);
3126 static int reset_merge(const struct object_id *oid)
3128 int ret;
3129 struct strvec argv = STRVEC_INIT;
3131 strvec_pushl(&argv, "reset", "--merge", NULL);
3133 if (!is_null_oid(oid))
3134 strvec_push(&argv, oid_to_hex(oid));
3136 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3137 strvec_clear(&argv);
3139 return ret;
3142 static int rollback_single_pick(struct repository *r)
3144 struct object_id head_oid;
3146 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3147 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3148 return error(_("no cherry-pick or revert in progress"));
3149 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3150 return error(_("cannot resolve HEAD"));
3151 if (is_null_oid(&head_oid))
3152 return error(_("cannot abort from a branch yet to be born"));
3153 return reset_merge(&head_oid);
3156 static int skip_single_pick(void)
3158 struct object_id head;
3160 if (read_ref_full("HEAD", 0, &head, NULL))
3161 return error(_("cannot resolve HEAD"));
3162 return reset_merge(&head);
3165 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3167 FILE *f;
3168 struct object_id oid;
3169 struct strbuf buf = STRBUF_INIT;
3170 const char *p;
3172 f = fopen(git_path_head_file(), "r");
3173 if (!f && errno == ENOENT) {
3175 * There is no multiple-cherry-pick in progress.
3176 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3177 * a single-cherry-pick in progress, abort that.
3179 return rollback_single_pick(r);
3181 if (!f)
3182 return error_errno(_("cannot open '%s'"), git_path_head_file());
3183 if (strbuf_getline_lf(&buf, f)) {
3184 error(_("cannot read '%s': %s"), git_path_head_file(),
3185 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3186 fclose(f);
3187 goto fail;
3189 fclose(f);
3190 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3191 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3192 git_path_head_file());
3193 goto fail;
3195 if (is_null_oid(&oid)) {
3196 error(_("cannot abort from a branch yet to be born"));
3197 goto fail;
3200 if (!rollback_is_safe()) {
3201 /* Do not error, just do not rollback */
3202 warning(_("You seem to have moved HEAD. "
3203 "Not rewinding, check your HEAD!"));
3204 } else
3205 if (reset_merge(&oid))
3206 goto fail;
3207 strbuf_release(&buf);
3208 return sequencer_remove_state(opts);
3209 fail:
3210 strbuf_release(&buf);
3211 return -1;
3214 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3216 enum replay_action action = -1;
3217 sequencer_get_last_command(r, &action);
3220 * Check whether the subcommand requested to skip the commit is actually
3221 * in progress and that it's safe to skip the commit.
3223 * opts->action tells us which subcommand requested to skip the commit.
3224 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3225 * action is in progress and we can skip the commit.
3227 * Otherwise we check that the last instruction was related to the
3228 * particular subcommand we're trying to execute and barf if that's not
3229 * the case.
3231 * Finally we check that the rollback is "safe", i.e., has the HEAD
3232 * moved? In this case, it doesn't make sense to "reset the merge" and
3233 * "skip the commit" as the user already handled this by committing. But
3234 * we'd not want to barf here, instead give advice on how to proceed. We
3235 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3236 * it gets removed when the user commits, so if it still exists we're
3237 * sure the user can't have committed before.
3239 switch (opts->action) {
3240 case REPLAY_REVERT:
3241 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3242 if (action != REPLAY_REVERT)
3243 return error(_("no revert in progress"));
3244 if (!rollback_is_safe())
3245 goto give_advice;
3247 break;
3248 case REPLAY_PICK:
3249 if (!refs_ref_exists(get_main_ref_store(r),
3250 "CHERRY_PICK_HEAD")) {
3251 if (action != REPLAY_PICK)
3252 return error(_("no cherry-pick in progress"));
3253 if (!rollback_is_safe())
3254 goto give_advice;
3256 break;
3257 default:
3258 BUG("unexpected action in sequencer_skip");
3261 if (skip_single_pick())
3262 return error(_("failed to skip the commit"));
3263 if (!is_directory(git_path_seq_dir()))
3264 return 0;
3266 return sequencer_continue(r, opts);
3268 give_advice:
3269 error(_("there is nothing to skip"));
3271 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3272 advise(_("have you committed already?\n"
3273 "try \"git %s --continue\""),
3274 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3276 return -1;
3279 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3281 struct lock_file todo_lock = LOCK_INIT;
3282 const char *todo_path = get_todo_path(opts);
3283 int next = todo_list->current, offset, fd;
3286 * rebase -i writes "git-rebase-todo" without the currently executing
3287 * command, appending it to "done" instead.
3289 if (is_rebase_i(opts))
3290 next++;
3292 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3293 if (fd < 0)
3294 return error_errno(_("could not lock '%s'"), todo_path);
3295 offset = get_item_line_offset(todo_list, next);
3296 if (write_in_full(fd, todo_list->buf.buf + offset,
3297 todo_list->buf.len - offset) < 0)
3298 return error_errno(_("could not write to '%s'"), todo_path);
3299 if (commit_lock_file(&todo_lock) < 0)
3300 return error(_("failed to finalize '%s'"), todo_path);
3302 if (is_rebase_i(opts) && next > 0) {
3303 const char *done = rebase_path_done();
3304 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3305 int ret = 0;
3307 if (fd < 0)
3308 return 0;
3309 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3310 get_item_line_length(todo_list, next - 1))
3311 < 0)
3312 ret = error_errno(_("could not write to '%s'"), done);
3313 if (close(fd) < 0)
3314 ret = error_errno(_("failed to finalize '%s'"), done);
3315 return ret;
3317 return 0;
3320 static int save_opts(struct replay_opts *opts)
3322 const char *opts_file = git_path_opts_file();
3323 int res = 0;
3325 if (opts->no_commit)
3326 res |= git_config_set_in_file_gently(opts_file,
3327 "options.no-commit", "true");
3328 if (opts->edit >= 0)
3329 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3330 opts->edit ? "true" : "false");
3331 if (opts->allow_empty)
3332 res |= git_config_set_in_file_gently(opts_file,
3333 "options.allow-empty", "true");
3334 if (opts->allow_empty_message)
3335 res |= git_config_set_in_file_gently(opts_file,
3336 "options.allow-empty-message", "true");
3337 if (opts->keep_redundant_commits)
3338 res |= git_config_set_in_file_gently(opts_file,
3339 "options.keep-redundant-commits", "true");
3340 if (opts->signoff)
3341 res |= git_config_set_in_file_gently(opts_file,
3342 "options.signoff", "true");
3343 if (opts->record_origin)
3344 res |= git_config_set_in_file_gently(opts_file,
3345 "options.record-origin", "true");
3346 if (opts->allow_ff)
3347 res |= git_config_set_in_file_gently(opts_file,
3348 "options.allow-ff", "true");
3349 if (opts->mainline) {
3350 struct strbuf buf = STRBUF_INIT;
3351 strbuf_addf(&buf, "%d", opts->mainline);
3352 res |= git_config_set_in_file_gently(opts_file,
3353 "options.mainline", buf.buf);
3354 strbuf_release(&buf);
3356 if (opts->strategy)
3357 res |= git_config_set_in_file_gently(opts_file,
3358 "options.strategy", opts->strategy);
3359 if (opts->gpg_sign)
3360 res |= git_config_set_in_file_gently(opts_file,
3361 "options.gpg-sign", opts->gpg_sign);
3362 if (opts->xopts) {
3363 int i;
3364 for (i = 0; i < opts->xopts_nr; i++)
3365 res |= git_config_set_multivar_in_file_gently(opts_file,
3366 "options.strategy-option",
3367 opts->xopts[i], "^$", 0);
3369 if (opts->allow_rerere_auto)
3370 res |= git_config_set_in_file_gently(opts_file,
3371 "options.allow-rerere-auto",
3372 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3373 "true" : "false");
3375 if (opts->explicit_cleanup)
3376 res |= git_config_set_in_file_gently(opts_file,
3377 "options.default-msg-cleanup",
3378 describe_cleanup_mode(opts->default_msg_cleanup));
3379 return res;
3382 static int make_patch(struct repository *r,
3383 struct commit *commit,
3384 struct replay_opts *opts)
3386 struct strbuf buf = STRBUF_INIT;
3387 struct rev_info log_tree_opt;
3388 const char *subject;
3389 char hex[GIT_MAX_HEXSZ + 1];
3390 int res = 0;
3392 oid_to_hex_r(hex, &commit->object.oid);
3393 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3394 return -1;
3395 res |= write_rebase_head(&commit->object.oid);
3397 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3398 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3399 repo_init_revisions(r, &log_tree_opt, NULL);
3400 log_tree_opt.abbrev = 0;
3401 log_tree_opt.diff = 1;
3402 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3403 log_tree_opt.disable_stdin = 1;
3404 log_tree_opt.no_commit_id = 1;
3405 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3406 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3407 if (!log_tree_opt.diffopt.file)
3408 res |= error_errno(_("could not open '%s'"), buf.buf);
3409 else {
3410 res |= log_tree_commit(&log_tree_opt, commit);
3411 fclose(log_tree_opt.diffopt.file);
3413 strbuf_reset(&buf);
3415 strbuf_addf(&buf, "%s/message", get_dir(opts));
3416 if (!file_exists(buf.buf)) {
3417 const char *encoding = get_commit_output_encoding();
3418 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3419 find_commit_subject(commit_buffer, &subject);
3420 res |= write_message(subject, strlen(subject), buf.buf, 1);
3421 unuse_commit_buffer(commit, commit_buffer);
3423 strbuf_release(&buf);
3425 return res;
3428 static int intend_to_amend(void)
3430 struct object_id head;
3431 char *p;
3433 if (get_oid("HEAD", &head))
3434 return error(_("cannot read HEAD"));
3436 p = oid_to_hex(&head);
3437 return write_message(p, strlen(p), rebase_path_amend(), 1);
3440 static int error_with_patch(struct repository *r,
3441 struct commit *commit,
3442 const char *subject, int subject_len,
3443 struct replay_opts *opts,
3444 int exit_code, int to_amend)
3446 if (commit) {
3447 if (make_patch(r, commit, opts))
3448 return -1;
3449 } else if (copy_file(rebase_path_message(),
3450 git_path_merge_msg(r), 0666))
3451 return error(_("unable to copy '%s' to '%s'"),
3452 git_path_merge_msg(r), rebase_path_message());
3454 if (to_amend) {
3455 if (intend_to_amend())
3456 return -1;
3458 fprintf(stderr,
3459 _("You can amend the commit now, with\n"
3460 "\n"
3461 " git commit --amend %s\n"
3462 "\n"
3463 "Once you are satisfied with your changes, run\n"
3464 "\n"
3465 " git rebase --continue\n"),
3466 gpg_sign_opt_quoted(opts));
3467 } else if (exit_code) {
3468 if (commit)
3469 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3470 short_commit_name(commit), subject_len, subject);
3471 else
3473 * We don't have the hash of the parent so
3474 * just print the line from the todo file.
3476 fprintf_ln(stderr, _("Could not merge %.*s"),
3477 subject_len, subject);
3480 return exit_code;
3483 static int error_failed_squash(struct repository *r,
3484 struct commit *commit,
3485 struct replay_opts *opts,
3486 int subject_len,
3487 const char *subject)
3489 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3490 return error(_("could not copy '%s' to '%s'"),
3491 rebase_path_squash_msg(), rebase_path_message());
3492 unlink(git_path_merge_msg(r));
3493 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3494 return error(_("could not copy '%s' to '%s'"),
3495 rebase_path_message(),
3496 git_path_merge_msg(r));
3497 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3500 static int do_exec(struct repository *r, const char *command_line)
3502 struct strvec child_env = STRVEC_INIT;
3503 const char *child_argv[] = { NULL, NULL };
3504 int dirty, status;
3506 fprintf(stderr, _("Executing: %s\n"), command_line);
3507 child_argv[0] = command_line;
3508 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3509 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3510 absolute_path(get_git_work_tree()));
3511 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3512 child_env.v);
3514 /* force re-reading of the cache */
3515 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3516 return error(_("could not read index"));
3518 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3520 if (status) {
3521 warning(_("execution failed: %s\n%s"
3522 "You can fix the problem, and then run\n"
3523 "\n"
3524 " git rebase --continue\n"
3525 "\n"),
3526 command_line,
3527 dirty ? N_("and made changes to the index and/or the "
3528 "working tree\n") : "");
3529 if (status == 127)
3530 /* command not found */
3531 status = 1;
3532 } else if (dirty) {
3533 warning(_("execution succeeded: %s\nbut "
3534 "left changes to the index and/or the working tree\n"
3535 "Commit or stash your changes, and then run\n"
3536 "\n"
3537 " git rebase --continue\n"
3538 "\n"), command_line);
3539 status = 1;
3542 strvec_clear(&child_env);
3544 return status;
3547 __attribute__((format (printf, 2, 3)))
3548 static int safe_append(const char *filename, const char *fmt, ...)
3550 va_list ap;
3551 struct lock_file lock = LOCK_INIT;
3552 int fd = hold_lock_file_for_update(&lock, filename,
3553 LOCK_REPORT_ON_ERROR);
3554 struct strbuf buf = STRBUF_INIT;
3556 if (fd < 0)
3557 return -1;
3559 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3560 error_errno(_("could not read '%s'"), filename);
3561 rollback_lock_file(&lock);
3562 return -1;
3564 strbuf_complete(&buf, '\n');
3565 va_start(ap, fmt);
3566 strbuf_vaddf(&buf, fmt, ap);
3567 va_end(ap);
3569 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3570 error_errno(_("could not write to '%s'"), filename);
3571 strbuf_release(&buf);
3572 rollback_lock_file(&lock);
3573 return -1;
3575 if (commit_lock_file(&lock) < 0) {
3576 strbuf_release(&buf);
3577 rollback_lock_file(&lock);
3578 return error(_("failed to finalize '%s'"), filename);
3581 strbuf_release(&buf);
3582 return 0;
3585 static int do_label(struct repository *r, const char *name, int len)
3587 struct ref_store *refs = get_main_ref_store(r);
3588 struct ref_transaction *transaction;
3589 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3590 struct strbuf msg = STRBUF_INIT;
3591 int ret = 0;
3592 struct object_id head_oid;
3594 if (len == 1 && *name == '#')
3595 return error(_("illegal label name: '%.*s'"), len, name);
3597 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3598 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3600 transaction = ref_store_transaction_begin(refs, &err);
3601 if (!transaction) {
3602 error("%s", err.buf);
3603 ret = -1;
3604 } else if (get_oid("HEAD", &head_oid)) {
3605 error(_("could not read HEAD"));
3606 ret = -1;
3607 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3608 NULL, 0, msg.buf, &err) < 0 ||
3609 ref_transaction_commit(transaction, &err)) {
3610 error("%s", err.buf);
3611 ret = -1;
3613 ref_transaction_free(transaction);
3614 strbuf_release(&err);
3615 strbuf_release(&msg);
3617 if (!ret)
3618 ret = safe_append(rebase_path_refs_to_delete(),
3619 "%s\n", ref_name.buf);
3620 strbuf_release(&ref_name);
3622 return ret;
3625 __attribute__((format (printf, 3, 4)))
3626 static const char *reflog_message(struct replay_opts *opts,
3627 const char *sub_action, const char *fmt, ...)
3629 va_list ap;
3630 static struct strbuf buf = STRBUF_INIT;
3631 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3633 va_start(ap, fmt);
3634 strbuf_reset(&buf);
3635 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3636 if (sub_action)
3637 strbuf_addf(&buf, " (%s)", sub_action);
3638 if (fmt) {
3639 strbuf_addstr(&buf, ": ");
3640 strbuf_vaddf(&buf, fmt, ap);
3642 va_end(ap);
3644 return buf.buf;
3647 static int do_reset(struct repository *r,
3648 const char *name, int len,
3649 struct replay_opts *opts)
3651 struct strbuf ref_name = STRBUF_INIT;
3652 struct object_id oid;
3653 struct lock_file lock = LOCK_INIT;
3654 struct tree_desc desc;
3655 struct tree *tree;
3656 struct unpack_trees_options unpack_tree_opts;
3657 int ret = 0;
3659 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3660 return -1;
3662 if (len == 10 && !strncmp("[new root]", name, len)) {
3663 if (!opts->have_squash_onto) {
3664 const char *hex;
3665 if (commit_tree("", 0, the_hash_algo->empty_tree,
3666 NULL, &opts->squash_onto,
3667 NULL, NULL))
3668 return error(_("writing fake root commit"));
3669 opts->have_squash_onto = 1;
3670 hex = oid_to_hex(&opts->squash_onto);
3671 if (write_message(hex, strlen(hex),
3672 rebase_path_squash_onto(), 0))
3673 return error(_("writing squash-onto"));
3675 oidcpy(&oid, &opts->squash_onto);
3676 } else {
3677 int i;
3679 /* Determine the length of the label */
3680 for (i = 0; i < len; i++)
3681 if (isspace(name[i]))
3682 break;
3683 len = i;
3685 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3686 if (get_oid(ref_name.buf, &oid) &&
3687 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3688 error(_("could not read '%s'"), ref_name.buf);
3689 rollback_lock_file(&lock);
3690 strbuf_release(&ref_name);
3691 return -1;
3695 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3696 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3697 unpack_tree_opts.head_idx = 1;
3698 unpack_tree_opts.src_index = r->index;
3699 unpack_tree_opts.dst_index = r->index;
3700 unpack_tree_opts.fn = oneway_merge;
3701 unpack_tree_opts.merge = 1;
3702 unpack_tree_opts.update = 1;
3703 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3704 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3706 if (repo_read_index_unmerged(r)) {
3707 rollback_lock_file(&lock);
3708 strbuf_release(&ref_name);
3709 return error_resolve_conflict(_(action_name(opts)));
3712 if (!fill_tree_descriptor(r, &desc, &oid)) {
3713 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3714 rollback_lock_file(&lock);
3715 free((void *)desc.buffer);
3716 strbuf_release(&ref_name);
3717 return -1;
3720 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3721 rollback_lock_file(&lock);
3722 free((void *)desc.buffer);
3723 strbuf_release(&ref_name);
3724 return -1;
3727 tree = parse_tree_indirect(&oid);
3728 prime_cache_tree(r, r->index, tree);
3730 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3731 ret = error(_("could not write index"));
3732 free((void *)desc.buffer);
3734 if (!ret)
3735 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3736 len, name), "HEAD", &oid,
3737 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3739 strbuf_release(&ref_name);
3740 return ret;
3743 static struct commit *lookup_label(const char *label, int len,
3744 struct strbuf *buf)
3746 struct commit *commit;
3748 strbuf_reset(buf);
3749 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3750 commit = lookup_commit_reference_by_name(buf->buf);
3751 if (!commit) {
3752 /* fall back to non-rewritten ref or commit */
3753 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3754 commit = lookup_commit_reference_by_name(buf->buf);
3757 if (!commit)
3758 error(_("could not resolve '%s'"), buf->buf);
3760 return commit;
3763 static int do_merge(struct repository *r,
3764 struct commit *commit,
3765 const char *arg, int arg_len,
3766 int flags, int *check_todo, struct replay_opts *opts)
3768 int run_commit_flags = 0;
3769 struct strbuf ref_name = STRBUF_INIT;
3770 struct commit *head_commit, *merge_commit, *i;
3771 struct commit_list *bases, *j, *reversed = NULL;
3772 struct commit_list *to_merge = NULL, **tail = &to_merge;
3773 const char *strategy = !opts->xopts_nr &&
3774 (!opts->strategy ||
3775 !strcmp(opts->strategy, "recursive") ||
3776 !strcmp(opts->strategy, "ort")) ?
3777 NULL : opts->strategy;
3778 struct merge_options o;
3779 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3780 static struct lock_file lock;
3781 const char *p;
3783 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3784 ret = -1;
3785 goto leave_merge;
3788 head_commit = lookup_commit_reference_by_name("HEAD");
3789 if (!head_commit) {
3790 ret = error(_("cannot merge without a current revision"));
3791 goto leave_merge;
3795 * For octopus merges, the arg starts with the list of revisions to be
3796 * merged. The list is optionally followed by '#' and the oneline.
3798 merge_arg_len = oneline_offset = arg_len;
3799 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3800 if (!*p)
3801 break;
3802 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3803 p += 1 + strspn(p + 1, " \t\n");
3804 oneline_offset = p - arg;
3805 break;
3807 k = strcspn(p, " \t\n");
3808 if (!k)
3809 continue;
3810 merge_commit = lookup_label(p, k, &ref_name);
3811 if (!merge_commit) {
3812 ret = error(_("unable to parse '%.*s'"), k, p);
3813 goto leave_merge;
3815 tail = &commit_list_insert(merge_commit, tail)->next;
3816 p += k;
3817 merge_arg_len = p - arg;
3820 if (!to_merge) {
3821 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3822 goto leave_merge;
3825 if (opts->have_squash_onto &&
3826 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3828 * When the user tells us to "merge" something into a
3829 * "[new root]", let's simply fast-forward to the merge head.
3831 rollback_lock_file(&lock);
3832 if (to_merge->next)
3833 ret = error(_("octopus merge cannot be executed on "
3834 "top of a [new root]"));
3835 else
3836 ret = fast_forward_to(r, &to_merge->item->object.oid,
3837 &head_commit->object.oid, 0,
3838 opts);
3839 goto leave_merge;
3843 * If HEAD is not identical to the first parent of the original merge
3844 * commit, we cannot fast-forward.
3846 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3847 oideq(&commit->parents->item->object.oid,
3848 &head_commit->object.oid);
3851 * If any merge head is different from the original one, we cannot
3852 * fast-forward.
3854 if (can_fast_forward) {
3855 struct commit_list *p = commit->parents->next;
3857 for (j = to_merge; j && p; j = j->next, p = p->next)
3858 if (!oideq(&j->item->object.oid,
3859 &p->item->object.oid)) {
3860 can_fast_forward = 0;
3861 break;
3864 * If the number of merge heads differs from the original merge
3865 * commit, we cannot fast-forward.
3867 if (j || p)
3868 can_fast_forward = 0;
3871 if (can_fast_forward) {
3872 rollback_lock_file(&lock);
3873 ret = fast_forward_to(r, &commit->object.oid,
3874 &head_commit->object.oid, 0, opts);
3875 if (flags & TODO_EDIT_MERGE_MSG)
3876 goto fast_forward_edit;
3878 goto leave_merge;
3881 if (commit) {
3882 const char *encoding = get_commit_output_encoding();
3883 const char *message = logmsg_reencode(commit, NULL, encoding);
3884 const char *body;
3885 int len;
3887 if (!message) {
3888 ret = error(_("could not get commit message of '%s'"),
3889 oid_to_hex(&commit->object.oid));
3890 goto leave_merge;
3892 write_author_script(message);
3893 find_commit_subject(message, &body);
3894 len = strlen(body);
3895 ret = write_message(body, len, git_path_merge_msg(r), 0);
3896 unuse_commit_buffer(commit, message);
3897 if (ret) {
3898 error_errno(_("could not write '%s'"),
3899 git_path_merge_msg(r));
3900 goto leave_merge;
3902 } else {
3903 struct strbuf buf = STRBUF_INIT;
3904 int len;
3906 strbuf_addf(&buf, "author %s", git_author_info(0));
3907 write_author_script(buf.buf);
3908 strbuf_reset(&buf);
3910 if (oneline_offset < arg_len) {
3911 p = arg + oneline_offset;
3912 len = arg_len - oneline_offset;
3913 } else {
3914 strbuf_addf(&buf, "Merge %s '%.*s'",
3915 to_merge->next ? "branches" : "branch",
3916 merge_arg_len, arg);
3917 p = buf.buf;
3918 len = buf.len;
3921 ret = write_message(p, len, git_path_merge_msg(r), 0);
3922 strbuf_release(&buf);
3923 if (ret) {
3924 error_errno(_("could not write '%s'"),
3925 git_path_merge_msg(r));
3926 goto leave_merge;
3930 if (strategy || to_merge->next) {
3931 /* Octopus merge */
3932 struct child_process cmd = CHILD_PROCESS_INIT;
3934 if (read_env_script(&cmd.env_array)) {
3935 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3937 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3938 goto leave_merge;
3941 if (opts->committer_date_is_author_date)
3942 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3943 opts->ignore_date ?
3944 "" :
3945 author_date_from_env_array(&cmd.env_array));
3946 if (opts->ignore_date)
3947 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3949 cmd.git_cmd = 1;
3950 strvec_push(&cmd.args, "merge");
3951 strvec_push(&cmd.args, "-s");
3952 if (!strategy)
3953 strvec_push(&cmd.args, "octopus");
3954 else {
3955 strvec_push(&cmd.args, strategy);
3956 for (k = 0; k < opts->xopts_nr; k++)
3957 strvec_pushf(&cmd.args,
3958 "-X%s", opts->xopts[k]);
3960 if (!(flags & TODO_EDIT_MERGE_MSG))
3961 strvec_push(&cmd.args, "--no-edit");
3962 else
3963 strvec_push(&cmd.args, "--edit");
3964 strvec_push(&cmd.args, "--no-ff");
3965 strvec_push(&cmd.args, "--no-log");
3966 strvec_push(&cmd.args, "--no-stat");
3967 strvec_push(&cmd.args, "-F");
3968 strvec_push(&cmd.args, git_path_merge_msg(r));
3969 if (opts->gpg_sign)
3970 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3971 else
3972 strvec_push(&cmd.args, "--no-gpg-sign");
3974 /* Add the tips to be merged */
3975 for (j = to_merge; j; j = j->next)
3976 strvec_push(&cmd.args,
3977 oid_to_hex(&j->item->object.oid));
3979 strbuf_release(&ref_name);
3980 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3981 NULL, 0);
3982 rollback_lock_file(&lock);
3984 ret = run_command(&cmd);
3986 /* force re-reading of the cache */
3987 if (!ret && (discard_index(r->index) < 0 ||
3988 repo_read_index(r) < 0))
3989 ret = error(_("could not read index"));
3990 goto leave_merge;
3993 merge_commit = to_merge->item;
3994 bases = get_merge_bases(head_commit, merge_commit);
3995 if (bases && oideq(&merge_commit->object.oid,
3996 &bases->item->object.oid)) {
3997 ret = 0;
3998 /* skip merging an ancestor of HEAD */
3999 goto leave_merge;
4002 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4003 git_path_merge_head(r), 0);
4004 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4006 for (j = bases; j; j = j->next)
4007 commit_list_insert(j->item, &reversed);
4008 free_commit_list(bases);
4010 repo_read_index(r);
4011 init_merge_options(&o, r);
4012 o.branch1 = "HEAD";
4013 o.branch2 = ref_name.buf;
4014 o.buffer_output = 2;
4016 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4018 * TODO: Should use merge_incore_recursive() and
4019 * merge_switch_to_result(), skipping the call to
4020 * merge_switch_to_result() when we don't actually need to
4021 * update the index and working copy immediately.
4023 ret = merge_ort_recursive(&o,
4024 head_commit, merge_commit, reversed,
4025 &i);
4026 } else {
4027 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4028 &i);
4030 if (ret <= 0)
4031 fputs(o.obuf.buf, stdout);
4032 strbuf_release(&o.obuf);
4033 if (ret < 0) {
4034 error(_("could not even attempt to merge '%.*s'"),
4035 merge_arg_len, arg);
4036 goto leave_merge;
4039 * The return value of merge_recursive() is 1 on clean, and 0 on
4040 * unclean merge.
4042 * Let's reverse that, so that do_merge() returns 0 upon success and
4043 * 1 upon failed merge (keeping the return value -1 for the cases where
4044 * we will want to reschedule the `merge` command).
4046 ret = !ret;
4048 if (r->index->cache_changed &&
4049 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4050 ret = error(_("merge: Unable to write new index file"));
4051 goto leave_merge;
4054 rollback_lock_file(&lock);
4055 if (ret)
4056 repo_rerere(r, opts->allow_rerere_auto);
4057 else
4059 * In case of problems, we now want to return a positive
4060 * value (a negative one would indicate that the `merge`
4061 * command needs to be rescheduled).
4063 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4064 run_commit_flags);
4066 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4067 fast_forward_edit:
4068 *check_todo = 1;
4069 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4070 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4074 leave_merge:
4075 strbuf_release(&ref_name);
4076 rollback_lock_file(&lock);
4077 free_commit_list(to_merge);
4078 return ret;
4081 static int is_final_fixup(struct todo_list *todo_list)
4083 int i = todo_list->current;
4085 if (!is_fixup(todo_list->items[i].command))
4086 return 0;
4088 while (++i < todo_list->nr)
4089 if (is_fixup(todo_list->items[i].command))
4090 return 0;
4091 else if (!is_noop(todo_list->items[i].command))
4092 break;
4093 return 1;
4096 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4098 int i;
4100 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4101 if (!is_noop(todo_list->items[i].command))
4102 return todo_list->items[i].command;
4104 return -1;
4107 void create_autostash(struct repository *r, const char *path,
4108 const char *default_reflog_action)
4110 struct strbuf buf = STRBUF_INIT;
4111 struct lock_file lock_file = LOCK_INIT;
4112 int fd;
4114 fd = repo_hold_locked_index(r, &lock_file, 0);
4115 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4116 if (0 <= fd)
4117 repo_update_index_if_able(r, &lock_file);
4118 rollback_lock_file(&lock_file);
4120 if (has_unstaged_changes(r, 1) ||
4121 has_uncommitted_changes(r, 1)) {
4122 struct child_process stash = CHILD_PROCESS_INIT;
4123 struct object_id oid;
4125 strvec_pushl(&stash.args,
4126 "stash", "create", "autostash", NULL);
4127 stash.git_cmd = 1;
4128 stash.no_stdin = 1;
4129 strbuf_reset(&buf);
4130 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4131 die(_("Cannot autostash"));
4132 strbuf_trim_trailing_newline(&buf);
4133 if (get_oid(buf.buf, &oid))
4134 die(_("Unexpected stash response: '%s'"),
4135 buf.buf);
4136 strbuf_reset(&buf);
4137 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4139 if (safe_create_leading_directories_const(path))
4140 die(_("Could not create directory for '%s'"),
4141 path);
4142 write_file(path, "%s", oid_to_hex(&oid));
4143 printf(_("Created autostash: %s\n"), buf.buf);
4144 if (reset_head(r, NULL, "reset --hard",
4145 NULL, RESET_HEAD_HARD, NULL, NULL,
4146 default_reflog_action) < 0)
4147 die(_("could not reset --hard"));
4149 if (discard_index(r->index) < 0 ||
4150 repo_read_index(r) < 0)
4151 die(_("could not read index"));
4153 strbuf_release(&buf);
4156 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4158 struct child_process child = CHILD_PROCESS_INIT;
4159 int ret = 0;
4161 if (attempt_apply) {
4162 child.git_cmd = 1;
4163 child.no_stdout = 1;
4164 child.no_stderr = 1;
4165 strvec_push(&child.args, "stash");
4166 strvec_push(&child.args, "apply");
4167 strvec_push(&child.args, stash_oid);
4168 ret = run_command(&child);
4171 if (attempt_apply && !ret)
4172 fprintf(stderr, _("Applied autostash.\n"));
4173 else {
4174 struct child_process store = CHILD_PROCESS_INIT;
4176 store.git_cmd = 1;
4177 strvec_push(&store.args, "stash");
4178 strvec_push(&store.args, "store");
4179 strvec_push(&store.args, "-m");
4180 strvec_push(&store.args, "autostash");
4181 strvec_push(&store.args, "-q");
4182 strvec_push(&store.args, stash_oid);
4183 if (run_command(&store))
4184 ret = error(_("cannot store %s"), stash_oid);
4185 else
4186 fprintf(stderr,
4187 _("%s\n"
4188 "Your changes are safe in the stash.\n"
4189 "You can run \"git stash pop\" or"
4190 " \"git stash drop\" at any time.\n"),
4191 attempt_apply ?
4192 _("Applying autostash resulted in conflicts.") :
4193 _("Autostash exists; creating a new stash entry."));
4196 return ret;
4199 static int apply_save_autostash(const char *path, int attempt_apply)
4201 struct strbuf stash_oid = STRBUF_INIT;
4202 int ret = 0;
4204 if (!read_oneliner(&stash_oid, path,
4205 READ_ONELINER_SKIP_IF_EMPTY)) {
4206 strbuf_release(&stash_oid);
4207 return 0;
4209 strbuf_trim(&stash_oid);
4211 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4213 unlink(path);
4214 strbuf_release(&stash_oid);
4215 return ret;
4218 int save_autostash(const char *path)
4220 return apply_save_autostash(path, 0);
4223 int apply_autostash(const char *path)
4225 return apply_save_autostash(path, 1);
4228 int apply_autostash_oid(const char *stash_oid)
4230 return apply_save_autostash_oid(stash_oid, 1);
4233 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4234 const char *commit, const char *action)
4236 struct child_process cmd = CHILD_PROCESS_INIT;
4237 int ret;
4239 cmd.git_cmd = 1;
4241 strvec_push(&cmd.args, "checkout");
4242 strvec_push(&cmd.args, commit);
4243 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4245 if (opts->verbose)
4246 ret = run_command(&cmd);
4247 else
4248 ret = run_command_silent_on_success(&cmd);
4250 if (!ret)
4251 discard_index(r->index);
4253 return ret;
4256 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4257 const char *onto_name, const struct object_id *onto,
4258 const struct object_id *orig_head)
4260 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4262 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4263 apply_autostash(rebase_path_autostash());
4264 sequencer_remove_state(opts);
4265 return error(_("could not detach HEAD"));
4268 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4271 static int stopped_at_head(struct repository *r)
4273 struct object_id head;
4274 struct commit *commit;
4275 struct commit_message message;
4277 if (get_oid("HEAD", &head) ||
4278 !(commit = lookup_commit(r, &head)) ||
4279 parse_commit(commit) || get_message(commit, &message))
4280 fprintf(stderr, _("Stopped at HEAD\n"));
4281 else {
4282 fprintf(stderr, _("Stopped at %s\n"), message.label);
4283 free_message(commit, &message);
4285 return 0;
4289 static int reread_todo_if_changed(struct repository *r,
4290 struct todo_list *todo_list,
4291 struct replay_opts *opts)
4293 int offset;
4294 struct strbuf buf = STRBUF_INIT;
4296 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4297 return -1;
4298 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4299 if (buf.len != todo_list->buf.len - offset ||
4300 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4301 /* Reread the todo file if it has changed. */
4302 todo_list_release(todo_list);
4303 if (read_populate_todo(r, todo_list, opts))
4304 return -1; /* message was printed */
4305 /* `current` will be incremented on return */
4306 todo_list->current = -1;
4308 strbuf_release(&buf);
4310 return 0;
4313 static const char rescheduled_advice[] =
4314 N_("Could not execute the todo command\n"
4315 "\n"
4316 " %.*s"
4317 "\n"
4318 "It has been rescheduled; To edit the command before continuing, please\n"
4319 "edit the todo list first:\n"
4320 "\n"
4321 " git rebase --edit-todo\n"
4322 " git rebase --continue\n");
4324 static int pick_commits(struct repository *r,
4325 struct todo_list *todo_list,
4326 struct replay_opts *opts)
4328 int res = 0, reschedule = 0;
4329 char *prev_reflog_action;
4331 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4332 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4333 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4334 if (opts->allow_ff)
4335 assert(!(opts->signoff || opts->no_commit ||
4336 opts->record_origin || should_edit(opts) ||
4337 opts->committer_date_is_author_date ||
4338 opts->ignore_date));
4339 if (read_and_refresh_cache(r, opts))
4340 return -1;
4342 while (todo_list->current < todo_list->nr) {
4343 struct todo_item *item = todo_list->items + todo_list->current;
4344 const char *arg = todo_item_get_arg(todo_list, item);
4345 int check_todo = 0;
4347 if (save_todo(todo_list, opts))
4348 return -1;
4349 if (is_rebase_i(opts)) {
4350 if (item->command != TODO_COMMENT) {
4351 FILE *f = fopen(rebase_path_msgnum(), "w");
4353 todo_list->done_nr++;
4355 if (f) {
4356 fprintf(f, "%d\n", todo_list->done_nr);
4357 fclose(f);
4359 if (!opts->quiet)
4360 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4361 todo_list->done_nr,
4362 todo_list->total_nr,
4363 opts->verbose ? "\n" : "\r");
4365 unlink(rebase_path_message());
4366 unlink(rebase_path_author_script());
4367 unlink(rebase_path_stopped_sha());
4368 unlink(rebase_path_amend());
4369 unlink(git_path_merge_head(r));
4370 unlink(git_path_auto_merge(r));
4371 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4373 if (item->command == TODO_BREAK) {
4374 if (!opts->verbose)
4375 term_clear_line();
4376 return stopped_at_head(r);
4379 if (item->command <= TODO_SQUASH) {
4380 if (is_rebase_i(opts))
4381 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4382 command_to_string(item->command), NULL),
4384 res = do_pick_commit(r, item, opts,
4385 is_final_fixup(todo_list),
4386 &check_todo);
4387 if (is_rebase_i(opts))
4388 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4389 if (is_rebase_i(opts) && res < 0) {
4390 /* Reschedule */
4391 advise(_(rescheduled_advice),
4392 get_item_line_length(todo_list,
4393 todo_list->current),
4394 get_item_line(todo_list,
4395 todo_list->current));
4396 todo_list->current--;
4397 if (save_todo(todo_list, opts))
4398 return -1;
4400 if (item->command == TODO_EDIT) {
4401 struct commit *commit = item->commit;
4402 if (!res) {
4403 if (!opts->verbose)
4404 term_clear_line();
4405 fprintf(stderr,
4406 _("Stopped at %s... %.*s\n"),
4407 short_commit_name(commit),
4408 item->arg_len, arg);
4410 return error_with_patch(r, commit,
4411 arg, item->arg_len, opts, res, !res);
4413 if (is_rebase_i(opts) && !res)
4414 record_in_rewritten(&item->commit->object.oid,
4415 peek_command(todo_list, 1));
4416 if (res && is_fixup(item->command)) {
4417 if (res == 1)
4418 intend_to_amend();
4419 return error_failed_squash(r, item->commit, opts,
4420 item->arg_len, arg);
4421 } else if (res && is_rebase_i(opts) && item->commit) {
4422 int to_amend = 0;
4423 struct object_id oid;
4426 * If we are rewording and have either
4427 * fast-forwarded already, or are about to
4428 * create a new root commit, we want to amend,
4429 * otherwise we do not.
4431 if (item->command == TODO_REWORD &&
4432 !get_oid("HEAD", &oid) &&
4433 (oideq(&item->commit->object.oid, &oid) ||
4434 (opts->have_squash_onto &&
4435 oideq(&opts->squash_onto, &oid))))
4436 to_amend = 1;
4438 return res | error_with_patch(r, item->commit,
4439 arg, item->arg_len, opts,
4440 res, to_amend);
4442 } else if (item->command == TODO_EXEC) {
4443 char *end_of_arg = (char *)(arg + item->arg_len);
4444 int saved = *end_of_arg;
4446 if (!opts->verbose)
4447 term_clear_line();
4448 *end_of_arg = '\0';
4449 res = do_exec(r, arg);
4450 *end_of_arg = saved;
4452 if (res) {
4453 if (opts->reschedule_failed_exec)
4454 reschedule = 1;
4456 check_todo = 1;
4457 } else if (item->command == TODO_LABEL) {
4458 if ((res = do_label(r, arg, item->arg_len)))
4459 reschedule = 1;
4460 } else if (item->command == TODO_RESET) {
4461 if ((res = do_reset(r, arg, item->arg_len, opts)))
4462 reschedule = 1;
4463 } else if (item->command == TODO_MERGE) {
4464 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4465 item->flags, &check_todo, opts)) < 0)
4466 reschedule = 1;
4467 else if (item->commit)
4468 record_in_rewritten(&item->commit->object.oid,
4469 peek_command(todo_list, 1));
4470 if (res > 0)
4471 /* failed with merge conflicts */
4472 return error_with_patch(r, item->commit,
4473 arg, item->arg_len,
4474 opts, res, 0);
4475 } else if (!is_noop(item->command))
4476 return error(_("unknown command %d"), item->command);
4478 if (reschedule) {
4479 advise(_(rescheduled_advice),
4480 get_item_line_length(todo_list,
4481 todo_list->current),
4482 get_item_line(todo_list, todo_list->current));
4483 todo_list->current--;
4484 if (save_todo(todo_list, opts))
4485 return -1;
4486 if (item->commit)
4487 return error_with_patch(r,
4488 item->commit,
4489 arg, item->arg_len,
4490 opts, res, 0);
4491 } else if (is_rebase_i(opts) && check_todo && !res &&
4492 reread_todo_if_changed(r, todo_list, opts)) {
4493 return -1;
4496 todo_list->current++;
4497 if (res)
4498 return res;
4501 if (is_rebase_i(opts)) {
4502 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4503 struct stat st;
4505 /* Stopped in the middle, as planned? */
4506 if (todo_list->current < todo_list->nr)
4507 return 0;
4509 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4510 starts_with(head_ref.buf, "refs/")) {
4511 const char *msg;
4512 struct object_id head, orig;
4513 int res;
4515 if (get_oid("HEAD", &head)) {
4516 res = error(_("cannot read HEAD"));
4517 cleanup_head_ref:
4518 strbuf_release(&head_ref);
4519 strbuf_release(&buf);
4520 return res;
4522 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4523 get_oid_hex(buf.buf, &orig)) {
4524 res = error(_("could not read orig-head"));
4525 goto cleanup_head_ref;
4527 strbuf_reset(&buf);
4528 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4529 res = error(_("could not read 'onto'"));
4530 goto cleanup_head_ref;
4532 msg = reflog_message(opts, "finish", "%s onto %s",
4533 head_ref.buf, buf.buf);
4534 if (update_ref(msg, head_ref.buf, &head, &orig,
4535 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4536 res = error(_("could not update %s"),
4537 head_ref.buf);
4538 goto cleanup_head_ref;
4540 msg = reflog_message(opts, "finish", "returning to %s",
4541 head_ref.buf);
4542 if (create_symref("HEAD", head_ref.buf, msg)) {
4543 res = error(_("could not update HEAD to %s"),
4544 head_ref.buf);
4545 goto cleanup_head_ref;
4547 strbuf_reset(&buf);
4550 if (opts->verbose) {
4551 struct rev_info log_tree_opt;
4552 struct object_id orig, head;
4554 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4555 repo_init_revisions(r, &log_tree_opt, NULL);
4556 log_tree_opt.diff = 1;
4557 log_tree_opt.diffopt.output_format =
4558 DIFF_FORMAT_DIFFSTAT;
4559 log_tree_opt.disable_stdin = 1;
4561 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4562 !get_oid(buf.buf, &orig) &&
4563 !get_oid("HEAD", &head)) {
4564 diff_tree_oid(&orig, &head, "",
4565 &log_tree_opt.diffopt);
4566 log_tree_diff_flush(&log_tree_opt);
4569 flush_rewritten_pending();
4570 if (!stat(rebase_path_rewritten_list(), &st) &&
4571 st.st_size > 0) {
4572 struct child_process child = CHILD_PROCESS_INIT;
4573 const char *post_rewrite_hook =
4574 find_hook("post-rewrite");
4576 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4577 child.git_cmd = 1;
4578 strvec_push(&child.args, "notes");
4579 strvec_push(&child.args, "copy");
4580 strvec_push(&child.args, "--for-rewrite=rebase");
4581 /* we don't care if this copying failed */
4582 run_command(&child);
4584 if (post_rewrite_hook) {
4585 struct child_process hook = CHILD_PROCESS_INIT;
4587 hook.in = open(rebase_path_rewritten_list(),
4588 O_RDONLY);
4589 hook.stdout_to_stderr = 1;
4590 hook.trace2_hook_name = "post-rewrite";
4591 strvec_push(&hook.args, post_rewrite_hook);
4592 strvec_push(&hook.args, "rebase");
4593 /* we don't care if this hook failed */
4594 run_command(&hook);
4597 apply_autostash(rebase_path_autostash());
4599 if (!opts->quiet) {
4600 if (!opts->verbose)
4601 term_clear_line();
4602 fprintf(stderr,
4603 _("Successfully rebased and updated %s.\n"),
4604 head_ref.buf);
4607 strbuf_release(&buf);
4608 strbuf_release(&head_ref);
4612 * Sequence of picks finished successfully; cleanup by
4613 * removing the .git/sequencer directory
4615 return sequencer_remove_state(opts);
4618 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4620 struct strvec argv = STRVEC_INIT;
4621 int ret;
4623 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4624 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4625 return error(_("no cherry-pick or revert in progress"));
4627 strvec_push(&argv, "commit");
4630 * continue_single_pick() handles the case of recovering from a
4631 * conflict. should_edit() doesn't handle that case; for a conflict,
4632 * we want to edit if the user asked for it, or if they didn't specify
4633 * and stdin is a tty.
4635 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4637 * Include --cleanup=strip as well because we don't want the
4638 * "# Conflicts:" messages.
4640 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4642 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4643 strvec_clear(&argv);
4644 return ret;
4647 static int commit_staged_changes(struct repository *r,
4648 struct replay_opts *opts,
4649 struct todo_list *todo_list)
4651 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4652 unsigned int final_fixup = 0, is_clean;
4654 if (has_unstaged_changes(r, 1))
4655 return error(_("cannot rebase: You have unstaged changes."));
4657 is_clean = !has_uncommitted_changes(r, 0);
4659 if (file_exists(rebase_path_amend())) {
4660 struct strbuf rev = STRBUF_INIT;
4661 struct object_id head, to_amend;
4663 if (get_oid("HEAD", &head))
4664 return error(_("cannot amend non-existing commit"));
4665 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4666 return error(_("invalid file: '%s'"), rebase_path_amend());
4667 if (get_oid_hex(rev.buf, &to_amend))
4668 return error(_("invalid contents: '%s'"),
4669 rebase_path_amend());
4670 if (!is_clean && !oideq(&head, &to_amend))
4671 return error(_("\nYou have uncommitted changes in your "
4672 "working tree. Please, commit them\n"
4673 "first and then run 'git rebase "
4674 "--continue' again."));
4676 * When skipping a failed fixup/squash, we need to edit the
4677 * commit message, the current fixup list and count, and if it
4678 * was the last fixup/squash in the chain, we need to clean up
4679 * the commit message and if there was a squash, let the user
4680 * edit it.
4682 if (!is_clean || !opts->current_fixup_count)
4683 ; /* this is not the final fixup */
4684 else if (!oideq(&head, &to_amend) ||
4685 !file_exists(rebase_path_stopped_sha())) {
4686 /* was a final fixup or squash done manually? */
4687 if (!is_fixup(peek_command(todo_list, 0))) {
4688 unlink(rebase_path_fixup_msg());
4689 unlink(rebase_path_squash_msg());
4690 unlink(rebase_path_current_fixups());
4691 strbuf_reset(&opts->current_fixups);
4692 opts->current_fixup_count = 0;
4694 } else {
4695 /* we are in a fixup/squash chain */
4696 const char *p = opts->current_fixups.buf;
4697 int len = opts->current_fixups.len;
4699 opts->current_fixup_count--;
4700 if (!len)
4701 BUG("Incorrect current_fixups:\n%s", p);
4702 while (len && p[len - 1] != '\n')
4703 len--;
4704 strbuf_setlen(&opts->current_fixups, len);
4705 if (write_message(p, len, rebase_path_current_fixups(),
4706 0) < 0)
4707 return error(_("could not write file: '%s'"),
4708 rebase_path_current_fixups());
4711 * If a fixup/squash in a fixup/squash chain failed, the
4712 * commit message is already correct, no need to commit
4713 * it again.
4715 * Only if it is the final command in the fixup/squash
4716 * chain, and only if the chain is longer than a single
4717 * fixup/squash command (which was just skipped), do we
4718 * actually need to re-commit with a cleaned up commit
4719 * message.
4721 if (opts->current_fixup_count > 0 &&
4722 !is_fixup(peek_command(todo_list, 0))) {
4723 final_fixup = 1;
4725 * If there was not a single "squash" in the
4726 * chain, we only need to clean up the commit
4727 * message, no need to bother the user with
4728 * opening the commit message in the editor.
4730 if (!starts_with(p, "squash ") &&
4731 !strstr(p, "\nsquash "))
4732 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4733 } else if (is_fixup(peek_command(todo_list, 0))) {
4735 * We need to update the squash message to skip
4736 * the latest commit message.
4738 struct commit *commit;
4739 const char *path = rebase_path_squash_msg();
4740 const char *encoding = get_commit_output_encoding();
4742 if (parse_head(r, &commit) ||
4743 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4744 write_message(p, strlen(p), path, 0)) {
4745 unuse_commit_buffer(commit, p);
4746 return error(_("could not write file: "
4747 "'%s'"), path);
4749 unuse_commit_buffer(commit, p);
4753 strbuf_release(&rev);
4754 flags |= AMEND_MSG;
4757 if (is_clean) {
4758 if (refs_ref_exists(get_main_ref_store(r),
4759 "CHERRY_PICK_HEAD") &&
4760 refs_delete_ref(get_main_ref_store(r), "",
4761 "CHERRY_PICK_HEAD", NULL, 0))
4762 return error(_("could not remove CHERRY_PICK_HEAD"));
4763 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4764 return error_errno(_("could not remove '%s'"),
4765 git_path_merge_msg(r));
4766 if (!final_fixup)
4767 return 0;
4770 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4771 opts, flags))
4772 return error(_("could not commit staged changes."));
4773 unlink(rebase_path_amend());
4774 unlink(git_path_merge_head(r));
4775 unlink(git_path_auto_merge(r));
4776 if (final_fixup) {
4777 unlink(rebase_path_fixup_msg());
4778 unlink(rebase_path_squash_msg());
4780 if (opts->current_fixup_count > 0) {
4782 * Whether final fixup or not, we just cleaned up the commit
4783 * message...
4785 unlink(rebase_path_current_fixups());
4786 strbuf_reset(&opts->current_fixups);
4787 opts->current_fixup_count = 0;
4789 return 0;
4792 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4794 struct todo_list todo_list = TODO_LIST_INIT;
4795 int res;
4797 if (read_and_refresh_cache(r, opts))
4798 return -1;
4800 if (read_populate_opts(opts))
4801 return -1;
4802 if (is_rebase_i(opts)) {
4803 if ((res = read_populate_todo(r, &todo_list, opts)))
4804 goto release_todo_list;
4806 if (file_exists(rebase_path_dropped())) {
4807 if ((res = todo_list_check_against_backup(r, &todo_list)))
4808 goto release_todo_list;
4810 unlink(rebase_path_dropped());
4813 if (commit_staged_changes(r, opts, &todo_list)) {
4814 res = -1;
4815 goto release_todo_list;
4817 } else if (!file_exists(get_todo_path(opts)))
4818 return continue_single_pick(r, opts);
4819 else if ((res = read_populate_todo(r, &todo_list, opts)))
4820 goto release_todo_list;
4822 if (!is_rebase_i(opts)) {
4823 /* Verify that the conflict has been resolved */
4824 if (refs_ref_exists(get_main_ref_store(r),
4825 "CHERRY_PICK_HEAD") ||
4826 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4827 res = continue_single_pick(r, opts);
4828 if (res)
4829 goto release_todo_list;
4831 if (index_differs_from(r, "HEAD", NULL, 0)) {
4832 res = error_dirty_index(r, opts);
4833 goto release_todo_list;
4835 todo_list.current++;
4836 } else if (file_exists(rebase_path_stopped_sha())) {
4837 struct strbuf buf = STRBUF_INIT;
4838 struct object_id oid;
4840 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4841 READ_ONELINER_SKIP_IF_EMPTY) &&
4842 !get_oid_hex(buf.buf, &oid))
4843 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4844 strbuf_release(&buf);
4847 res = pick_commits(r, &todo_list, opts);
4848 release_todo_list:
4849 todo_list_release(&todo_list);
4850 return res;
4853 static int single_pick(struct repository *r,
4854 struct commit *cmit,
4855 struct replay_opts *opts)
4857 int check_todo;
4858 struct todo_item item;
4860 item.command = opts->action == REPLAY_PICK ?
4861 TODO_PICK : TODO_REVERT;
4862 item.commit = cmit;
4864 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4865 return do_pick_commit(r, &item, opts, 0, &check_todo);
4868 int sequencer_pick_revisions(struct repository *r,
4869 struct replay_opts *opts)
4871 struct todo_list todo_list = TODO_LIST_INIT;
4872 struct object_id oid;
4873 int i, res;
4875 assert(opts->revs);
4876 if (read_and_refresh_cache(r, opts))
4877 return -1;
4879 for (i = 0; i < opts->revs->pending.nr; i++) {
4880 struct object_id oid;
4881 const char *name = opts->revs->pending.objects[i].name;
4883 /* This happens when using --stdin. */
4884 if (!strlen(name))
4885 continue;
4887 if (!get_oid(name, &oid)) {
4888 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4889 enum object_type type = oid_object_info(r,
4890 &oid,
4891 NULL);
4892 return error(_("%s: can't cherry-pick a %s"),
4893 name, type_name(type));
4895 } else
4896 return error(_("%s: bad revision"), name);
4900 * If we were called as "git cherry-pick <commit>", just
4901 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4902 * REVERT_HEAD, and don't touch the sequencer state.
4903 * This means it is possible to cherry-pick in the middle
4904 * of a cherry-pick sequence.
4906 if (opts->revs->cmdline.nr == 1 &&
4907 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4908 opts->revs->no_walk &&
4909 !opts->revs->cmdline.rev->flags) {
4910 struct commit *cmit;
4911 if (prepare_revision_walk(opts->revs))
4912 return error(_("revision walk setup failed"));
4913 cmit = get_revision(opts->revs);
4914 if (!cmit)
4915 return error(_("empty commit set passed"));
4916 if (get_revision(opts->revs))
4917 BUG("unexpected extra commit from walk");
4918 return single_pick(r, cmit, opts);
4922 * Start a new cherry-pick/ revert sequence; but
4923 * first, make sure that an existing one isn't in
4924 * progress
4927 if (walk_revs_populate_todo(&todo_list, opts) ||
4928 create_seq_dir(r) < 0)
4929 return -1;
4930 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4931 return error(_("can't revert as initial commit"));
4932 if (save_head(oid_to_hex(&oid)))
4933 return -1;
4934 if (save_opts(opts))
4935 return -1;
4936 update_abort_safety_file();
4937 res = pick_commits(r, &todo_list, opts);
4938 todo_list_release(&todo_list);
4939 return res;
4942 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4944 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4945 struct strbuf sob = STRBUF_INIT;
4946 int has_footer;
4948 strbuf_addstr(&sob, sign_off_header);
4949 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4950 strbuf_addch(&sob, '\n');
4952 if (!ignore_footer)
4953 strbuf_complete_line(msgbuf);
4956 * If the whole message buffer is equal to the sob, pretend that we
4957 * found a conforming footer with a matching sob
4959 if (msgbuf->len - ignore_footer == sob.len &&
4960 !strncmp(msgbuf->buf, sob.buf, sob.len))
4961 has_footer = 3;
4962 else
4963 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4965 if (!has_footer) {
4966 const char *append_newlines = NULL;
4967 size_t len = msgbuf->len - ignore_footer;
4969 if (!len) {
4971 * The buffer is completely empty. Leave foom for
4972 * the title and body to be filled in by the user.
4974 append_newlines = "\n\n";
4975 } else if (len == 1) {
4977 * Buffer contains a single newline. Add another
4978 * so that we leave room for the title and body.
4980 append_newlines = "\n";
4981 } else if (msgbuf->buf[len - 2] != '\n') {
4983 * Buffer ends with a single newline. Add another
4984 * so that there is an empty line between the message
4985 * body and the sob.
4987 append_newlines = "\n";
4988 } /* else, the buffer already ends with two newlines. */
4990 if (append_newlines)
4991 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4992 append_newlines, strlen(append_newlines));
4995 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4996 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4997 sob.buf, sob.len);
4999 strbuf_release(&sob);
5002 struct labels_entry {
5003 struct hashmap_entry entry;
5004 char label[FLEX_ARRAY];
5007 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
5008 const struct hashmap_entry *entry_or_key, const void *key)
5010 const struct labels_entry *a, *b;
5012 a = container_of(eptr, const struct labels_entry, entry);
5013 b = container_of(entry_or_key, const struct labels_entry, entry);
5015 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5018 struct string_entry {
5019 struct oidmap_entry entry;
5020 char string[FLEX_ARRAY];
5023 struct label_state {
5024 struct oidmap commit2label;
5025 struct hashmap labels;
5026 struct strbuf buf;
5029 static const char *label_oid(struct object_id *oid, const char *label,
5030 struct label_state *state)
5032 struct labels_entry *labels_entry;
5033 struct string_entry *string_entry;
5034 struct object_id dummy;
5035 int i;
5037 string_entry = oidmap_get(&state->commit2label, oid);
5038 if (string_entry)
5039 return string_entry->string;
5042 * For "uninteresting" commits, i.e. commits that are not to be
5043 * rebased, and which can therefore not be labeled, we use a unique
5044 * abbreviation of the commit name. This is slightly more complicated
5045 * than calling find_unique_abbrev() because we also need to make
5046 * sure that the abbreviation does not conflict with any other
5047 * label.
5049 * We disallow "interesting" commits to be labeled by a string that
5050 * is a valid full-length hash, to ensure that we always can find an
5051 * abbreviation for any uninteresting commit's names that does not
5052 * clash with any other label.
5054 strbuf_reset(&state->buf);
5055 if (!label) {
5056 char *p;
5058 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5059 label = p = state->buf.buf;
5061 find_unique_abbrev_r(p, oid, default_abbrev);
5064 * We may need to extend the abbreviated hash so that there is
5065 * no conflicting label.
5067 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5068 size_t i = strlen(p) + 1;
5070 oid_to_hex_r(p, oid);
5071 for (; i < the_hash_algo->hexsz; i++) {
5072 char save = p[i];
5073 p[i] = '\0';
5074 if (!hashmap_get_from_hash(&state->labels,
5075 strihash(p), p))
5076 break;
5077 p[i] = save;
5080 } else {
5081 struct strbuf *buf = &state->buf;
5084 * Sanitize labels by replacing non-alpha-numeric characters
5085 * (including white-space ones) by dashes, as they might be
5086 * illegal in file names (and hence in ref names).
5088 * Note that we retain non-ASCII UTF-8 characters (identified
5089 * via the most significant bit). They should be all acceptable
5090 * in file names. We do not validate the UTF-8 here, that's not
5091 * the job of this function.
5093 for (; *label; label++)
5094 if ((*label & 0x80) || isalnum(*label))
5095 strbuf_addch(buf, *label);
5096 /* avoid leading dash and double-dashes */
5097 else if (buf->len && buf->buf[buf->len - 1] != '-')
5098 strbuf_addch(buf, '-');
5099 if (!buf->len) {
5100 strbuf_addstr(buf, "rev-");
5101 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5103 label = buf->buf;
5105 if ((buf->len == the_hash_algo->hexsz &&
5106 !get_oid_hex(label, &dummy)) ||
5107 (buf->len == 1 && *label == '#') ||
5108 hashmap_get_from_hash(&state->labels,
5109 strihash(label), label)) {
5111 * If the label already exists, or if the label is a
5112 * valid full OID, or the label is a '#' (which we use
5113 * as a separator between merge heads and oneline), we
5114 * append a dash and a number to make it unique.
5116 size_t len = buf->len;
5118 for (i = 2; ; i++) {
5119 strbuf_setlen(buf, len);
5120 strbuf_addf(buf, "-%d", i);
5121 if (!hashmap_get_from_hash(&state->labels,
5122 strihash(buf->buf),
5123 buf->buf))
5124 break;
5127 label = buf->buf;
5131 FLEX_ALLOC_STR(labels_entry, label, label);
5132 hashmap_entry_init(&labels_entry->entry, strihash(label));
5133 hashmap_add(&state->labels, &labels_entry->entry);
5135 FLEX_ALLOC_STR(string_entry, string, label);
5136 oidcpy(&string_entry->entry.oid, oid);
5137 oidmap_put(&state->commit2label, string_entry);
5139 return string_entry->string;
5142 static int make_script_with_merges(struct pretty_print_context *pp,
5143 struct rev_info *revs, struct strbuf *out,
5144 unsigned flags)
5146 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5147 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5148 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5149 int skipped_commit = 0;
5150 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5151 struct strbuf label = STRBUF_INIT;
5152 struct commit_list *commits = NULL, **tail = &commits, *iter;
5153 struct commit_list *tips = NULL, **tips_tail = &tips;
5154 struct commit *commit;
5155 struct oidmap commit2todo = OIDMAP_INIT;
5156 struct string_entry *entry;
5157 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5158 shown = OIDSET_INIT;
5159 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5161 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5162 const char *cmd_pick = abbr ? "p" : "pick",
5163 *cmd_label = abbr ? "l" : "label",
5164 *cmd_reset = abbr ? "t" : "reset",
5165 *cmd_merge = abbr ? "m" : "merge";
5167 oidmap_init(&commit2todo, 0);
5168 oidmap_init(&state.commit2label, 0);
5169 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5170 strbuf_init(&state.buf, 32);
5172 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5173 struct labels_entry *onto_label_entry;
5174 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5175 FLEX_ALLOC_STR(entry, string, "onto");
5176 oidcpy(&entry->entry.oid, oid);
5177 oidmap_put(&state.commit2label, entry);
5179 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5180 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5181 hashmap_add(&state.labels, &onto_label_entry->entry);
5185 * First phase:
5186 * - get onelines for all commits
5187 * - gather all branch tips (i.e. 2nd or later parents of merges)
5188 * - label all branch tips
5190 while ((commit = get_revision(revs))) {
5191 struct commit_list *to_merge;
5192 const char *p1, *p2;
5193 struct object_id *oid;
5194 int is_empty;
5196 tail = &commit_list_insert(commit, tail)->next;
5197 oidset_insert(&interesting, &commit->object.oid);
5199 is_empty = is_original_commit_empty(commit);
5200 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5201 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5202 warning(_("skipped previously applied commit %s"),
5203 short_commit_name(commit));
5204 skipped_commit = 1;
5205 continue;
5207 if (is_empty && !keep_empty)
5208 continue;
5210 strbuf_reset(&oneline);
5211 pretty_print_commit(pp, commit, &oneline);
5213 to_merge = commit->parents ? commit->parents->next : NULL;
5214 if (!to_merge) {
5215 /* non-merge commit: easy case */
5216 strbuf_reset(&buf);
5217 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5218 oid_to_hex(&commit->object.oid),
5219 oneline.buf);
5220 if (is_empty)
5221 strbuf_addf(&buf, " %c empty",
5222 comment_line_char);
5224 FLEX_ALLOC_STR(entry, string, buf.buf);
5225 oidcpy(&entry->entry.oid, &commit->object.oid);
5226 oidmap_put(&commit2todo, entry);
5228 continue;
5231 /* Create a label */
5232 strbuf_reset(&label);
5233 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5234 (p1 = strchr(p1, '\'')) &&
5235 (p2 = strchr(++p1, '\'')))
5236 strbuf_add(&label, p1, p2 - p1);
5237 else if (skip_prefix(oneline.buf, "Merge pull request ",
5238 &p1) &&
5239 (p1 = strstr(p1, " from ")))
5240 strbuf_addstr(&label, p1 + strlen(" from "));
5241 else
5242 strbuf_addbuf(&label, &oneline);
5244 strbuf_reset(&buf);
5245 strbuf_addf(&buf, "%s -C %s",
5246 cmd_merge, oid_to_hex(&commit->object.oid));
5248 /* label the tips of merged branches */
5249 for (; to_merge; to_merge = to_merge->next) {
5250 oid = &to_merge->item->object.oid;
5251 strbuf_addch(&buf, ' ');
5253 if (!oidset_contains(&interesting, oid)) {
5254 strbuf_addstr(&buf, label_oid(oid, NULL,
5255 &state));
5256 continue;
5259 tips_tail = &commit_list_insert(to_merge->item,
5260 tips_tail)->next;
5262 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5264 strbuf_addf(&buf, " # %s", oneline.buf);
5266 FLEX_ALLOC_STR(entry, string, buf.buf);
5267 oidcpy(&entry->entry.oid, &commit->object.oid);
5268 oidmap_put(&commit2todo, entry);
5270 if (skipped_commit)
5271 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5272 _("use --reapply-cherry-picks to include skipped commits"));
5275 * Second phase:
5276 * - label branch points
5277 * - add HEAD to the branch tips
5279 for (iter = commits; iter; iter = iter->next) {
5280 struct commit_list *parent = iter->item->parents;
5281 for (; parent; parent = parent->next) {
5282 struct object_id *oid = &parent->item->object.oid;
5283 if (!oidset_contains(&interesting, oid))
5284 continue;
5285 if (oidset_insert(&child_seen, oid))
5286 label_oid(oid, "branch-point", &state);
5289 /* Add HEAD as implicit "tip of branch" */
5290 if (!iter->next)
5291 tips_tail = &commit_list_insert(iter->item,
5292 tips_tail)->next;
5296 * Third phase: output the todo list. This is a bit tricky, as we
5297 * want to avoid jumping back and forth between revisions. To
5298 * accomplish that goal, we walk backwards from the branch tips,
5299 * gathering commits not yet shown, reversing the list on the fly,
5300 * then outputting that list (labeling revisions as needed).
5302 strbuf_addf(out, "%s onto\n", cmd_label);
5303 for (iter = tips; iter; iter = iter->next) {
5304 struct commit_list *list = NULL, *iter2;
5306 commit = iter->item;
5307 if (oidset_contains(&shown, &commit->object.oid))
5308 continue;
5309 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5311 if (entry)
5312 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5313 else
5314 strbuf_addch(out, '\n');
5316 while (oidset_contains(&interesting, &commit->object.oid) &&
5317 !oidset_contains(&shown, &commit->object.oid)) {
5318 commit_list_insert(commit, &list);
5319 if (!commit->parents) {
5320 commit = NULL;
5321 break;
5323 commit = commit->parents->item;
5326 if (!commit)
5327 strbuf_addf(out, "%s %s\n", cmd_reset,
5328 rebase_cousins || root_with_onto ?
5329 "onto" : "[new root]");
5330 else {
5331 const char *to = NULL;
5333 entry = oidmap_get(&state.commit2label,
5334 &commit->object.oid);
5335 if (entry)
5336 to = entry->string;
5337 else if (!rebase_cousins)
5338 to = label_oid(&commit->object.oid, NULL,
5339 &state);
5341 if (!to || !strcmp(to, "onto"))
5342 strbuf_addf(out, "%s onto\n", cmd_reset);
5343 else {
5344 strbuf_reset(&oneline);
5345 pretty_print_commit(pp, commit, &oneline);
5346 strbuf_addf(out, "%s %s # %s\n",
5347 cmd_reset, to, oneline.buf);
5351 for (iter2 = list; iter2; iter2 = iter2->next) {
5352 struct object_id *oid = &iter2->item->object.oid;
5353 entry = oidmap_get(&commit2todo, oid);
5354 /* only show if not already upstream */
5355 if (entry)
5356 strbuf_addf(out, "%s\n", entry->string);
5357 entry = oidmap_get(&state.commit2label, oid);
5358 if (entry)
5359 strbuf_addf(out, "%s %s\n",
5360 cmd_label, entry->string);
5361 oidset_insert(&shown, oid);
5364 free_commit_list(list);
5367 free_commit_list(commits);
5368 free_commit_list(tips);
5370 strbuf_release(&label);
5371 strbuf_release(&oneline);
5372 strbuf_release(&buf);
5374 oidmap_free(&commit2todo, 1);
5375 oidmap_free(&state.commit2label, 1);
5376 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5377 strbuf_release(&state.buf);
5379 return 0;
5382 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5383 const char **argv, unsigned flags)
5385 char *format = NULL;
5386 struct pretty_print_context pp = {0};
5387 struct rev_info revs;
5388 struct commit *commit;
5389 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5390 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5391 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5392 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5393 int skipped_commit = 0;
5395 repo_init_revisions(r, &revs, NULL);
5396 revs.verbose_header = 1;
5397 if (!rebase_merges)
5398 revs.max_parents = 1;
5399 revs.cherry_mark = !reapply_cherry_picks;
5400 revs.limited = 1;
5401 revs.reverse = 1;
5402 revs.right_only = 1;
5403 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5404 revs.topo_order = 1;
5406 revs.pretty_given = 1;
5407 git_config_get_string("rebase.instructionFormat", &format);
5408 if (!format || !*format) {
5409 free(format);
5410 format = xstrdup("%s");
5412 get_commit_format(format, &revs);
5413 free(format);
5414 pp.fmt = revs.commit_format;
5415 pp.output_encoding = get_log_output_encoding();
5417 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5418 return error(_("make_script: unhandled options"));
5420 if (prepare_revision_walk(&revs) < 0)
5421 return error(_("make_script: error preparing revisions"));
5423 if (rebase_merges)
5424 return make_script_with_merges(&pp, &revs, out, flags);
5426 while ((commit = get_revision(&revs))) {
5427 int is_empty = is_original_commit_empty(commit);
5429 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5430 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5431 warning(_("skipped previously applied commit %s"),
5432 short_commit_name(commit));
5433 skipped_commit = 1;
5434 continue;
5436 if (is_empty && !keep_empty)
5437 continue;
5438 strbuf_addf(out, "%s %s ", insn,
5439 oid_to_hex(&commit->object.oid));
5440 pretty_print_commit(&pp, commit, out);
5441 if (is_empty)
5442 strbuf_addf(out, " %c empty", comment_line_char);
5443 strbuf_addch(out, '\n');
5445 if (skipped_commit)
5446 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5447 _("use --reapply-cherry-picks to include skipped commits"));
5448 return 0;
5452 * Add commands after pick and (series of) squash/fixup commands
5453 * in the todo list.
5455 void todo_list_add_exec_commands(struct todo_list *todo_list,
5456 struct string_list *commands)
5458 struct strbuf *buf = &todo_list->buf;
5459 size_t base_offset = buf->len;
5460 int i, insert, nr = 0, alloc = 0;
5461 struct todo_item *items = NULL, *base_items = NULL;
5463 CALLOC_ARRAY(base_items, commands->nr);
5464 for (i = 0; i < commands->nr; i++) {
5465 size_t command_len = strlen(commands->items[i].string);
5467 strbuf_addstr(buf, commands->items[i].string);
5468 strbuf_addch(buf, '\n');
5470 base_items[i].command = TODO_EXEC;
5471 base_items[i].offset_in_buf = base_offset;
5472 base_items[i].arg_offset = base_offset + strlen("exec ");
5473 base_items[i].arg_len = command_len - strlen("exec ");
5475 base_offset += command_len + 1;
5479 * Insert <commands> after every pick. Here, fixup/squash chains
5480 * are considered part of the pick, so we insert the commands *after*
5481 * those chains if there are any.
5483 * As we insert the exec commands immediately after rearranging
5484 * any fixups and before the user edits the list, a fixup chain
5485 * can never contain comments (any comments are empty picks that
5486 * have been commented out because the user did not specify
5487 * --keep-empty). So, it is safe to insert an exec command
5488 * without looking at the command following a comment.
5490 insert = 0;
5491 for (i = 0; i < todo_list->nr; i++) {
5492 enum todo_command command = todo_list->items[i].command;
5493 if (insert && !is_fixup(command)) {
5494 ALLOC_GROW(items, nr + commands->nr, alloc);
5495 COPY_ARRAY(items + nr, base_items, commands->nr);
5496 nr += commands->nr;
5498 insert = 0;
5501 ALLOC_GROW(items, nr + 1, alloc);
5502 items[nr++] = todo_list->items[i];
5504 if (command == TODO_PICK || command == TODO_MERGE)
5505 insert = 1;
5508 /* insert or append final <commands> */
5509 if (insert || nr == todo_list->nr) {
5510 ALLOC_GROW(items, nr + commands->nr, alloc);
5511 COPY_ARRAY(items + nr, base_items, commands->nr);
5512 nr += commands->nr;
5515 free(base_items);
5516 FREE_AND_NULL(todo_list->items);
5517 todo_list->items = items;
5518 todo_list->nr = nr;
5519 todo_list->alloc = alloc;
5522 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5523 struct strbuf *buf, int num, unsigned flags)
5525 struct todo_item *item;
5526 int i, max = todo_list->nr;
5528 if (num > 0 && num < max)
5529 max = num;
5531 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5532 char cmd;
5534 /* if the item is not a command write it and continue */
5535 if (item->command >= TODO_COMMENT) {
5536 strbuf_addf(buf, "%.*s\n", item->arg_len,
5537 todo_item_get_arg(todo_list, item));
5538 continue;
5541 /* add command to the buffer */
5542 cmd = command_to_char(item->command);
5543 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5544 strbuf_addch(buf, cmd);
5545 else
5546 strbuf_addstr(buf, command_to_string(item->command));
5548 /* add commit id */
5549 if (item->commit) {
5550 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5551 short_commit_name(item->commit) :
5552 oid_to_hex(&item->commit->object.oid);
5554 if (item->command == TODO_FIXUP) {
5555 if (item->flags & TODO_EDIT_FIXUP_MSG)
5556 strbuf_addstr(buf, " -c");
5557 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5558 strbuf_addstr(buf, " -C");
5562 if (item->command == TODO_MERGE) {
5563 if (item->flags & TODO_EDIT_MERGE_MSG)
5564 strbuf_addstr(buf, " -c");
5565 else
5566 strbuf_addstr(buf, " -C");
5569 strbuf_addf(buf, " %s", oid);
5572 /* add all the rest */
5573 if (!item->arg_len)
5574 strbuf_addch(buf, '\n');
5575 else
5576 strbuf_addf(buf, " %.*s\n", item->arg_len,
5577 todo_item_get_arg(todo_list, item));
5581 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5582 const char *file, const char *shortrevisions,
5583 const char *shortonto, int num, unsigned flags)
5585 int res;
5586 struct strbuf buf = STRBUF_INIT;
5588 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5589 if (flags & TODO_LIST_APPEND_TODO_HELP)
5590 append_todo_help(count_commands(todo_list),
5591 shortrevisions, shortonto, &buf);
5593 res = write_message(buf.buf, buf.len, file, 0);
5594 strbuf_release(&buf);
5596 return res;
5599 /* skip picking commits whose parents are unchanged */
5600 static int skip_unnecessary_picks(struct repository *r,
5601 struct todo_list *todo_list,
5602 struct object_id *base_oid)
5604 struct object_id *parent_oid;
5605 int i;
5607 for (i = 0; i < todo_list->nr; i++) {
5608 struct todo_item *item = todo_list->items + i;
5610 if (item->command >= TODO_NOOP)
5611 continue;
5612 if (item->command != TODO_PICK)
5613 break;
5614 if (parse_commit(item->commit)) {
5615 return error(_("could not parse commit '%s'"),
5616 oid_to_hex(&item->commit->object.oid));
5618 if (!item->commit->parents)
5619 break; /* root commit */
5620 if (item->commit->parents->next)
5621 break; /* merge commit */
5622 parent_oid = &item->commit->parents->item->object.oid;
5623 if (!oideq(parent_oid, base_oid))
5624 break;
5625 oidcpy(base_oid, &item->commit->object.oid);
5627 if (i > 0) {
5628 const char *done_path = rebase_path_done();
5630 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5631 error_errno(_("could not write to '%s'"), done_path);
5632 return -1;
5635 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5636 todo_list->nr -= i;
5637 todo_list->current = 0;
5638 todo_list->done_nr += i;
5640 if (is_fixup(peek_command(todo_list, 0)))
5641 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5644 return 0;
5647 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5648 const char *shortrevisions, const char *onto_name,
5649 struct commit *onto, const struct object_id *orig_head,
5650 struct string_list *commands, unsigned autosquash,
5651 struct todo_list *todo_list)
5653 char shortonto[GIT_MAX_HEXSZ + 1];
5654 const char *todo_file = rebase_path_todo();
5655 struct todo_list new_todo = TODO_LIST_INIT;
5656 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5657 struct object_id oid = onto->object.oid;
5658 int res;
5660 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5662 if (buf->len == 0) {
5663 struct todo_item *item = append_new_todo(todo_list);
5664 item->command = TODO_NOOP;
5665 item->commit = NULL;
5666 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5669 if (autosquash && todo_list_rearrange_squash(todo_list))
5670 return -1;
5672 if (commands->nr)
5673 todo_list_add_exec_commands(todo_list, commands);
5675 if (count_commands(todo_list) == 0) {
5676 apply_autostash(rebase_path_autostash());
5677 sequencer_remove_state(opts);
5679 return error(_("nothing to do"));
5682 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5683 shortonto, flags);
5684 if (res == -1)
5685 return -1;
5686 else if (res == -2) {
5687 apply_autostash(rebase_path_autostash());
5688 sequencer_remove_state(opts);
5690 return -1;
5691 } else if (res == -3) {
5692 apply_autostash(rebase_path_autostash());
5693 sequencer_remove_state(opts);
5694 todo_list_release(&new_todo);
5696 return error(_("nothing to do"));
5697 } else if (res == -4) {
5698 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5699 todo_list_release(&new_todo);
5701 return -1;
5704 /* Expand the commit IDs */
5705 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5706 strbuf_swap(&new_todo.buf, &buf2);
5707 strbuf_release(&buf2);
5708 new_todo.total_nr -= new_todo.nr;
5709 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5710 BUG("invalid todo list after expanding IDs:\n%s",
5711 new_todo.buf.buf);
5713 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5714 todo_list_release(&new_todo);
5715 return error(_("could not skip unnecessary pick commands"));
5718 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5719 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5720 todo_list_release(&new_todo);
5721 return error_errno(_("could not write '%s'"), todo_file);
5724 res = -1;
5726 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5727 goto cleanup;
5729 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5730 goto cleanup;
5732 todo_list_write_total_nr(&new_todo);
5733 res = pick_commits(r, &new_todo, opts);
5735 cleanup:
5736 todo_list_release(&new_todo);
5738 return res;
5741 struct subject2item_entry {
5742 struct hashmap_entry entry;
5743 int i;
5744 char subject[FLEX_ARRAY];
5747 static int subject2item_cmp(const void *fndata,
5748 const struct hashmap_entry *eptr,
5749 const struct hashmap_entry *entry_or_key,
5750 const void *key)
5752 const struct subject2item_entry *a, *b;
5754 a = container_of(eptr, const struct subject2item_entry, entry);
5755 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5757 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5760 define_commit_slab(commit_todo_item, struct todo_item *);
5762 static int skip_fixupish(const char *subject, const char **p) {
5763 return skip_prefix(subject, "fixup! ", p) ||
5764 skip_prefix(subject, "amend! ", p) ||
5765 skip_prefix(subject, "squash! ", p);
5769 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5770 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5771 * after the former, and change "pick" to "fixup"/"squash".
5773 * Note that if the config has specified a custom instruction format, each log
5774 * message will have to be retrieved from the commit (as the oneline in the
5775 * script cannot be trusted) in order to normalize the autosquash arrangement.
5777 int todo_list_rearrange_squash(struct todo_list *todo_list)
5779 struct hashmap subject2item;
5780 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5781 char **subjects;
5782 struct commit_todo_item commit_todo;
5783 struct todo_item *items = NULL;
5785 init_commit_todo_item(&commit_todo);
5787 * The hashmap maps onelines to the respective todo list index.
5789 * If any items need to be rearranged, the next[i] value will indicate
5790 * which item was moved directly after the i'th.
5792 * In that case, last[i] will indicate the index of the latest item to
5793 * be moved to appear after the i'th.
5795 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5796 ALLOC_ARRAY(next, todo_list->nr);
5797 ALLOC_ARRAY(tail, todo_list->nr);
5798 ALLOC_ARRAY(subjects, todo_list->nr);
5799 for (i = 0; i < todo_list->nr; i++) {
5800 struct strbuf buf = STRBUF_INIT;
5801 struct todo_item *item = todo_list->items + i;
5802 const char *commit_buffer, *subject, *p;
5803 size_t subject_len;
5804 int i2 = -1;
5805 struct subject2item_entry *entry;
5807 next[i] = tail[i] = -1;
5808 if (!item->commit || item->command == TODO_DROP) {
5809 subjects[i] = NULL;
5810 continue;
5813 if (is_fixup(item->command)) {
5814 clear_commit_todo_item(&commit_todo);
5815 return error(_("the script was already rearranged."));
5818 *commit_todo_item_at(&commit_todo, item->commit) = item;
5820 parse_commit(item->commit);
5821 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5822 find_commit_subject(commit_buffer, &subject);
5823 format_subject(&buf, subject, " ");
5824 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5825 unuse_commit_buffer(item->commit, commit_buffer);
5826 if (skip_fixupish(subject, &p)) {
5827 struct commit *commit2;
5829 for (;;) {
5830 while (isspace(*p))
5831 p++;
5832 if (!skip_fixupish(p, &p))
5833 break;
5836 entry = hashmap_get_entry_from_hash(&subject2item,
5837 strhash(p), p,
5838 struct subject2item_entry,
5839 entry);
5840 if (entry)
5841 /* found by title */
5842 i2 = entry->i;
5843 else if (!strchr(p, ' ') &&
5844 (commit2 =
5845 lookup_commit_reference_by_name(p)) &&
5846 *commit_todo_item_at(&commit_todo, commit2))
5847 /* found by commit name */
5848 i2 = *commit_todo_item_at(&commit_todo, commit2)
5849 - todo_list->items;
5850 else {
5851 /* copy can be a prefix of the commit subject */
5852 for (i2 = 0; i2 < i; i2++)
5853 if (subjects[i2] &&
5854 starts_with(subjects[i2], p))
5855 break;
5856 if (i2 == i)
5857 i2 = -1;
5860 if (i2 >= 0) {
5861 rearranged = 1;
5862 if (starts_with(subject, "fixup!")) {
5863 todo_list->items[i].command = TODO_FIXUP;
5864 } else if (starts_with(subject, "amend!")) {
5865 todo_list->items[i].command = TODO_FIXUP;
5866 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5867 } else {
5868 todo_list->items[i].command = TODO_SQUASH;
5870 if (tail[i2] < 0) {
5871 next[i] = next[i2];
5872 next[i2] = i;
5873 } else {
5874 next[i] = next[tail[i2]];
5875 next[tail[i2]] = i;
5877 tail[i2] = i;
5878 } else if (!hashmap_get_from_hash(&subject2item,
5879 strhash(subject), subject)) {
5880 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5881 entry->i = i;
5882 hashmap_entry_init(&entry->entry,
5883 strhash(entry->subject));
5884 hashmap_put(&subject2item, &entry->entry);
5888 if (rearranged) {
5889 for (i = 0; i < todo_list->nr; i++) {
5890 enum todo_command command = todo_list->items[i].command;
5891 int cur = i;
5894 * Initially, all commands are 'pick's. If it is a
5895 * fixup or a squash now, we have rearranged it.
5897 if (is_fixup(command))
5898 continue;
5900 while (cur >= 0) {
5901 ALLOC_GROW(items, nr + 1, alloc);
5902 items[nr++] = todo_list->items[cur];
5903 cur = next[cur];
5907 FREE_AND_NULL(todo_list->items);
5908 todo_list->items = items;
5909 todo_list->nr = nr;
5910 todo_list->alloc = alloc;
5913 free(next);
5914 free(tail);
5915 for (i = 0; i < todo_list->nr; i++)
5916 free(subjects[i]);
5917 free(subjects);
5918 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5920 clear_commit_todo_item(&commit_todo);
5922 return 0;
5925 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5927 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5928 struct object_id cherry_pick_head, rebase_head;
5930 if (file_exists(git_path_seq_dir()))
5931 *whence = FROM_CHERRY_PICK_MULTI;
5932 if (file_exists(rebase_path()) &&
5933 !get_oid("REBASE_HEAD", &rebase_head) &&
5934 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5935 oideq(&rebase_head, &cherry_pick_head))
5936 *whence = FROM_REBASE_PICK;
5937 else
5938 *whence = FROM_CHERRY_PICK_SINGLE;
5940 return 1;
5943 return 0;