i18n: ref-filter: factorize "%(foo) atom used without %(bar) atom"
[git/debian.git] / sequencer.c
blobe314af4d60a1dcb13f6ea215c80b219742275c3d
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "hook.h"
12 #include "exec-cmd.h"
13 #include "utf8.h"
14 #include "cache-tree.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "rerere.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
20 #include "refs.h"
21 #include "strvec.h"
22 #include "quote.h"
23 #include "trailer.h"
24 #include "log-tree.h"
25 #include "wt-status.h"
26 #include "hashmap.h"
27 #include "notes-utils.h"
28 #include "sigchain.h"
29 #include "unpack-trees.h"
30 #include "worktree.h"
31 #include "oidmap.h"
32 #include "oidset.h"
33 #include "commit-slab.h"
34 #include "alias.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
37 #include "reset.h"
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
41 static const char sign_off_header[] = "Signed-off-by: ";
42 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
44 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
46 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
48 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
49 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
50 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
51 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
53 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
55 * The file containing rebase commands, comments, and empty lines.
56 * This file is created by "git rebase -i" then edited by the user. As
57 * the lines are processed, they are removed from the front of this
58 * file and written to the tail of 'done'.
60 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
61 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
63 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
66 * The rebase command lines that have already been processed. A line
67 * is moved here when it is first handled, before any associated user
68 * actions.
70 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
72 * The file to keep track of how many commands were already processed (e.g.
73 * for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
77 * The file to keep track of how many commands are to be processed in total
78 * (e.g. for the prompt).
80 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
82 * The commit message that is planned to be used for any changes that
83 * need to be committed following a user interaction.
85 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
87 * The file into which is accumulated the suggested commit message for
88 * squash/fixup commands. When the first of a series of squash/fixups
89 * is seen, the file is created and the commit message from the
90 * previous commit and from the first squash/fixup commit are written
91 * to it. The commit message for each subsequent squash/fixup commit
92 * is appended to the file as it is processed.
94 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
96 * If the current series of squash/fixups has not yet included a squash
97 * command, then this file exists and holds the commit message of the
98 * original "pick" commit. (If the series ends without a "squash"
99 * command, then this can be used as the commit message of the combined
100 * commit without opening the editor.)
102 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
104 * This file contains the list fixup/squash commands that have been
105 * accumulated into message-fixup or message-squash so far.
107 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
109 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
110 * GIT_AUTHOR_DATE that will be used for the commit that is currently
111 * being rebased.
113 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
115 * When an "edit" rebase command is being processed, the SHA1 of the
116 * commit to be edited is recorded in this file. When "git rebase
117 * --continue" is executed, if there are any staged changes then they
118 * will be amended to the HEAD commit, but only provided the HEAD
119 * commit is still the commit to be edited. When any other rebase
120 * command is processed, this file is deleted.
122 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
124 * When we stop at a given patch via the "edit" command, this file contains
125 * the commit object name of the corresponding patch.
127 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
129 * For the post-rewrite hook, we make a list of rewritten commits and
130 * their new sha1s. The rewritten-pending list keeps the sha1s of
131 * commits that have been processed, but not committed yet,
132 * e.g. because they are waiting for a 'squash' command.
134 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
135 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
136 "rebase-merge/rewritten-pending")
139 * The path of the file containing the OID of the "squash onto" commit, i.e.
140 * the dummy commit used for `reset [new root]`.
142 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
145 * The path of the file listing refs that need to be deleted after the rebase
146 * finishes. This is used by the `label` command to record the need for cleanup.
148 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
151 * The following files are written by git-rebase just after parsing the
152 * command-line.
154 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
155 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
156 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
157 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
158 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
159 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
160 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
161 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
162 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
163 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
164 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
165 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
166 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
167 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
170 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
172 static int git_sequencer_config(const char *k, const char *v, void *cb)
174 struct replay_opts *opts = cb;
175 int status;
177 if (!strcmp(k, "commit.cleanup")) {
178 const char *s;
180 status = git_config_string(&s, k, v);
181 if (status)
182 return status;
184 if (!strcmp(s, "verbatim")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "whitespace")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
189 opts->explicit_cleanup = 1;
190 } else if (!strcmp(s, "strip")) {
191 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
192 opts->explicit_cleanup = 1;
193 } else if (!strcmp(s, "scissors")) {
194 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
195 opts->explicit_cleanup = 1;
196 } else {
197 warning(_("invalid commit message cleanup mode '%s'"),
201 free((char *)s);
202 return status;
205 if (!strcmp(k, "commit.gpgsign")) {
206 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
207 return 0;
210 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
211 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212 if (ret == 0) {
214 * pull.twohead is allowed to be multi-valued; we only
215 * care about the first value.
217 char *tmp = strchr(opts->default_strategy, ' ');
218 if (tmp)
219 *tmp = '\0';
221 return ret;
224 status = git_gpg_config(k, v, NULL);
225 if (status)
226 return status;
228 return git_diff_basic_config(k, v, NULL);
231 void sequencer_init_config(struct replay_opts *opts)
233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
234 git_config(git_sequencer_config, opts);
237 static inline int is_rebase_i(const struct replay_opts *opts)
239 return opts->action == REPLAY_INTERACTIVE_REBASE;
242 static const char *get_dir(const struct replay_opts *opts)
244 if (is_rebase_i(opts))
245 return rebase_path();
246 return git_path_seq_dir();
249 static const char *get_todo_path(const struct replay_opts *opts)
251 if (is_rebase_i(opts))
252 return rebase_path_todo();
253 return git_path_todo_file();
257 * Returns 0 for non-conforming footer
258 * Returns 1 for conforming footer
259 * Returns 2 when sob exists within conforming footer
260 * Returns 3 when sob exists within conforming footer as last entry
262 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
263 size_t ignore_footer)
265 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
266 struct trailer_info info;
267 size_t i;
268 int found_sob = 0, found_sob_last = 0;
269 char saved_char;
271 opts.no_divider = 1;
273 if (ignore_footer) {
274 saved_char = sb->buf[sb->len - ignore_footer];
275 sb->buf[sb->len - ignore_footer] = '\0';
278 trailer_info_get(&info, sb->buf, &opts);
280 if (ignore_footer)
281 sb->buf[sb->len - ignore_footer] = saved_char;
283 if (info.trailer_start == info.trailer_end)
284 return 0;
286 for (i = 0; i < info.trailer_nr; i++)
287 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
288 found_sob = 1;
289 if (i == info.trailer_nr - 1)
290 found_sob_last = 1;
293 trailer_info_release(&info);
295 if (found_sob_last)
296 return 3;
297 if (found_sob)
298 return 2;
299 return 1;
302 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
304 static struct strbuf buf = STRBUF_INIT;
306 strbuf_reset(&buf);
307 if (opts->gpg_sign)
308 sq_quotef(&buf, "-S%s", opts->gpg_sign);
309 return buf.buf;
312 int sequencer_remove_state(struct replay_opts *opts)
314 struct strbuf buf = STRBUF_INIT;
315 int i, ret = 0;
317 if (is_rebase_i(opts) &&
318 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319 char *p = buf.buf;
320 while (*p) {
321 char *eol = strchr(p, '\n');
322 if (eol)
323 *eol = '\0';
324 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
325 warning(_("could not delete '%s'"), p);
326 ret = -1;
328 if (!eol)
329 break;
330 p = eol + 1;
334 free(opts->gpg_sign);
335 free(opts->default_strategy);
336 free(opts->strategy);
337 for (i = 0; i < opts->xopts_nr; i++)
338 free(opts->xopts[i]);
339 free(opts->xopts);
340 strbuf_release(&opts->current_fixups);
342 strbuf_reset(&buf);
343 strbuf_addstr(&buf, get_dir(opts));
344 if (remove_dir_recursively(&buf, 0))
345 ret = error(_("could not remove '%s'"), buf.buf);
346 strbuf_release(&buf);
348 return ret;
351 static const char *action_name(const struct replay_opts *opts)
353 switch (opts->action) {
354 case REPLAY_REVERT:
355 return N_("revert");
356 case REPLAY_PICK:
357 return N_("cherry-pick");
358 case REPLAY_INTERACTIVE_REBASE:
359 return N_("rebase");
361 die(_("unknown action: %d"), opts->action);
364 struct commit_message {
365 char *parent_label;
366 char *label;
367 char *subject;
368 const char *message;
371 static const char *short_commit_name(struct commit *commit)
373 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
376 static int get_message(struct commit *commit, struct commit_message *out)
378 const char *abbrev, *subject;
379 int subject_len;
381 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
382 abbrev = short_commit_name(commit);
384 subject_len = find_commit_subject(out->message, &subject);
386 out->subject = xmemdupz(subject, subject_len);
387 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
388 out->parent_label = xstrfmt("parent of %s", out->label);
390 return 0;
393 static void free_message(struct commit *commit, struct commit_message *msg)
395 free(msg->parent_label);
396 free(msg->label);
397 free(msg->subject);
398 unuse_commit_buffer(commit, msg->message);
401 static void print_advice(struct repository *r, int show_hint,
402 struct replay_opts *opts)
404 char *msg = getenv("GIT_CHERRY_PICK_HELP");
406 if (msg) {
407 advise("%s\n", msg);
409 * A conflict has occurred but the porcelain
410 * (typically rebase --interactive) wants to take care
411 * of the commit itself so remove CHERRY_PICK_HEAD
413 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
414 NULL, 0);
415 return;
418 if (show_hint) {
419 if (opts->no_commit)
420 advise(_("after resolving the conflicts, mark the corrected paths\n"
421 "with 'git add <paths>' or 'git rm <paths>'"));
422 else if (opts->action == REPLAY_PICK)
423 advise(_("After resolving the conflicts, mark them with\n"
424 "\"git add/rm <pathspec>\", then run\n"
425 "\"git cherry-pick --continue\".\n"
426 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
427 "To abort and get back to the state before \"git cherry-pick\",\n"
428 "run \"git cherry-pick --abort\"."));
429 else if (opts->action == REPLAY_REVERT)
430 advise(_("After resolving the conflicts, mark them with\n"
431 "\"git add/rm <pathspec>\", then run\n"
432 "\"git revert --continue\".\n"
433 "You can instead skip this commit with \"git revert --skip\".\n"
434 "To abort and get back to the state before \"git revert\",\n"
435 "run \"git revert --abort\"."));
436 else
437 BUG("unexpected pick action in print_advice()");
441 static int write_message(const void *buf, size_t len, const char *filename,
442 int append_eol)
444 struct lock_file msg_file = LOCK_INIT;
446 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
447 if (msg_fd < 0)
448 return error_errno(_("could not lock '%s'"), filename);
449 if (write_in_full(msg_fd, buf, len) < 0) {
450 error_errno(_("could not write to '%s'"), filename);
451 rollback_lock_file(&msg_file);
452 return -1;
454 if (append_eol && write(msg_fd, "\n", 1) < 0) {
455 error_errno(_("could not write eol to '%s'"), filename);
456 rollback_lock_file(&msg_file);
457 return -1;
459 if (commit_lock_file(&msg_file) < 0)
460 return error(_("failed to finalize '%s'"), filename);
462 return 0;
465 int read_oneliner(struct strbuf *buf,
466 const char *path, unsigned flags)
468 int orig_len = buf->len;
470 if (strbuf_read_file(buf, path, 0) < 0) {
471 if ((flags & READ_ONELINER_WARN_MISSING) ||
472 (errno != ENOENT && errno != ENOTDIR))
473 warning_errno(_("could not read '%s'"), path);
474 return 0;
477 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
478 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
479 --buf->len;
480 buf->buf[buf->len] = '\0';
483 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
484 return 0;
486 return 1;
489 static struct tree *empty_tree(struct repository *r)
491 return lookup_tree(r, the_hash_algo->empty_tree);
494 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
496 if (repo_read_index_unmerged(repo))
497 return error_resolve_conflict(_(action_name(opts)));
499 error(_("your local changes would be overwritten by %s."),
500 _(action_name(opts)));
502 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
503 advise(_("commit your changes or stash them to proceed."));
504 return -1;
507 static void update_abort_safety_file(void)
509 struct object_id head;
511 /* Do nothing on a single-pick */
512 if (!file_exists(git_path_seq_dir()))
513 return;
515 if (!get_oid("HEAD", &head))
516 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
517 else
518 write_file(git_path_abort_safety_file(), "%s", "");
521 static int fast_forward_to(struct repository *r,
522 const struct object_id *to,
523 const struct object_id *from,
524 int unborn,
525 struct replay_opts *opts)
527 struct ref_transaction *transaction;
528 struct strbuf sb = STRBUF_INIT;
529 struct strbuf err = STRBUF_INIT;
531 repo_read_index(r);
532 if (checkout_fast_forward(r, from, to, 1))
533 return -1; /* the callee should have complained already */
535 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
537 transaction = ref_transaction_begin(&err);
538 if (!transaction ||
539 ref_transaction_update(transaction, "HEAD",
540 to, unborn && !is_rebase_i(opts) ?
541 null_oid() : from,
542 0, sb.buf, &err) ||
543 ref_transaction_commit(transaction, &err)) {
544 ref_transaction_free(transaction);
545 error("%s", err.buf);
546 strbuf_release(&sb);
547 strbuf_release(&err);
548 return -1;
551 strbuf_release(&sb);
552 strbuf_release(&err);
553 ref_transaction_free(transaction);
554 update_abort_safety_file();
555 return 0;
558 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
559 int use_editor)
561 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
562 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
563 COMMIT_MSG_CLEANUP_SPACE;
564 else if (!strcmp(cleanup_arg, "verbatim"))
565 return COMMIT_MSG_CLEANUP_NONE;
566 else if (!strcmp(cleanup_arg, "whitespace"))
567 return COMMIT_MSG_CLEANUP_SPACE;
568 else if (!strcmp(cleanup_arg, "strip"))
569 return COMMIT_MSG_CLEANUP_ALL;
570 else if (!strcmp(cleanup_arg, "scissors"))
571 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
572 COMMIT_MSG_CLEANUP_SPACE;
573 else
574 die(_("Invalid cleanup mode %s"), cleanup_arg);
578 * NB using int rather than enum cleanup_mode to stop clang's
579 * -Wtautological-constant-out-of-range-compare complaining that the comparison
580 * is always true.
582 static const char *describe_cleanup_mode(int cleanup_mode)
584 static const char *modes[] = { "whitespace",
585 "verbatim",
586 "scissors",
587 "strip" };
589 if (cleanup_mode < ARRAY_SIZE(modes))
590 return modes[cleanup_mode];
592 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
595 void append_conflicts_hint(struct index_state *istate,
596 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
598 int i;
600 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
601 strbuf_addch(msgbuf, '\n');
602 wt_status_append_cut_line(msgbuf);
603 strbuf_addch(msgbuf, comment_line_char);
606 strbuf_addch(msgbuf, '\n');
607 strbuf_commented_addf(msgbuf, "Conflicts:\n");
608 for (i = 0; i < istate->cache_nr;) {
609 const struct cache_entry *ce = istate->cache[i++];
610 if (ce_stage(ce)) {
611 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
612 while (i < istate->cache_nr &&
613 !strcmp(ce->name, istate->cache[i]->name))
614 i++;
619 static int do_recursive_merge(struct repository *r,
620 struct commit *base, struct commit *next,
621 const char *base_label, const char *next_label,
622 struct object_id *head, struct strbuf *msgbuf,
623 struct replay_opts *opts)
625 struct merge_options o;
626 struct merge_result result;
627 struct tree *next_tree, *base_tree, *head_tree;
628 int clean, show_output;
629 int i;
630 struct lock_file index_lock = LOCK_INIT;
632 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
633 return -1;
635 repo_read_index(r);
637 init_merge_options(&o, r);
638 o.ancestor = base ? base_label : "(empty tree)";
639 o.branch1 = "HEAD";
640 o.branch2 = next ? next_label : "(empty tree)";
641 if (is_rebase_i(opts))
642 o.buffer_output = 2;
643 o.show_rename_progress = 1;
645 head_tree = parse_tree_indirect(head);
646 next_tree = next ? get_commit_tree(next) : empty_tree(r);
647 base_tree = base ? get_commit_tree(base) : empty_tree(r);
649 for (i = 0; i < opts->xopts_nr; i++)
650 parse_merge_opt(&o, opts->xopts[i]);
652 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
653 memset(&result, 0, sizeof(result));
654 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
655 &result);
656 show_output = !is_rebase_i(opts) || !result.clean;
658 * TODO: merge_switch_to_result will update index/working tree;
659 * we only really want to do that if !result.clean || this is
660 * the final patch to be picked. But determining this is the
661 * final patch would take some work, and "head_tree" would need
662 * to be replace with the tree the index matched before we
663 * started doing any picks.
665 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
666 clean = result.clean;
667 } else {
668 ensure_full_index(r->index);
669 clean = merge_trees(&o, head_tree, next_tree, base_tree);
670 if (is_rebase_i(opts) && clean <= 0)
671 fputs(o.obuf.buf, stdout);
672 strbuf_release(&o.obuf);
674 if (clean < 0) {
675 rollback_lock_file(&index_lock);
676 return clean;
679 if (write_locked_index(r->index, &index_lock,
680 COMMIT_LOCK | SKIP_IF_UNCHANGED))
682 * TRANSLATORS: %s will be "revert", "cherry-pick" or
683 * "rebase".
685 return error(_("%s: Unable to write new index file"),
686 _(action_name(opts)));
688 if (!clean)
689 append_conflicts_hint(r->index, msgbuf,
690 opts->default_msg_cleanup);
692 return !clean;
695 static struct object_id *get_cache_tree_oid(struct index_state *istate)
697 if (!cache_tree_fully_valid(istate->cache_tree))
698 if (cache_tree_update(istate, 0)) {
699 error(_("unable to update cache tree"));
700 return NULL;
703 return &istate->cache_tree->oid;
706 static int is_index_unchanged(struct repository *r)
708 struct object_id head_oid, *cache_tree_oid;
709 struct commit *head_commit;
710 struct index_state *istate = r->index;
712 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
713 return error(_("could not resolve HEAD commit"));
715 head_commit = lookup_commit(r, &head_oid);
718 * If head_commit is NULL, check_commit, called from
719 * lookup_commit, would have indicated that head_commit is not
720 * a commit object already. parse_commit() will return failure
721 * without further complaints in such a case. Otherwise, if
722 * the commit is invalid, parse_commit() will complain. So
723 * there is nothing for us to say here. Just return failure.
725 if (parse_commit(head_commit))
726 return -1;
728 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
729 return -1;
731 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
734 static int write_author_script(const char *message)
736 struct strbuf buf = STRBUF_INIT;
737 const char *eol;
738 int res;
740 for (;;)
741 if (!*message || starts_with(message, "\n")) {
742 missing_author:
743 /* Missing 'author' line? */
744 unlink(rebase_path_author_script());
745 return 0;
746 } else if (skip_prefix(message, "author ", &message))
747 break;
748 else if ((eol = strchr(message, '\n')))
749 message = eol + 1;
750 else
751 goto missing_author;
753 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
754 while (*message && *message != '\n' && *message != '\r')
755 if (skip_prefix(message, " <", &message))
756 break;
757 else if (*message != '\'')
758 strbuf_addch(&buf, *(message++));
759 else
760 strbuf_addf(&buf, "'\\%c'", *(message++));
761 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
762 while (*message && *message != '\n' && *message != '\r')
763 if (skip_prefix(message, "> ", &message))
764 break;
765 else if (*message != '\'')
766 strbuf_addch(&buf, *(message++));
767 else
768 strbuf_addf(&buf, "'\\%c'", *(message++));
769 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
770 while (*message && *message != '\n' && *message != '\r')
771 if (*message != '\'')
772 strbuf_addch(&buf, *(message++));
773 else
774 strbuf_addf(&buf, "'\\%c'", *(message++));
775 strbuf_addch(&buf, '\'');
776 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
777 strbuf_release(&buf);
778 return res;
782 * Take a series of KEY='VALUE' lines where VALUE part is
783 * sq-quoted, and append <KEY, VALUE> at the end of the string list
785 static int parse_key_value_squoted(char *buf, struct string_list *list)
787 while (*buf) {
788 struct string_list_item *item;
789 char *np;
790 char *cp = strchr(buf, '=');
791 if (!cp) {
792 np = strchrnul(buf, '\n');
793 return error(_("no key present in '%.*s'"),
794 (int) (np - buf), buf);
796 np = strchrnul(cp, '\n');
797 *cp++ = '\0';
798 item = string_list_append(list, buf);
800 buf = np + (*np == '\n');
801 *np = '\0';
802 cp = sq_dequote(cp);
803 if (!cp)
804 return error(_("unable to dequote value of '%s'"),
805 item->string);
806 item->util = xstrdup(cp);
808 return 0;
812 * Reads and parses the state directory's "author-script" file, and sets name,
813 * email and date accordingly.
814 * Returns 0 on success, -1 if the file could not be parsed.
816 * The author script is of the format:
818 * GIT_AUTHOR_NAME='$author_name'
819 * GIT_AUTHOR_EMAIL='$author_email'
820 * GIT_AUTHOR_DATE='$author_date'
822 * where $author_name, $author_email and $author_date are quoted. We are strict
823 * with our parsing, as the file was meant to be eval'd in the now-removed
824 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
825 * from what this function expects, it is better to bail out than to do
826 * something that the user does not expect.
828 int read_author_script(const char *path, char **name, char **email, char **date,
829 int allow_missing)
831 struct strbuf buf = STRBUF_INIT;
832 struct string_list kv = STRING_LIST_INIT_DUP;
833 int retval = -1; /* assume failure */
834 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
836 if (strbuf_read_file(&buf, path, 256) <= 0) {
837 strbuf_release(&buf);
838 if (errno == ENOENT && allow_missing)
839 return 0;
840 else
841 return error_errno(_("could not open '%s' for reading"),
842 path);
845 if (parse_key_value_squoted(buf.buf, &kv))
846 goto finish;
848 for (i = 0; i < kv.nr; i++) {
849 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
850 if (name_i != -2)
851 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
852 else
853 name_i = i;
854 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
855 if (email_i != -2)
856 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
857 else
858 email_i = i;
859 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
860 if (date_i != -2)
861 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
862 else
863 date_i = i;
864 } else {
865 err = error(_("unknown variable '%s'"),
866 kv.items[i].string);
869 if (name_i == -2)
870 error(_("missing 'GIT_AUTHOR_NAME'"));
871 if (email_i == -2)
872 error(_("missing 'GIT_AUTHOR_EMAIL'"));
873 if (date_i == -2)
874 error(_("missing 'GIT_AUTHOR_DATE'"));
875 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
876 goto finish;
877 *name = kv.items[name_i].util;
878 *email = kv.items[email_i].util;
879 *date = kv.items[date_i].util;
880 retval = 0;
881 finish:
882 string_list_clear(&kv, !!retval);
883 strbuf_release(&buf);
884 return retval;
888 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
889 * file with shell quoting into struct strvec. Returns -1 on
890 * error, 0 otherwise.
892 static int read_env_script(struct strvec *env)
894 char *name, *email, *date;
896 if (read_author_script(rebase_path_author_script(),
897 &name, &email, &date, 0))
898 return -1;
900 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
901 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
902 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
903 free(name);
904 free(email);
905 free(date);
907 return 0;
910 static char *get_author(const char *message)
912 size_t len;
913 const char *a;
915 a = find_commit_header(message, "author", &len);
916 if (a)
917 return xmemdupz(a, len);
919 return NULL;
922 static const char *author_date_from_env_array(const struct strvec *env)
924 int i;
925 const char *date;
927 for (i = 0; i < env->nr; i++)
928 if (skip_prefix(env->v[i],
929 "GIT_AUTHOR_DATE=", &date))
930 return date;
932 * If GIT_AUTHOR_DATE is missing we should have already errored out when
933 * reading the script
935 BUG("GIT_AUTHOR_DATE missing from author script");
938 static const char staged_changes_advice[] =
939 N_("you have staged changes in your working tree\n"
940 "If these changes are meant to be squashed into the previous commit, run:\n"
941 "\n"
942 " git commit --amend %s\n"
943 "\n"
944 "If they are meant to go into a new commit, run:\n"
945 "\n"
946 " git commit %s\n"
947 "\n"
948 "In both cases, once you're done, continue with:\n"
949 "\n"
950 " git rebase --continue\n");
952 #define ALLOW_EMPTY (1<<0)
953 #define EDIT_MSG (1<<1)
954 #define AMEND_MSG (1<<2)
955 #define CLEANUP_MSG (1<<3)
956 #define VERIFY_MSG (1<<4)
957 #define CREATE_ROOT_COMMIT (1<<5)
958 #define VERBATIM_MSG (1<<6)
960 static int run_command_silent_on_success(struct child_process *cmd)
962 struct strbuf buf = STRBUF_INIT;
963 int rc;
965 cmd->stdout_to_stderr = 1;
966 rc = pipe_command(cmd,
967 NULL, 0,
968 NULL, 0,
969 &buf, 0);
971 if (rc)
972 fputs(buf.buf, stderr);
973 strbuf_release(&buf);
974 return rc;
978 * If we are cherry-pick, and if the merge did not result in
979 * hand-editing, we will hit this commit and inherit the original
980 * author date and name.
982 * If we are revert, or if our cherry-pick results in a hand merge,
983 * we had better say that the current user is responsible for that.
985 * An exception is when run_git_commit() is called during an
986 * interactive rebase: in that case, we will want to retain the
987 * author metadata.
989 static int run_git_commit(const char *defmsg,
990 struct replay_opts *opts,
991 unsigned int flags)
993 struct child_process cmd = CHILD_PROCESS_INIT;
995 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
996 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
998 cmd.git_cmd = 1;
1000 if (is_rebase_i(opts) &&
1001 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1002 !(!defmsg && (flags & AMEND_MSG))) &&
1003 read_env_script(&cmd.env_array)) {
1004 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1006 return error(_(staged_changes_advice),
1007 gpg_opt, gpg_opt);
1010 if (opts->committer_date_is_author_date)
1011 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1012 opts->ignore_date ?
1013 "" :
1014 author_date_from_env_array(&cmd.env_array));
1015 if (opts->ignore_date)
1016 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1018 strvec_push(&cmd.args, "commit");
1020 if (!(flags & VERIFY_MSG))
1021 strvec_push(&cmd.args, "-n");
1022 if ((flags & AMEND_MSG))
1023 strvec_push(&cmd.args, "--amend");
1024 if (opts->gpg_sign)
1025 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1026 else
1027 strvec_push(&cmd.args, "--no-gpg-sign");
1028 if (defmsg)
1029 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1030 else if (!(flags & EDIT_MSG))
1031 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1032 if ((flags & CLEANUP_MSG))
1033 strvec_push(&cmd.args, "--cleanup=strip");
1034 if ((flags & VERBATIM_MSG))
1035 strvec_push(&cmd.args, "--cleanup=verbatim");
1036 if ((flags & EDIT_MSG))
1037 strvec_push(&cmd.args, "-e");
1038 else if (!(flags & CLEANUP_MSG) &&
1039 !opts->signoff && !opts->record_origin &&
1040 !opts->explicit_cleanup)
1041 strvec_push(&cmd.args, "--cleanup=verbatim");
1043 if ((flags & ALLOW_EMPTY))
1044 strvec_push(&cmd.args, "--allow-empty");
1046 if (!(flags & EDIT_MSG))
1047 strvec_push(&cmd.args, "--allow-empty-message");
1049 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1050 return run_command_silent_on_success(&cmd);
1051 else
1052 return run_command(&cmd);
1055 static int rest_is_empty(const struct strbuf *sb, int start)
1057 int i, eol;
1058 const char *nl;
1060 /* Check if the rest is just whitespace and Signed-off-by's. */
1061 for (i = start; i < sb->len; i++) {
1062 nl = memchr(sb->buf + i, '\n', sb->len - i);
1063 if (nl)
1064 eol = nl - sb->buf;
1065 else
1066 eol = sb->len;
1068 if (strlen(sign_off_header) <= eol - i &&
1069 starts_with(sb->buf + i, sign_off_header)) {
1070 i = eol;
1071 continue;
1073 while (i < eol)
1074 if (!isspace(sb->buf[i++]))
1075 return 0;
1078 return 1;
1081 void cleanup_message(struct strbuf *msgbuf,
1082 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1084 if (verbose || /* Truncate the message just before the diff, if any. */
1085 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1086 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1087 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1088 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1092 * Find out if the message in the strbuf contains only whitespace and
1093 * Signed-off-by lines.
1095 int message_is_empty(const struct strbuf *sb,
1096 enum commit_msg_cleanup_mode cleanup_mode)
1098 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1099 return 0;
1100 return rest_is_empty(sb, 0);
1104 * See if the user edited the message in the editor or left what
1105 * was in the template intact
1107 int template_untouched(const struct strbuf *sb, const char *template_file,
1108 enum commit_msg_cleanup_mode cleanup_mode)
1110 struct strbuf tmpl = STRBUF_INIT;
1111 const char *start;
1113 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1114 return 0;
1116 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1117 return 0;
1119 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1120 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1121 start = sb->buf;
1122 strbuf_release(&tmpl);
1123 return rest_is_empty(sb, start - sb->buf);
1126 int update_head_with_reflog(const struct commit *old_head,
1127 const struct object_id *new_head,
1128 const char *action, const struct strbuf *msg,
1129 struct strbuf *err)
1131 struct ref_transaction *transaction;
1132 struct strbuf sb = STRBUF_INIT;
1133 const char *nl;
1134 int ret = 0;
1136 if (action) {
1137 strbuf_addstr(&sb, action);
1138 strbuf_addstr(&sb, ": ");
1141 nl = strchr(msg->buf, '\n');
1142 if (nl) {
1143 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1144 } else {
1145 strbuf_addbuf(&sb, msg);
1146 strbuf_addch(&sb, '\n');
1149 transaction = ref_transaction_begin(err);
1150 if (!transaction ||
1151 ref_transaction_update(transaction, "HEAD", new_head,
1152 old_head ? &old_head->object.oid : null_oid(),
1153 0, sb.buf, err) ||
1154 ref_transaction_commit(transaction, err)) {
1155 ret = -1;
1157 ref_transaction_free(transaction);
1158 strbuf_release(&sb);
1160 return ret;
1163 static int run_rewrite_hook(const struct object_id *oldoid,
1164 const struct object_id *newoid)
1166 struct child_process proc = CHILD_PROCESS_INIT;
1167 int code;
1168 struct strbuf sb = STRBUF_INIT;
1169 const char *hook_path = find_hook("post-rewrite");
1171 if (!hook_path)
1172 return 0;
1174 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1175 proc.in = -1;
1176 proc.stdout_to_stderr = 1;
1177 proc.trace2_hook_name = "post-rewrite";
1179 code = start_command(&proc);
1180 if (code)
1181 return code;
1182 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1183 sigchain_push(SIGPIPE, SIG_IGN);
1184 write_in_full(proc.in, sb.buf, sb.len);
1185 close(proc.in);
1186 strbuf_release(&sb);
1187 sigchain_pop(SIGPIPE);
1188 return finish_command(&proc);
1191 void commit_post_rewrite(struct repository *r,
1192 const struct commit *old_head,
1193 const struct object_id *new_head)
1195 struct notes_rewrite_cfg *cfg;
1197 cfg = init_copy_notes_for_rewrite("amend");
1198 if (cfg) {
1199 /* we are amending, so old_head is not NULL */
1200 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1201 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1203 run_rewrite_hook(&old_head->object.oid, new_head);
1206 static int run_prepare_commit_msg_hook(struct repository *r,
1207 struct strbuf *msg,
1208 const char *commit)
1210 int ret = 0;
1211 const char *name, *arg1 = NULL, *arg2 = NULL;
1213 name = git_path_commit_editmsg();
1214 if (write_message(msg->buf, msg->len, name, 0))
1215 return -1;
1217 if (commit) {
1218 arg1 = "commit";
1219 arg2 = commit;
1220 } else {
1221 arg1 = "message";
1223 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1224 arg1, arg2, NULL))
1225 ret = error(_("'prepare-commit-msg' hook failed"));
1227 return ret;
1230 static const char implicit_ident_advice_noconfig[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly. Run the\n"
1234 "following command and follow the instructions in your editor to edit\n"
1235 "your configuration file:\n"
1236 "\n"
1237 " git config --global --edit\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 " git commit --amend --reset-author\n");
1243 static const char implicit_ident_advice_config[] =
1244 N_("Your name and email address were configured automatically based\n"
1245 "on your username and hostname. Please check that they are accurate.\n"
1246 "You can suppress this message by setting them explicitly:\n"
1247 "\n"
1248 " git config --global user.name \"Your Name\"\n"
1249 " git config --global user.email you@example.com\n"
1250 "\n"
1251 "After doing this, you may fix the identity used for this commit with:\n"
1252 "\n"
1253 " git commit --amend --reset-author\n");
1255 static const char *implicit_ident_advice(void)
1257 char *user_config = interpolate_path("~/.gitconfig", 0);
1258 char *xdg_config = xdg_config_home("config");
1259 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1261 free(user_config);
1262 free(xdg_config);
1264 if (config_exists)
1265 return _(implicit_ident_advice_config);
1266 else
1267 return _(implicit_ident_advice_noconfig);
1271 void print_commit_summary(struct repository *r,
1272 const char *prefix,
1273 const struct object_id *oid,
1274 unsigned int flags)
1276 struct rev_info rev;
1277 struct commit *commit;
1278 struct strbuf format = STRBUF_INIT;
1279 const char *head;
1280 struct pretty_print_context pctx = {0};
1281 struct strbuf author_ident = STRBUF_INIT;
1282 struct strbuf committer_ident = STRBUF_INIT;
1283 struct ref_store *refs;
1284 int resolve_errno;
1286 commit = lookup_commit(r, oid);
1287 if (!commit)
1288 die(_("couldn't look up newly created commit"));
1289 if (parse_commit(commit))
1290 die(_("could not parse newly created commit"));
1292 strbuf_addstr(&format, "format:%h] %s");
1294 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1295 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1296 if (strbuf_cmp(&author_ident, &committer_ident)) {
1297 strbuf_addstr(&format, "\n Author: ");
1298 strbuf_addbuf_percentquote(&format, &author_ident);
1300 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1301 struct strbuf date = STRBUF_INIT;
1303 format_commit_message(commit, "%ad", &date, &pctx);
1304 strbuf_addstr(&format, "\n Date: ");
1305 strbuf_addbuf_percentquote(&format, &date);
1306 strbuf_release(&date);
1308 if (!committer_ident_sufficiently_given()) {
1309 strbuf_addstr(&format, "\n Committer: ");
1310 strbuf_addbuf_percentquote(&format, &committer_ident);
1311 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1312 strbuf_addch(&format, '\n');
1313 strbuf_addstr(&format, implicit_ident_advice());
1316 strbuf_release(&author_ident);
1317 strbuf_release(&committer_ident);
1319 repo_init_revisions(r, &rev, prefix);
1320 setup_revisions(0, NULL, &rev, NULL);
1322 rev.diff = 1;
1323 rev.diffopt.output_format =
1324 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1326 rev.verbose_header = 1;
1327 rev.show_root_diff = 1;
1328 get_commit_format(format.buf, &rev);
1329 rev.always_show_header = 0;
1330 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1331 rev.diffopt.break_opt = 0;
1332 diff_setup_done(&rev.diffopt);
1334 refs = get_main_ref_store(the_repository);
1335 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL,
1336 &resolve_errno);
1337 if (!head) {
1338 errno = resolve_errno;
1339 die_errno(_("unable to resolve HEAD after creating commit"));
1341 if (!strcmp(head, "HEAD"))
1342 head = _("detached HEAD");
1343 else
1344 skip_prefix(head, "refs/heads/", &head);
1345 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1346 _(" (root-commit)") : "");
1348 if (!log_tree_commit(&rev, commit)) {
1349 rev.always_show_header = 1;
1350 rev.use_terminator = 1;
1351 log_tree_commit(&rev, commit);
1354 strbuf_release(&format);
1357 static int parse_head(struct repository *r, struct commit **head)
1359 struct commit *current_head;
1360 struct object_id oid;
1362 if (get_oid("HEAD", &oid)) {
1363 current_head = NULL;
1364 } else {
1365 current_head = lookup_commit_reference(r, &oid);
1366 if (!current_head)
1367 return error(_("could not parse HEAD"));
1368 if (!oideq(&oid, &current_head->object.oid)) {
1369 warning(_("HEAD %s is not a commit!"),
1370 oid_to_hex(&oid));
1372 if (parse_commit(current_head))
1373 return error(_("could not parse HEAD commit"));
1375 *head = current_head;
1377 return 0;
1381 * Try to commit without forking 'git commit'. In some cases we need
1382 * to run 'git commit' to display an error message
1384 * Returns:
1385 * -1 - error unable to commit
1386 * 0 - success
1387 * 1 - run 'git commit'
1389 static int try_to_commit(struct repository *r,
1390 struct strbuf *msg, const char *author,
1391 struct replay_opts *opts, unsigned int flags,
1392 struct object_id *oid)
1394 struct object_id tree;
1395 struct commit *current_head = NULL;
1396 struct commit_list *parents = NULL;
1397 struct commit_extra_header *extra = NULL;
1398 struct strbuf err = STRBUF_INIT;
1399 struct strbuf commit_msg = STRBUF_INIT;
1400 char *amend_author = NULL;
1401 const char *committer = NULL;
1402 const char *hook_commit = NULL;
1403 enum commit_msg_cleanup_mode cleanup;
1404 int res = 0;
1406 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1407 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1409 if (parse_head(r, &current_head))
1410 return -1;
1412 if (flags & AMEND_MSG) {
1413 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1414 const char *out_enc = get_commit_output_encoding();
1415 const char *message = logmsg_reencode(current_head, NULL,
1416 out_enc);
1418 if (!msg) {
1419 const char *orig_message = NULL;
1421 find_commit_subject(message, &orig_message);
1422 msg = &commit_msg;
1423 strbuf_addstr(msg, orig_message);
1424 hook_commit = "HEAD";
1426 author = amend_author = get_author(message);
1427 unuse_commit_buffer(current_head, message);
1428 if (!author) {
1429 res = error(_("unable to parse commit author"));
1430 goto out;
1432 parents = copy_commit_list(current_head->parents);
1433 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1434 } else if (current_head &&
1435 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1436 commit_list_insert(current_head, &parents);
1439 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1440 res = error(_("git write-tree failed to write a tree"));
1441 goto out;
1444 if (!(flags & ALLOW_EMPTY)) {
1445 struct commit *first_parent = current_head;
1447 if (flags & AMEND_MSG) {
1448 if (current_head->parents) {
1449 first_parent = current_head->parents->item;
1450 if (repo_parse_commit(r, first_parent)) {
1451 res = error(_("could not parse HEAD commit"));
1452 goto out;
1454 } else {
1455 first_parent = NULL;
1458 if (oideq(first_parent
1459 ? get_commit_tree_oid(first_parent)
1460 : the_hash_algo->empty_tree,
1461 &tree)) {
1462 res = 1; /* run 'git commit' to display error message */
1463 goto out;
1467 if (hook_exists("prepare-commit-msg")) {
1468 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1469 if (res)
1470 goto out;
1471 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1472 2048) < 0) {
1473 res = error_errno(_("unable to read commit message "
1474 "from '%s'"),
1475 git_path_commit_editmsg());
1476 goto out;
1478 msg = &commit_msg;
1481 if (flags & CLEANUP_MSG)
1482 cleanup = COMMIT_MSG_CLEANUP_ALL;
1483 else if (flags & VERBATIM_MSG)
1484 cleanup = COMMIT_MSG_CLEANUP_NONE;
1485 else if ((opts->signoff || opts->record_origin) &&
1486 !opts->explicit_cleanup)
1487 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1488 else
1489 cleanup = opts->default_msg_cleanup;
1491 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1492 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1493 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1494 res = 1; /* run 'git commit' to display error message */
1495 goto out;
1498 if (opts->committer_date_is_author_date) {
1499 struct ident_split id;
1500 struct strbuf date = STRBUF_INIT;
1502 if (!opts->ignore_date) {
1503 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1504 res = error(_("invalid author identity '%s'"),
1505 author);
1506 goto out;
1508 if (!id.date_begin) {
1509 res = error(_(
1510 "corrupt author: missing date information"));
1511 goto out;
1513 strbuf_addf(&date, "@%.*s %.*s",
1514 (int)(id.date_end - id.date_begin),
1515 id.date_begin,
1516 (int)(id.tz_end - id.tz_begin),
1517 id.tz_begin);
1518 } else {
1519 reset_ident_date();
1521 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1522 getenv("GIT_COMMITTER_EMAIL"),
1523 WANT_COMMITTER_IDENT,
1524 opts->ignore_date ? NULL : date.buf,
1525 IDENT_STRICT);
1526 strbuf_release(&date);
1527 } else {
1528 reset_ident_date();
1531 if (opts->ignore_date) {
1532 struct ident_split id;
1533 char *name, *email;
1535 if (split_ident_line(&id, author, strlen(author)) < 0) {
1536 error(_("invalid author identity '%s'"), author);
1537 goto out;
1539 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1540 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1541 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1542 IDENT_STRICT);
1543 free(name);
1544 free(email);
1547 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1548 author, committer, opts->gpg_sign, extra)) {
1549 res = error(_("failed to write commit object"));
1550 goto out;
1553 if (update_head_with_reflog(current_head, oid,
1554 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1555 res = error("%s", err.buf);
1556 goto out;
1559 run_commit_hook(0, r->index_file, "post-commit", NULL);
1560 if (flags & AMEND_MSG)
1561 commit_post_rewrite(r, current_head, oid);
1563 out:
1564 free_commit_extra_headers(extra);
1565 strbuf_release(&err);
1566 strbuf_release(&commit_msg);
1567 free(amend_author);
1569 return res;
1572 static int write_rebase_head(struct object_id *oid)
1574 if (update_ref("rebase", "REBASE_HEAD", oid,
1575 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1576 return error(_("could not update %s"), "REBASE_HEAD");
1578 return 0;
1581 static int do_commit(struct repository *r,
1582 const char *msg_file, const char *author,
1583 struct replay_opts *opts, unsigned int flags,
1584 struct object_id *oid)
1586 int res = 1;
1588 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1589 struct object_id oid;
1590 struct strbuf sb = STRBUF_INIT;
1592 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1593 return error_errno(_("unable to read commit message "
1594 "from '%s'"),
1595 msg_file);
1597 res = try_to_commit(r, msg_file ? &sb : NULL,
1598 author, opts, flags, &oid);
1599 strbuf_release(&sb);
1600 if (!res) {
1601 refs_delete_ref(get_main_ref_store(r), "",
1602 "CHERRY_PICK_HEAD", NULL, 0);
1603 unlink(git_path_merge_msg(r));
1604 if (!is_rebase_i(opts))
1605 print_commit_summary(r, NULL, &oid,
1606 SUMMARY_SHOW_AUTHOR_DATE);
1607 return res;
1610 if (res == 1) {
1611 if (is_rebase_i(opts) && oid)
1612 if (write_rebase_head(oid))
1613 return -1;
1614 return run_git_commit(msg_file, opts, flags);
1617 return res;
1620 static int is_original_commit_empty(struct commit *commit)
1622 const struct object_id *ptree_oid;
1624 if (parse_commit(commit))
1625 return error(_("could not parse commit %s"),
1626 oid_to_hex(&commit->object.oid));
1627 if (commit->parents) {
1628 struct commit *parent = commit->parents->item;
1629 if (parse_commit(parent))
1630 return error(_("could not parse parent commit %s"),
1631 oid_to_hex(&parent->object.oid));
1632 ptree_oid = get_commit_tree_oid(parent);
1633 } else {
1634 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1637 return oideq(ptree_oid, get_commit_tree_oid(commit));
1641 * Should empty commits be allowed? Return status:
1642 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1643 * 0: Halt on empty commit
1644 * 1: Allow empty commit
1645 * 2: Drop empty commit
1647 static int allow_empty(struct repository *r,
1648 struct replay_opts *opts,
1649 struct commit *commit)
1651 int index_unchanged, originally_empty;
1654 * Four cases:
1656 * (1) we do not allow empty at all and error out.
1658 * (2) we allow ones that were initially empty, and
1659 * just drop the ones that become empty
1661 * (3) we allow ones that were initially empty, but
1662 * halt for the ones that become empty;
1664 * (4) we allow both.
1666 if (!opts->allow_empty)
1667 return 0; /* let "git commit" barf as necessary */
1669 index_unchanged = is_index_unchanged(r);
1670 if (index_unchanged < 0)
1671 return index_unchanged;
1672 if (!index_unchanged)
1673 return 0; /* we do not have to say --allow-empty */
1675 if (opts->keep_redundant_commits)
1676 return 1;
1678 originally_empty = is_original_commit_empty(commit);
1679 if (originally_empty < 0)
1680 return originally_empty;
1681 if (originally_empty)
1682 return 1;
1683 else if (opts->drop_redundant_commits)
1684 return 2;
1685 else
1686 return 0;
1689 static struct {
1690 char c;
1691 const char *str;
1692 } todo_command_info[] = {
1693 { 'p', "pick" },
1694 { 0, "revert" },
1695 { 'e', "edit" },
1696 { 'r', "reword" },
1697 { 'f', "fixup" },
1698 { 's', "squash" },
1699 { 'x', "exec" },
1700 { 'b', "break" },
1701 { 'l', "label" },
1702 { 't', "reset" },
1703 { 'm', "merge" },
1704 { 0, "noop" },
1705 { 'd', "drop" },
1706 { 0, NULL }
1709 static const char *command_to_string(const enum todo_command command)
1711 if (command < TODO_COMMENT)
1712 return todo_command_info[command].str;
1713 die(_("unknown command: %d"), command);
1716 static char command_to_char(const enum todo_command command)
1718 if (command < TODO_COMMENT)
1719 return todo_command_info[command].c;
1720 return comment_line_char;
1723 static int is_noop(const enum todo_command command)
1725 return TODO_NOOP <= command;
1728 static int is_fixup(enum todo_command command)
1730 return command == TODO_FIXUP || command == TODO_SQUASH;
1733 /* Does this command create a (non-merge) commit? */
1734 static int is_pick_or_similar(enum todo_command command)
1736 switch (command) {
1737 case TODO_PICK:
1738 case TODO_REVERT:
1739 case TODO_EDIT:
1740 case TODO_REWORD:
1741 case TODO_FIXUP:
1742 case TODO_SQUASH:
1743 return 1;
1744 default:
1745 return 0;
1749 enum todo_item_flags {
1750 TODO_EDIT_MERGE_MSG = (1 << 0),
1751 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1752 TODO_EDIT_FIXUP_MSG = (1 << 2),
1755 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1756 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1757 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1758 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1759 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1761 static int is_fixup_flag(enum todo_command command, unsigned flag)
1763 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1764 (flag & TODO_EDIT_FIXUP_MSG));
1768 * Wrapper around strbuf_add_commented_lines() which avoids double
1769 * commenting commit subjects.
1771 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1773 const char *s = str;
1774 while (len > 0 && s[0] == comment_line_char) {
1775 size_t count;
1776 const char *n = memchr(s, '\n', len);
1777 if (!n)
1778 count = len;
1779 else
1780 count = n - s + 1;
1781 strbuf_add(buf, s, count);
1782 s += count;
1783 len -= count;
1785 strbuf_add_commented_lines(buf, s, len);
1788 /* Does the current fixup chain contain a squash command? */
1789 static int seen_squash(struct replay_opts *opts)
1791 return starts_with(opts->current_fixups.buf, "squash") ||
1792 strstr(opts->current_fixups.buf, "\nsquash");
1795 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1797 strbuf_setlen(buf1, 2);
1798 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1799 strbuf_addch(buf1, '\n');
1800 strbuf_setlen(buf2, 2);
1801 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1802 strbuf_addch(buf2, '\n');
1806 * Comment out any un-commented commit messages, updating the message comments
1807 * to say they will be skipped but do not comment out the empty lines that
1808 * surround commit messages and their comments.
1810 static void update_squash_message_for_fixup(struct strbuf *msg)
1812 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1813 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1814 const char *s, *start;
1815 char *orig_msg;
1816 size_t orig_msg_len;
1817 int i = 1;
1819 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1820 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1821 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1822 while (s) {
1823 const char *next;
1824 size_t off;
1825 if (skip_prefix(s, buf1.buf, &next)) {
1827 * Copy the last message, preserving the blank line
1828 * preceding the current line
1830 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1831 copy_lines(msg, start, s - start - off);
1832 if (off)
1833 strbuf_addch(msg, '\n');
1835 * The next message needs to be commented out but the
1836 * message header is already commented out so just copy
1837 * it and the blank line that follows it.
1839 strbuf_addbuf(msg, &buf2);
1840 if (*next == '\n')
1841 strbuf_addch(msg, *next++);
1842 start = s = next;
1843 copy_lines = add_commented_lines;
1844 update_comment_bufs(&buf1, &buf2, ++i);
1845 } else if (skip_prefix(s, buf2.buf, &next)) {
1846 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1847 copy_lines(msg, start, s - start - off);
1848 start = s - off;
1849 s = next;
1850 copy_lines = strbuf_add;
1851 update_comment_bufs(&buf1, &buf2, ++i);
1852 } else {
1853 s = strchr(s, '\n');
1854 if (s)
1855 s++;
1858 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1859 free(orig_msg);
1860 strbuf_release(&buf1);
1861 strbuf_release(&buf2);
1864 static int append_squash_message(struct strbuf *buf, const char *body,
1865 enum todo_command command, struct replay_opts *opts,
1866 unsigned flag)
1868 const char *fixup_msg;
1869 size_t commented_len = 0, fixup_off;
1871 * amend is non-interactive and not normally used with fixup!
1872 * or squash! commits, so only comment out those subjects when
1873 * squashing commit messages.
1875 if (starts_with(body, "amend!") ||
1876 ((command == TODO_SQUASH || seen_squash(opts)) &&
1877 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1878 commented_len = commit_subject_length(body);
1880 strbuf_addf(buf, "\n%c ", comment_line_char);
1881 strbuf_addf(buf, _(nth_commit_msg_fmt),
1882 ++opts->current_fixup_count + 1);
1883 strbuf_addstr(buf, "\n\n");
1884 strbuf_add_commented_lines(buf, body, commented_len);
1885 /* buf->buf may be reallocated so store an offset into the buffer */
1886 fixup_off = buf->len;
1887 strbuf_addstr(buf, body + commented_len);
1889 /* fixup -C after squash behaves like squash */
1890 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1892 * We're replacing the commit message so we need to
1893 * append the Signed-off-by: trailer if the user
1894 * requested '--signoff'.
1896 if (opts->signoff)
1897 append_signoff(buf, 0, 0);
1899 if ((command == TODO_FIXUP) &&
1900 (flag & TODO_REPLACE_FIXUP_MSG) &&
1901 (file_exists(rebase_path_fixup_msg()) ||
1902 !file_exists(rebase_path_squash_msg()))) {
1903 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1904 if (write_message(fixup_msg, strlen(fixup_msg),
1905 rebase_path_fixup_msg(), 0) < 0)
1906 return error(_("cannot write '%s'"),
1907 rebase_path_fixup_msg());
1908 } else {
1909 unlink(rebase_path_fixup_msg());
1911 } else {
1912 unlink(rebase_path_fixup_msg());
1915 return 0;
1918 static int update_squash_messages(struct repository *r,
1919 enum todo_command command,
1920 struct commit *commit,
1921 struct replay_opts *opts,
1922 unsigned flag)
1924 struct strbuf buf = STRBUF_INIT;
1925 int res = 0;
1926 const char *message, *body;
1927 const char *encoding = get_commit_output_encoding();
1929 if (opts->current_fixup_count > 0) {
1930 struct strbuf header = STRBUF_INIT;
1931 char *eol;
1933 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1934 return error(_("could not read '%s'"),
1935 rebase_path_squash_msg());
1937 eol = buf.buf[0] != comment_line_char ?
1938 buf.buf : strchrnul(buf.buf, '\n');
1940 strbuf_addf(&header, "%c ", comment_line_char);
1941 strbuf_addf(&header, _(combined_commit_msg_fmt),
1942 opts->current_fixup_count + 2);
1943 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1944 strbuf_release(&header);
1945 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1946 update_squash_message_for_fixup(&buf);
1947 } else {
1948 struct object_id head;
1949 struct commit *head_commit;
1950 const char *head_message, *body;
1952 if (get_oid("HEAD", &head))
1953 return error(_("need a HEAD to fixup"));
1954 if (!(head_commit = lookup_commit_reference(r, &head)))
1955 return error(_("could not read HEAD"));
1956 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1957 return error(_("could not read HEAD's commit message"));
1959 find_commit_subject(head_message, &body);
1960 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1961 rebase_path_fixup_msg(), 0) < 0) {
1962 unuse_commit_buffer(head_commit, head_message);
1963 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1965 strbuf_addf(&buf, "%c ", comment_line_char);
1966 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1967 strbuf_addf(&buf, "\n%c ", comment_line_char);
1968 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1969 _(skip_first_commit_msg_str) :
1970 _(first_commit_msg_str));
1971 strbuf_addstr(&buf, "\n\n");
1972 if (is_fixup_flag(command, flag))
1973 strbuf_add_commented_lines(&buf, body, strlen(body));
1974 else
1975 strbuf_addstr(&buf, body);
1977 unuse_commit_buffer(head_commit, head_message);
1980 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1981 return error(_("could not read commit message of %s"),
1982 oid_to_hex(&commit->object.oid));
1983 find_commit_subject(message, &body);
1985 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1986 res = append_squash_message(&buf, body, command, opts, flag);
1987 } else if (command == TODO_FIXUP) {
1988 strbuf_addf(&buf, "\n%c ", comment_line_char);
1989 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1990 ++opts->current_fixup_count + 1);
1991 strbuf_addstr(&buf, "\n\n");
1992 strbuf_add_commented_lines(&buf, body, strlen(body));
1993 } else
1994 return error(_("unknown command: %d"), command);
1995 unuse_commit_buffer(commit, message);
1997 if (!res)
1998 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2000 strbuf_release(&buf);
2002 if (!res) {
2003 strbuf_addf(&opts->current_fixups, "%s%s %s",
2004 opts->current_fixups.len ? "\n" : "",
2005 command_to_string(command),
2006 oid_to_hex(&commit->object.oid));
2007 res = write_message(opts->current_fixups.buf,
2008 opts->current_fixups.len,
2009 rebase_path_current_fixups(), 0);
2012 return res;
2015 static void flush_rewritten_pending(void)
2017 struct strbuf buf = STRBUF_INIT;
2018 struct object_id newoid;
2019 FILE *out;
2021 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2022 !get_oid("HEAD", &newoid) &&
2023 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2024 char *bol = buf.buf, *eol;
2026 while (*bol) {
2027 eol = strchrnul(bol, '\n');
2028 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2029 bol, oid_to_hex(&newoid));
2030 if (!*eol)
2031 break;
2032 bol = eol + 1;
2034 fclose(out);
2035 unlink(rebase_path_rewritten_pending());
2037 strbuf_release(&buf);
2040 static void record_in_rewritten(struct object_id *oid,
2041 enum todo_command next_command)
2043 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2045 if (!out)
2046 return;
2048 fprintf(out, "%s\n", oid_to_hex(oid));
2049 fclose(out);
2051 if (!is_fixup(next_command))
2052 flush_rewritten_pending();
2055 static int should_edit(struct replay_opts *opts) {
2056 if (opts->edit < 0)
2058 * Note that we only handle the case of non-conflicted
2059 * commits; continue_single_pick() handles the conflicted
2060 * commits itself instead of calling this function.
2062 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2063 return opts->edit;
2066 static int do_pick_commit(struct repository *r,
2067 struct todo_item *item,
2068 struct replay_opts *opts,
2069 int final_fixup, int *check_todo)
2071 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2072 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2073 struct object_id head;
2074 struct commit *base, *next, *parent;
2075 const char *base_label, *next_label;
2076 char *author = NULL;
2077 struct commit_message msg = { NULL, NULL, NULL, NULL };
2078 struct strbuf msgbuf = STRBUF_INIT;
2079 int res, unborn = 0, reword = 0, allow, drop_commit;
2080 enum todo_command command = item->command;
2081 struct commit *commit = item->commit;
2083 if (opts->no_commit) {
2085 * We do not intend to commit immediately. We just want to
2086 * merge the differences in, so let's compute the tree
2087 * that represents the "current" state for the merge machinery
2088 * to work on.
2090 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2091 return error(_("your index file is unmerged."));
2092 } else {
2093 unborn = get_oid("HEAD", &head);
2094 /* Do we want to generate a root commit? */
2095 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2096 oideq(&head, &opts->squash_onto)) {
2097 if (is_fixup(command))
2098 return error(_("cannot fixup root commit"));
2099 flags |= CREATE_ROOT_COMMIT;
2100 unborn = 1;
2101 } else if (unborn)
2102 oidcpy(&head, the_hash_algo->empty_tree);
2103 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2104 NULL, 0))
2105 return error_dirty_index(r, opts);
2107 discard_index(r->index);
2109 if (!commit->parents)
2110 parent = NULL;
2111 else if (commit->parents->next) {
2112 /* Reverting or cherry-picking a merge commit */
2113 int cnt;
2114 struct commit_list *p;
2116 if (!opts->mainline)
2117 return error(_("commit %s is a merge but no -m option was given."),
2118 oid_to_hex(&commit->object.oid));
2120 for (cnt = 1, p = commit->parents;
2121 cnt != opts->mainline && p;
2122 cnt++)
2123 p = p->next;
2124 if (cnt != opts->mainline || !p)
2125 return error(_("commit %s does not have parent %d"),
2126 oid_to_hex(&commit->object.oid), opts->mainline);
2127 parent = p->item;
2128 } else if (1 < opts->mainline)
2130 * Non-first parent explicitly specified as mainline for
2131 * non-merge commit
2133 return error(_("commit %s does not have parent %d"),
2134 oid_to_hex(&commit->object.oid), opts->mainline);
2135 else
2136 parent = commit->parents->item;
2138 if (get_message(commit, &msg) != 0)
2139 return error(_("cannot get commit message for %s"),
2140 oid_to_hex(&commit->object.oid));
2142 if (opts->allow_ff && !is_fixup(command) &&
2143 ((parent && oideq(&parent->object.oid, &head)) ||
2144 (!parent && unborn))) {
2145 if (is_rebase_i(opts))
2146 write_author_script(msg.message);
2147 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2148 opts);
2149 if (res || command != TODO_REWORD)
2150 goto leave;
2151 reword = 1;
2152 msg_file = NULL;
2153 goto fast_forward_edit;
2155 if (parent && parse_commit(parent) < 0)
2156 /* TRANSLATORS: The first %s will be a "todo" command like
2157 "revert" or "pick", the second %s a SHA1. */
2158 return error(_("%s: cannot parse parent commit %s"),
2159 command_to_string(command),
2160 oid_to_hex(&parent->object.oid));
2163 * "commit" is an existing commit. We would want to apply
2164 * the difference it introduces since its first parent "prev"
2165 * on top of the current HEAD if we are cherry-pick. Or the
2166 * reverse of it if we are revert.
2169 if (command == TODO_REVERT) {
2170 base = commit;
2171 base_label = msg.label;
2172 next = parent;
2173 next_label = msg.parent_label;
2174 strbuf_addstr(&msgbuf, "Revert \"");
2175 strbuf_addstr(&msgbuf, msg.subject);
2176 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2177 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2179 if (commit->parents && commit->parents->next) {
2180 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2181 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2183 strbuf_addstr(&msgbuf, ".\n");
2184 } else {
2185 const char *p;
2187 base = parent;
2188 base_label = msg.parent_label;
2189 next = commit;
2190 next_label = msg.label;
2192 /* Append the commit log message to msgbuf. */
2193 if (find_commit_subject(msg.message, &p))
2194 strbuf_addstr(&msgbuf, p);
2196 if (opts->record_origin) {
2197 strbuf_complete_line(&msgbuf);
2198 if (!has_conforming_footer(&msgbuf, NULL, 0))
2199 strbuf_addch(&msgbuf, '\n');
2200 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2201 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2202 strbuf_addstr(&msgbuf, ")\n");
2204 if (!is_fixup(command))
2205 author = get_author(msg.message);
2208 if (command == TODO_REWORD)
2209 reword = 1;
2210 else if (is_fixup(command)) {
2211 if (update_squash_messages(r, command, commit,
2212 opts, item->flags))
2213 return -1;
2214 flags |= AMEND_MSG;
2215 if (!final_fixup)
2216 msg_file = rebase_path_squash_msg();
2217 else if (file_exists(rebase_path_fixup_msg())) {
2218 flags |= VERBATIM_MSG;
2219 msg_file = rebase_path_fixup_msg();
2220 } else {
2221 const char *dest = git_path_squash_msg(r);
2222 unlink(dest);
2223 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2224 return error(_("could not rename '%s' to '%s'"),
2225 rebase_path_squash_msg(), dest);
2226 unlink(git_path_merge_msg(r));
2227 msg_file = dest;
2228 flags |= EDIT_MSG;
2232 if (opts->signoff && !is_fixup(command))
2233 append_signoff(&msgbuf, 0, 0);
2235 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2236 res = -1;
2237 else if (!opts->strategy ||
2238 !strcmp(opts->strategy, "recursive") ||
2239 !strcmp(opts->strategy, "ort") ||
2240 command == TODO_REVERT) {
2241 res = do_recursive_merge(r, base, next, base_label, next_label,
2242 &head, &msgbuf, opts);
2243 if (res < 0)
2244 goto leave;
2246 res |= write_message(msgbuf.buf, msgbuf.len,
2247 git_path_merge_msg(r), 0);
2248 } else {
2249 struct commit_list *common = NULL;
2250 struct commit_list *remotes = NULL;
2252 res = write_message(msgbuf.buf, msgbuf.len,
2253 git_path_merge_msg(r), 0);
2255 commit_list_insert(base, &common);
2256 commit_list_insert(next, &remotes);
2257 res |= try_merge_command(r, opts->strategy,
2258 opts->xopts_nr, (const char **)opts->xopts,
2259 common, oid_to_hex(&head), remotes);
2260 free_commit_list(common);
2261 free_commit_list(remotes);
2263 strbuf_release(&msgbuf);
2266 * If the merge was clean or if it failed due to conflict, we write
2267 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2268 * However, if the merge did not even start, then we don't want to
2269 * write it at all.
2271 if ((command == TODO_PICK || command == TODO_REWORD ||
2272 command == TODO_EDIT) && !opts->no_commit &&
2273 (res == 0 || res == 1) &&
2274 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2275 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2276 res = -1;
2277 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2278 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2279 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2280 res = -1;
2282 if (res) {
2283 error(command == TODO_REVERT
2284 ? _("could not revert %s... %s")
2285 : _("could not apply %s... %s"),
2286 short_commit_name(commit), msg.subject);
2287 print_advice(r, res == 1, opts);
2288 repo_rerere(r, opts->allow_rerere_auto);
2289 goto leave;
2292 drop_commit = 0;
2293 allow = allow_empty(r, opts, commit);
2294 if (allow < 0) {
2295 res = allow;
2296 goto leave;
2297 } else if (allow == 1) {
2298 flags |= ALLOW_EMPTY;
2299 } else if (allow == 2) {
2300 drop_commit = 1;
2301 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2302 NULL, 0);
2303 unlink(git_path_merge_msg(r));
2304 unlink(git_path_auto_merge(r));
2305 fprintf(stderr,
2306 _("dropping %s %s -- patch contents already upstream\n"),
2307 oid_to_hex(&commit->object.oid), msg.subject);
2308 } /* else allow == 0 and there's nothing special to do */
2309 if (!opts->no_commit && !drop_commit) {
2310 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2311 res = do_commit(r, msg_file, author, opts, flags,
2312 commit? &commit->object.oid : NULL);
2313 else
2314 res = error(_("unable to parse commit author"));
2315 *check_todo = !!(flags & EDIT_MSG);
2316 if (!res && reword) {
2317 fast_forward_edit:
2318 res = run_git_commit(NULL, opts, EDIT_MSG |
2319 VERIFY_MSG | AMEND_MSG |
2320 (flags & ALLOW_EMPTY));
2321 *check_todo = 1;
2326 if (!res && final_fixup) {
2327 unlink(rebase_path_fixup_msg());
2328 unlink(rebase_path_squash_msg());
2329 unlink(rebase_path_current_fixups());
2330 strbuf_reset(&opts->current_fixups);
2331 opts->current_fixup_count = 0;
2334 leave:
2335 free_message(commit, &msg);
2336 free(author);
2337 update_abort_safety_file();
2339 return res;
2342 static int prepare_revs(struct replay_opts *opts)
2345 * picking (but not reverting) ranges (but not individual revisions)
2346 * should be done in reverse
2348 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2349 opts->revs->reverse ^= 1;
2351 if (prepare_revision_walk(opts->revs))
2352 return error(_("revision walk setup failed"));
2354 return 0;
2357 static int read_and_refresh_cache(struct repository *r,
2358 struct replay_opts *opts)
2360 struct lock_file index_lock = LOCK_INIT;
2361 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2362 if (repo_read_index(r) < 0) {
2363 rollback_lock_file(&index_lock);
2364 return error(_("git %s: failed to read the index"),
2365 _(action_name(opts)));
2367 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2369 if (index_fd >= 0) {
2370 if (write_locked_index(r->index, &index_lock,
2371 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2372 return error(_("git %s: failed to refresh the index"),
2373 _(action_name(opts)));
2378 * If we are resolving merges in any way other than "ort", then
2379 * expand the sparse index.
2381 if (opts->strategy && strcmp(opts->strategy, "ort"))
2382 ensure_full_index(r->index);
2383 return 0;
2386 void todo_list_release(struct todo_list *todo_list)
2388 strbuf_release(&todo_list->buf);
2389 FREE_AND_NULL(todo_list->items);
2390 todo_list->nr = todo_list->alloc = 0;
2393 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2395 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2396 todo_list->total_nr++;
2397 return todo_list->items + todo_list->nr++;
2400 const char *todo_item_get_arg(struct todo_list *todo_list,
2401 struct todo_item *item)
2403 return todo_list->buf.buf + item->arg_offset;
2406 static int is_command(enum todo_command command, const char **bol)
2408 const char *str = todo_command_info[command].str;
2409 const char nick = todo_command_info[command].c;
2410 const char *p = *bol + 1;
2412 return skip_prefix(*bol, str, bol) ||
2413 ((nick && **bol == nick) &&
2414 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2415 (*bol = p));
2418 static int parse_insn_line(struct repository *r, struct todo_item *item,
2419 const char *buf, const char *bol, char *eol)
2421 struct object_id commit_oid;
2422 char *end_of_object_name;
2423 int i, saved, status, padding;
2425 item->flags = 0;
2427 /* left-trim */
2428 bol += strspn(bol, " \t");
2430 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2431 item->command = TODO_COMMENT;
2432 item->commit = NULL;
2433 item->arg_offset = bol - buf;
2434 item->arg_len = eol - bol;
2435 return 0;
2438 for (i = 0; i < TODO_COMMENT; i++)
2439 if (is_command(i, &bol)) {
2440 item->command = i;
2441 break;
2443 if (i >= TODO_COMMENT)
2444 return -1;
2446 /* Eat up extra spaces/ tabs before object name */
2447 padding = strspn(bol, " \t");
2448 bol += padding;
2450 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2451 if (bol != eol)
2452 return error(_("%s does not accept arguments: '%s'"),
2453 command_to_string(item->command), bol);
2454 item->commit = NULL;
2455 item->arg_offset = bol - buf;
2456 item->arg_len = eol - bol;
2457 return 0;
2460 if (!padding)
2461 return error(_("missing arguments for %s"),
2462 command_to_string(item->command));
2464 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2465 item->command == TODO_RESET) {
2466 item->commit = NULL;
2467 item->arg_offset = bol - buf;
2468 item->arg_len = (int)(eol - bol);
2469 return 0;
2472 if (item->command == TODO_FIXUP) {
2473 if (skip_prefix(bol, "-C", &bol) &&
2474 (*bol == ' ' || *bol == '\t')) {
2475 bol += strspn(bol, " \t");
2476 item->flags |= TODO_REPLACE_FIXUP_MSG;
2477 } else if (skip_prefix(bol, "-c", &bol) &&
2478 (*bol == ' ' || *bol == '\t')) {
2479 bol += strspn(bol, " \t");
2480 item->flags |= TODO_EDIT_FIXUP_MSG;
2484 if (item->command == TODO_MERGE) {
2485 if (skip_prefix(bol, "-C", &bol))
2486 bol += strspn(bol, " \t");
2487 else if (skip_prefix(bol, "-c", &bol)) {
2488 bol += strspn(bol, " \t");
2489 item->flags |= TODO_EDIT_MERGE_MSG;
2490 } else {
2491 item->flags |= TODO_EDIT_MERGE_MSG;
2492 item->commit = NULL;
2493 item->arg_offset = bol - buf;
2494 item->arg_len = (int)(eol - bol);
2495 return 0;
2499 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2500 saved = *end_of_object_name;
2501 *end_of_object_name = '\0';
2502 status = get_oid(bol, &commit_oid);
2503 if (status < 0)
2504 error(_("could not parse '%s'"), bol); /* return later */
2505 *end_of_object_name = saved;
2507 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2508 item->arg_offset = bol - buf;
2509 item->arg_len = (int)(eol - bol);
2511 if (status < 0)
2512 return status;
2514 item->commit = lookup_commit_reference(r, &commit_oid);
2515 return item->commit ? 0 : -1;
2518 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2520 const char *todo_file, *bol;
2521 struct strbuf buf = STRBUF_INIT;
2522 int ret = 0;
2524 todo_file = git_path_todo_file();
2525 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2526 if (errno == ENOENT || errno == ENOTDIR)
2527 return -1;
2528 else
2529 return error_errno("unable to open '%s'", todo_file);
2531 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2532 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2533 *action = REPLAY_PICK;
2534 else if (is_command(TODO_REVERT, &bol) &&
2535 (*bol == ' ' || *bol == '\t'))
2536 *action = REPLAY_REVERT;
2537 else
2538 ret = -1;
2540 strbuf_release(&buf);
2542 return ret;
2545 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2546 struct todo_list *todo_list)
2548 struct todo_item *item;
2549 char *p = buf, *next_p;
2550 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2552 todo_list->current = todo_list->nr = 0;
2554 for (i = 1; *p; i++, p = next_p) {
2555 char *eol = strchrnul(p, '\n');
2557 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2559 if (p != eol && eol[-1] == '\r')
2560 eol--; /* strip Carriage Return */
2562 item = append_new_todo(todo_list);
2563 item->offset_in_buf = p - todo_list->buf.buf;
2564 if (parse_insn_line(r, item, buf, p, eol)) {
2565 res = error(_("invalid line %d: %.*s"),
2566 i, (int)(eol - p), p);
2567 item->command = TODO_COMMENT + 1;
2568 item->arg_offset = p - buf;
2569 item->arg_len = (int)(eol - p);
2570 item->commit = NULL;
2573 if (fixup_okay)
2574 ; /* do nothing */
2575 else if (is_fixup(item->command))
2576 return error(_("cannot '%s' without a previous commit"),
2577 command_to_string(item->command));
2578 else if (!is_noop(item->command))
2579 fixup_okay = 1;
2582 return res;
2585 static int count_commands(struct todo_list *todo_list)
2587 int count = 0, i;
2589 for (i = 0; i < todo_list->nr; i++)
2590 if (todo_list->items[i].command != TODO_COMMENT)
2591 count++;
2593 return count;
2596 static int get_item_line_offset(struct todo_list *todo_list, int index)
2598 return index < todo_list->nr ?
2599 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2602 static const char *get_item_line(struct todo_list *todo_list, int index)
2604 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2607 static int get_item_line_length(struct todo_list *todo_list, int index)
2609 return get_item_line_offset(todo_list, index + 1)
2610 - get_item_line_offset(todo_list, index);
2613 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2615 int fd;
2616 ssize_t len;
2618 fd = open(path, O_RDONLY);
2619 if (fd < 0)
2620 return error_errno(_("could not open '%s'"), path);
2621 len = strbuf_read(sb, fd, 0);
2622 close(fd);
2623 if (len < 0)
2624 return error(_("could not read '%s'."), path);
2625 return len;
2628 static int have_finished_the_last_pick(void)
2630 struct strbuf buf = STRBUF_INIT;
2631 const char *eol;
2632 const char *todo_path = git_path_todo_file();
2633 int ret = 0;
2635 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2636 if (errno == ENOENT) {
2637 return 0;
2638 } else {
2639 error_errno("unable to open '%s'", todo_path);
2640 return 0;
2643 /* If there is only one line then we are done */
2644 eol = strchr(buf.buf, '\n');
2645 if (!eol || !eol[1])
2646 ret = 1;
2648 strbuf_release(&buf);
2650 return ret;
2653 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2655 struct replay_opts opts = REPLAY_OPTS_INIT;
2656 int need_cleanup = 0;
2658 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2659 if (!refs_delete_ref(get_main_ref_store(r), "",
2660 "CHERRY_PICK_HEAD", NULL, 0) &&
2661 verbose)
2662 warning(_("cancelling a cherry picking in progress"));
2663 opts.action = REPLAY_PICK;
2664 need_cleanup = 1;
2667 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2668 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2669 NULL, 0) &&
2670 verbose)
2671 warning(_("cancelling a revert in progress"));
2672 opts.action = REPLAY_REVERT;
2673 need_cleanup = 1;
2676 unlink(git_path_auto_merge(r));
2678 if (!need_cleanup)
2679 return;
2681 if (!have_finished_the_last_pick())
2682 return;
2684 sequencer_remove_state(&opts);
2687 static void todo_list_write_total_nr(struct todo_list *todo_list)
2689 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2691 if (f) {
2692 fprintf(f, "%d\n", todo_list->total_nr);
2693 fclose(f);
2697 static int read_populate_todo(struct repository *r,
2698 struct todo_list *todo_list,
2699 struct replay_opts *opts)
2701 const char *todo_file = get_todo_path(opts);
2702 int res;
2704 strbuf_reset(&todo_list->buf);
2705 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2706 return -1;
2708 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2709 if (res) {
2710 if (is_rebase_i(opts))
2711 return error(_("please fix this using "
2712 "'git rebase --edit-todo'."));
2713 return error(_("unusable instruction sheet: '%s'"), todo_file);
2716 if (!todo_list->nr &&
2717 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2718 return error(_("no commits parsed."));
2720 if (!is_rebase_i(opts)) {
2721 enum todo_command valid =
2722 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2723 int i;
2725 for (i = 0; i < todo_list->nr; i++)
2726 if (valid == todo_list->items[i].command)
2727 continue;
2728 else if (valid == TODO_PICK)
2729 return error(_("cannot cherry-pick during a revert."));
2730 else
2731 return error(_("cannot revert during a cherry-pick."));
2734 if (is_rebase_i(opts)) {
2735 struct todo_list done = TODO_LIST_INIT;
2737 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2738 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2739 todo_list->done_nr = count_commands(&done);
2740 else
2741 todo_list->done_nr = 0;
2743 todo_list->total_nr = todo_list->done_nr
2744 + count_commands(todo_list);
2745 todo_list_release(&done);
2747 todo_list_write_total_nr(todo_list);
2750 return 0;
2753 static int git_config_string_dup(char **dest,
2754 const char *var, const char *value)
2756 if (!value)
2757 return config_error_nonbool(var);
2758 free(*dest);
2759 *dest = xstrdup(value);
2760 return 0;
2763 static int populate_opts_cb(const char *key, const char *value, void *data)
2765 struct replay_opts *opts = data;
2766 int error_flag = 1;
2768 if (!value)
2769 error_flag = 0;
2770 else if (!strcmp(key, "options.no-commit"))
2771 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2772 else if (!strcmp(key, "options.edit"))
2773 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2774 else if (!strcmp(key, "options.allow-empty"))
2775 opts->allow_empty =
2776 git_config_bool_or_int(key, value, &error_flag);
2777 else if (!strcmp(key, "options.allow-empty-message"))
2778 opts->allow_empty_message =
2779 git_config_bool_or_int(key, value, &error_flag);
2780 else if (!strcmp(key, "options.keep-redundant-commits"))
2781 opts->keep_redundant_commits =
2782 git_config_bool_or_int(key, value, &error_flag);
2783 else if (!strcmp(key, "options.signoff"))
2784 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2785 else if (!strcmp(key, "options.record-origin"))
2786 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2787 else if (!strcmp(key, "options.allow-ff"))
2788 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2789 else if (!strcmp(key, "options.mainline"))
2790 opts->mainline = git_config_int(key, value);
2791 else if (!strcmp(key, "options.strategy"))
2792 git_config_string_dup(&opts->strategy, key, value);
2793 else if (!strcmp(key, "options.gpg-sign"))
2794 git_config_string_dup(&opts->gpg_sign, key, value);
2795 else if (!strcmp(key, "options.strategy-option")) {
2796 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2797 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2798 } else if (!strcmp(key, "options.allow-rerere-auto"))
2799 opts->allow_rerere_auto =
2800 git_config_bool_or_int(key, value, &error_flag) ?
2801 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2802 else if (!strcmp(key, "options.default-msg-cleanup")) {
2803 opts->explicit_cleanup = 1;
2804 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2805 } else
2806 return error(_("invalid key: %s"), key);
2808 if (!error_flag)
2809 return error(_("invalid value for %s: %s"), key, value);
2811 return 0;
2814 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2816 int i;
2817 char *strategy_opts_string = raw_opts;
2819 if (*strategy_opts_string == ' ')
2820 strategy_opts_string++;
2822 opts->xopts_nr = split_cmdline(strategy_opts_string,
2823 (const char ***)&opts->xopts);
2824 for (i = 0; i < opts->xopts_nr; i++) {
2825 const char *arg = opts->xopts[i];
2827 skip_prefix(arg, "--", &arg);
2828 opts->xopts[i] = xstrdup(arg);
2832 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2834 strbuf_reset(buf);
2835 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2836 return;
2837 opts->strategy = strbuf_detach(buf, NULL);
2838 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2839 return;
2841 parse_strategy_opts(opts, buf->buf);
2844 static int read_populate_opts(struct replay_opts *opts)
2846 if (is_rebase_i(opts)) {
2847 struct strbuf buf = STRBUF_INIT;
2848 int ret = 0;
2850 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2851 READ_ONELINER_SKIP_IF_EMPTY)) {
2852 if (!starts_with(buf.buf, "-S"))
2853 strbuf_reset(&buf);
2854 else {
2855 free(opts->gpg_sign);
2856 opts->gpg_sign = xstrdup(buf.buf + 2);
2858 strbuf_reset(&buf);
2861 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2862 READ_ONELINER_SKIP_IF_EMPTY)) {
2863 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2864 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2865 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2866 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2867 strbuf_reset(&buf);
2870 if (file_exists(rebase_path_verbose()))
2871 opts->verbose = 1;
2873 if (file_exists(rebase_path_quiet()))
2874 opts->quiet = 1;
2876 if (file_exists(rebase_path_signoff())) {
2877 opts->allow_ff = 0;
2878 opts->signoff = 1;
2881 if (file_exists(rebase_path_cdate_is_adate())) {
2882 opts->allow_ff = 0;
2883 opts->committer_date_is_author_date = 1;
2886 if (file_exists(rebase_path_ignore_date())) {
2887 opts->allow_ff = 0;
2888 opts->ignore_date = 1;
2891 if (file_exists(rebase_path_reschedule_failed_exec()))
2892 opts->reschedule_failed_exec = 1;
2893 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2894 opts->reschedule_failed_exec = 0;
2896 if (file_exists(rebase_path_drop_redundant_commits()))
2897 opts->drop_redundant_commits = 1;
2899 if (file_exists(rebase_path_keep_redundant_commits()))
2900 opts->keep_redundant_commits = 1;
2902 read_strategy_opts(opts, &buf);
2903 strbuf_reset(&buf);
2905 if (read_oneliner(&opts->current_fixups,
2906 rebase_path_current_fixups(),
2907 READ_ONELINER_SKIP_IF_EMPTY)) {
2908 const char *p = opts->current_fixups.buf;
2909 opts->current_fixup_count = 1;
2910 while ((p = strchr(p, '\n'))) {
2911 opts->current_fixup_count++;
2912 p++;
2916 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2917 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2918 ret = error(_("unusable squash-onto"));
2919 goto done_rebase_i;
2921 opts->have_squash_onto = 1;
2924 done_rebase_i:
2925 strbuf_release(&buf);
2926 return ret;
2929 if (!file_exists(git_path_opts_file()))
2930 return 0;
2932 * The function git_parse_source(), called from git_config_from_file(),
2933 * may die() in case of a syntactically incorrect file. We do not care
2934 * about this case, though, because we wrote that file ourselves, so we
2935 * are pretty certain that it is syntactically correct.
2937 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2938 return error(_("malformed options sheet: '%s'"),
2939 git_path_opts_file());
2940 return 0;
2943 static void write_strategy_opts(struct replay_opts *opts)
2945 int i;
2946 struct strbuf buf = STRBUF_INIT;
2948 for (i = 0; i < opts->xopts_nr; ++i)
2949 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2951 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2952 strbuf_release(&buf);
2955 int write_basic_state(struct replay_opts *opts, const char *head_name,
2956 struct commit *onto, const struct object_id *orig_head)
2958 if (head_name)
2959 write_file(rebase_path_head_name(), "%s\n", head_name);
2960 if (onto)
2961 write_file(rebase_path_onto(), "%s\n",
2962 oid_to_hex(&onto->object.oid));
2963 if (orig_head)
2964 write_file(rebase_path_orig_head(), "%s\n",
2965 oid_to_hex(orig_head));
2967 if (opts->quiet)
2968 write_file(rebase_path_quiet(), "%s", "");
2969 if (opts->verbose)
2970 write_file(rebase_path_verbose(), "%s", "");
2971 if (opts->strategy)
2972 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2973 if (opts->xopts_nr > 0)
2974 write_strategy_opts(opts);
2976 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2977 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2978 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2979 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2981 if (opts->gpg_sign)
2982 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2983 if (opts->signoff)
2984 write_file(rebase_path_signoff(), "--signoff\n");
2985 if (opts->drop_redundant_commits)
2986 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2987 if (opts->keep_redundant_commits)
2988 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2989 if (opts->committer_date_is_author_date)
2990 write_file(rebase_path_cdate_is_adate(), "%s", "");
2991 if (opts->ignore_date)
2992 write_file(rebase_path_ignore_date(), "%s", "");
2993 if (opts->reschedule_failed_exec)
2994 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2995 else
2996 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2998 return 0;
3001 static int walk_revs_populate_todo(struct todo_list *todo_list,
3002 struct replay_opts *opts)
3004 enum todo_command command = opts->action == REPLAY_PICK ?
3005 TODO_PICK : TODO_REVERT;
3006 const char *command_string = todo_command_info[command].str;
3007 const char *encoding;
3008 struct commit *commit;
3010 if (prepare_revs(opts))
3011 return -1;
3013 encoding = get_log_output_encoding();
3015 while ((commit = get_revision(opts->revs))) {
3016 struct todo_item *item = append_new_todo(todo_list);
3017 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3018 const char *subject;
3019 int subject_len;
3021 item->command = command;
3022 item->commit = commit;
3023 item->arg_offset = 0;
3024 item->arg_len = 0;
3025 item->offset_in_buf = todo_list->buf.len;
3026 subject_len = find_commit_subject(commit_buffer, &subject);
3027 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3028 short_commit_name(commit), subject_len, subject);
3029 unuse_commit_buffer(commit, commit_buffer);
3032 if (!todo_list->nr)
3033 return error(_("empty commit set passed"));
3035 return 0;
3038 static int create_seq_dir(struct repository *r)
3040 enum replay_action action;
3041 const char *in_progress_error = NULL;
3042 const char *in_progress_advice = NULL;
3043 unsigned int advise_skip =
3044 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3045 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3047 if (!sequencer_get_last_command(r, &action)) {
3048 switch (action) {
3049 case REPLAY_REVERT:
3050 in_progress_error = _("revert is already in progress");
3051 in_progress_advice =
3052 _("try \"git revert (--continue | %s--abort | --quit)\"");
3053 break;
3054 case REPLAY_PICK:
3055 in_progress_error = _("cherry-pick is already in progress");
3056 in_progress_advice =
3057 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3058 break;
3059 default:
3060 BUG("unexpected action in create_seq_dir");
3063 if (in_progress_error) {
3064 error("%s", in_progress_error);
3065 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3066 advise(in_progress_advice,
3067 advise_skip ? "--skip | " : "");
3068 return -1;
3070 if (mkdir(git_path_seq_dir(), 0777) < 0)
3071 return error_errno(_("could not create sequencer directory '%s'"),
3072 git_path_seq_dir());
3074 return 0;
3077 static int save_head(const char *head)
3079 struct lock_file head_lock = LOCK_INIT;
3080 struct strbuf buf = STRBUF_INIT;
3081 int fd;
3082 ssize_t written;
3084 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3085 if (fd < 0)
3086 return error_errno(_("could not lock HEAD"));
3087 strbuf_addf(&buf, "%s\n", head);
3088 written = write_in_full(fd, buf.buf, buf.len);
3089 strbuf_release(&buf);
3090 if (written < 0) {
3091 error_errno(_("could not write to '%s'"), git_path_head_file());
3092 rollback_lock_file(&head_lock);
3093 return -1;
3095 if (commit_lock_file(&head_lock) < 0)
3096 return error(_("failed to finalize '%s'"), git_path_head_file());
3097 return 0;
3100 static int rollback_is_safe(void)
3102 struct strbuf sb = STRBUF_INIT;
3103 struct object_id expected_head, actual_head;
3105 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3106 strbuf_trim(&sb);
3107 if (get_oid_hex(sb.buf, &expected_head)) {
3108 strbuf_release(&sb);
3109 die(_("could not parse %s"), git_path_abort_safety_file());
3111 strbuf_release(&sb);
3113 else if (errno == ENOENT)
3114 oidclr(&expected_head);
3115 else
3116 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3118 if (get_oid("HEAD", &actual_head))
3119 oidclr(&actual_head);
3121 return oideq(&actual_head, &expected_head);
3124 static int reset_merge(const struct object_id *oid)
3126 int ret;
3127 struct strvec argv = STRVEC_INIT;
3129 strvec_pushl(&argv, "reset", "--merge", NULL);
3131 if (!is_null_oid(oid))
3132 strvec_push(&argv, oid_to_hex(oid));
3134 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3135 strvec_clear(&argv);
3137 return ret;
3140 static int rollback_single_pick(struct repository *r)
3142 struct object_id head_oid;
3144 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3145 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3146 return error(_("no cherry-pick or revert in progress"));
3147 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3148 return error(_("cannot resolve HEAD"));
3149 if (is_null_oid(&head_oid))
3150 return error(_("cannot abort from a branch yet to be born"));
3151 return reset_merge(&head_oid);
3154 static int skip_single_pick(void)
3156 struct object_id head;
3158 if (read_ref_full("HEAD", 0, &head, NULL))
3159 return error(_("cannot resolve HEAD"));
3160 return reset_merge(&head);
3163 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3165 FILE *f;
3166 struct object_id oid;
3167 struct strbuf buf = STRBUF_INIT;
3168 const char *p;
3170 f = fopen(git_path_head_file(), "r");
3171 if (!f && errno == ENOENT) {
3173 * There is no multiple-cherry-pick in progress.
3174 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3175 * a single-cherry-pick in progress, abort that.
3177 return rollback_single_pick(r);
3179 if (!f)
3180 return error_errno(_("cannot open '%s'"), git_path_head_file());
3181 if (strbuf_getline_lf(&buf, f)) {
3182 error(_("cannot read '%s': %s"), git_path_head_file(),
3183 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3184 fclose(f);
3185 goto fail;
3187 fclose(f);
3188 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3189 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3190 git_path_head_file());
3191 goto fail;
3193 if (is_null_oid(&oid)) {
3194 error(_("cannot abort from a branch yet to be born"));
3195 goto fail;
3198 if (!rollback_is_safe()) {
3199 /* Do not error, just do not rollback */
3200 warning(_("You seem to have moved HEAD. "
3201 "Not rewinding, check your HEAD!"));
3202 } else
3203 if (reset_merge(&oid))
3204 goto fail;
3205 strbuf_release(&buf);
3206 return sequencer_remove_state(opts);
3207 fail:
3208 strbuf_release(&buf);
3209 return -1;
3212 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3214 enum replay_action action = -1;
3215 sequencer_get_last_command(r, &action);
3218 * Check whether the subcommand requested to skip the commit is actually
3219 * in progress and that it's safe to skip the commit.
3221 * opts->action tells us which subcommand requested to skip the commit.
3222 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3223 * action is in progress and we can skip the commit.
3225 * Otherwise we check that the last instruction was related to the
3226 * particular subcommand we're trying to execute and barf if that's not
3227 * the case.
3229 * Finally we check that the rollback is "safe", i.e., has the HEAD
3230 * moved? In this case, it doesn't make sense to "reset the merge" and
3231 * "skip the commit" as the user already handled this by committing. But
3232 * we'd not want to barf here, instead give advice on how to proceed. We
3233 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3234 * it gets removed when the user commits, so if it still exists we're
3235 * sure the user can't have committed before.
3237 switch (opts->action) {
3238 case REPLAY_REVERT:
3239 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3240 if (action != REPLAY_REVERT)
3241 return error(_("no revert in progress"));
3242 if (!rollback_is_safe())
3243 goto give_advice;
3245 break;
3246 case REPLAY_PICK:
3247 if (!refs_ref_exists(get_main_ref_store(r),
3248 "CHERRY_PICK_HEAD")) {
3249 if (action != REPLAY_PICK)
3250 return error(_("no cherry-pick in progress"));
3251 if (!rollback_is_safe())
3252 goto give_advice;
3254 break;
3255 default:
3256 BUG("unexpected action in sequencer_skip");
3259 if (skip_single_pick())
3260 return error(_("failed to skip the commit"));
3261 if (!is_directory(git_path_seq_dir()))
3262 return 0;
3264 return sequencer_continue(r, opts);
3266 give_advice:
3267 error(_("there is nothing to skip"));
3269 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3270 advise(_("have you committed already?\n"
3271 "try \"git %s --continue\""),
3272 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3274 return -1;
3277 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3279 struct lock_file todo_lock = LOCK_INIT;
3280 const char *todo_path = get_todo_path(opts);
3281 int next = todo_list->current, offset, fd;
3284 * rebase -i writes "git-rebase-todo" without the currently executing
3285 * command, appending it to "done" instead.
3287 if (is_rebase_i(opts))
3288 next++;
3290 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3291 if (fd < 0)
3292 return error_errno(_("could not lock '%s'"), todo_path);
3293 offset = get_item_line_offset(todo_list, next);
3294 if (write_in_full(fd, todo_list->buf.buf + offset,
3295 todo_list->buf.len - offset) < 0)
3296 return error_errno(_("could not write to '%s'"), todo_path);
3297 if (commit_lock_file(&todo_lock) < 0)
3298 return error(_("failed to finalize '%s'"), todo_path);
3300 if (is_rebase_i(opts) && next > 0) {
3301 const char *done = rebase_path_done();
3302 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3303 int ret = 0;
3305 if (fd < 0)
3306 return 0;
3307 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3308 get_item_line_length(todo_list, next - 1))
3309 < 0)
3310 ret = error_errno(_("could not write to '%s'"), done);
3311 if (close(fd) < 0)
3312 ret = error_errno(_("failed to finalize '%s'"), done);
3313 return ret;
3315 return 0;
3318 static int save_opts(struct replay_opts *opts)
3320 const char *opts_file = git_path_opts_file();
3321 int res = 0;
3323 if (opts->no_commit)
3324 res |= git_config_set_in_file_gently(opts_file,
3325 "options.no-commit", "true");
3326 if (opts->edit >= 0)
3327 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3328 opts->edit ? "true" : "false");
3329 if (opts->allow_empty)
3330 res |= git_config_set_in_file_gently(opts_file,
3331 "options.allow-empty", "true");
3332 if (opts->allow_empty_message)
3333 res |= git_config_set_in_file_gently(opts_file,
3334 "options.allow-empty-message", "true");
3335 if (opts->keep_redundant_commits)
3336 res |= git_config_set_in_file_gently(opts_file,
3337 "options.keep-redundant-commits", "true");
3338 if (opts->signoff)
3339 res |= git_config_set_in_file_gently(opts_file,
3340 "options.signoff", "true");
3341 if (opts->record_origin)
3342 res |= git_config_set_in_file_gently(opts_file,
3343 "options.record-origin", "true");
3344 if (opts->allow_ff)
3345 res |= git_config_set_in_file_gently(opts_file,
3346 "options.allow-ff", "true");
3347 if (opts->mainline) {
3348 struct strbuf buf = STRBUF_INIT;
3349 strbuf_addf(&buf, "%d", opts->mainline);
3350 res |= git_config_set_in_file_gently(opts_file,
3351 "options.mainline", buf.buf);
3352 strbuf_release(&buf);
3354 if (opts->strategy)
3355 res |= git_config_set_in_file_gently(opts_file,
3356 "options.strategy", opts->strategy);
3357 if (opts->gpg_sign)
3358 res |= git_config_set_in_file_gently(opts_file,
3359 "options.gpg-sign", opts->gpg_sign);
3360 if (opts->xopts) {
3361 int i;
3362 for (i = 0; i < opts->xopts_nr; i++)
3363 res |= git_config_set_multivar_in_file_gently(opts_file,
3364 "options.strategy-option",
3365 opts->xopts[i], "^$", 0);
3367 if (opts->allow_rerere_auto)
3368 res |= git_config_set_in_file_gently(opts_file,
3369 "options.allow-rerere-auto",
3370 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3371 "true" : "false");
3373 if (opts->explicit_cleanup)
3374 res |= git_config_set_in_file_gently(opts_file,
3375 "options.default-msg-cleanup",
3376 describe_cleanup_mode(opts->default_msg_cleanup));
3377 return res;
3380 static int make_patch(struct repository *r,
3381 struct commit *commit,
3382 struct replay_opts *opts)
3384 struct strbuf buf = STRBUF_INIT;
3385 struct rev_info log_tree_opt;
3386 const char *subject;
3387 char hex[GIT_MAX_HEXSZ + 1];
3388 int res = 0;
3390 oid_to_hex_r(hex, &commit->object.oid);
3391 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3392 return -1;
3393 res |= write_rebase_head(&commit->object.oid);
3395 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3396 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3397 repo_init_revisions(r, &log_tree_opt, NULL);
3398 log_tree_opt.abbrev = 0;
3399 log_tree_opt.diff = 1;
3400 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3401 log_tree_opt.disable_stdin = 1;
3402 log_tree_opt.no_commit_id = 1;
3403 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3404 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3405 if (!log_tree_opt.diffopt.file)
3406 res |= error_errno(_("could not open '%s'"), buf.buf);
3407 else {
3408 res |= log_tree_commit(&log_tree_opt, commit);
3409 fclose(log_tree_opt.diffopt.file);
3411 strbuf_reset(&buf);
3413 strbuf_addf(&buf, "%s/message", get_dir(opts));
3414 if (!file_exists(buf.buf)) {
3415 const char *encoding = get_commit_output_encoding();
3416 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3417 find_commit_subject(commit_buffer, &subject);
3418 res |= write_message(subject, strlen(subject), buf.buf, 1);
3419 unuse_commit_buffer(commit, commit_buffer);
3421 strbuf_release(&buf);
3423 return res;
3426 static int intend_to_amend(void)
3428 struct object_id head;
3429 char *p;
3431 if (get_oid("HEAD", &head))
3432 return error(_("cannot read HEAD"));
3434 p = oid_to_hex(&head);
3435 return write_message(p, strlen(p), rebase_path_amend(), 1);
3438 static int error_with_patch(struct repository *r,
3439 struct commit *commit,
3440 const char *subject, int subject_len,
3441 struct replay_opts *opts,
3442 int exit_code, int to_amend)
3444 if (commit) {
3445 if (make_patch(r, commit, opts))
3446 return -1;
3447 } else if (copy_file(rebase_path_message(),
3448 git_path_merge_msg(r), 0666))
3449 return error(_("unable to copy '%s' to '%s'"),
3450 git_path_merge_msg(r), rebase_path_message());
3452 if (to_amend) {
3453 if (intend_to_amend())
3454 return -1;
3456 fprintf(stderr,
3457 _("You can amend the commit now, with\n"
3458 "\n"
3459 " git commit --amend %s\n"
3460 "\n"
3461 "Once you are satisfied with your changes, run\n"
3462 "\n"
3463 " git rebase --continue\n"),
3464 gpg_sign_opt_quoted(opts));
3465 } else if (exit_code) {
3466 if (commit)
3467 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3468 short_commit_name(commit), subject_len, subject);
3469 else
3471 * We don't have the hash of the parent so
3472 * just print the line from the todo file.
3474 fprintf_ln(stderr, _("Could not merge %.*s"),
3475 subject_len, subject);
3478 return exit_code;
3481 static int error_failed_squash(struct repository *r,
3482 struct commit *commit,
3483 struct replay_opts *opts,
3484 int subject_len,
3485 const char *subject)
3487 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3488 return error(_("could not copy '%s' to '%s'"),
3489 rebase_path_squash_msg(), rebase_path_message());
3490 unlink(git_path_merge_msg(r));
3491 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3492 return error(_("could not copy '%s' to '%s'"),
3493 rebase_path_message(),
3494 git_path_merge_msg(r));
3495 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3498 static int do_exec(struct repository *r, const char *command_line)
3500 const char *child_argv[] = { NULL, NULL };
3501 int dirty, status;
3503 fprintf(stderr, _("Executing: %s\n"), command_line);
3504 child_argv[0] = command_line;
3505 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
3507 /* force re-reading of the cache */
3508 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3509 return error(_("could not read index"));
3511 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3513 if (status) {
3514 warning(_("execution failed: %s\n%s"
3515 "You can fix the problem, and then run\n"
3516 "\n"
3517 " git rebase --continue\n"
3518 "\n"),
3519 command_line,
3520 dirty ? N_("and made changes to the index and/or the "
3521 "working tree\n") : "");
3522 if (status == 127)
3523 /* command not found */
3524 status = 1;
3525 } else if (dirty) {
3526 warning(_("execution succeeded: %s\nbut "
3527 "left changes to the index and/or the working tree\n"
3528 "Commit or stash your changes, and then run\n"
3529 "\n"
3530 " git rebase --continue\n"
3531 "\n"), command_line);
3532 status = 1;
3535 return status;
3538 __attribute__((format (printf, 2, 3)))
3539 static int safe_append(const char *filename, const char *fmt, ...)
3541 va_list ap;
3542 struct lock_file lock = LOCK_INIT;
3543 int fd = hold_lock_file_for_update(&lock, filename,
3544 LOCK_REPORT_ON_ERROR);
3545 struct strbuf buf = STRBUF_INIT;
3547 if (fd < 0)
3548 return -1;
3550 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3551 error_errno(_("could not read '%s'"), filename);
3552 rollback_lock_file(&lock);
3553 return -1;
3555 strbuf_complete(&buf, '\n');
3556 va_start(ap, fmt);
3557 strbuf_vaddf(&buf, fmt, ap);
3558 va_end(ap);
3560 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3561 error_errno(_("could not write to '%s'"), filename);
3562 strbuf_release(&buf);
3563 rollback_lock_file(&lock);
3564 return -1;
3566 if (commit_lock_file(&lock) < 0) {
3567 strbuf_release(&buf);
3568 rollback_lock_file(&lock);
3569 return error(_("failed to finalize '%s'"), filename);
3572 strbuf_release(&buf);
3573 return 0;
3576 static int do_label(struct repository *r, const char *name, int len)
3578 struct ref_store *refs = get_main_ref_store(r);
3579 struct ref_transaction *transaction;
3580 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3581 struct strbuf msg = STRBUF_INIT;
3582 int ret = 0;
3583 struct object_id head_oid;
3585 if (len == 1 && *name == '#')
3586 return error(_("illegal label name: '%.*s'"), len, name);
3588 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3589 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3591 transaction = ref_store_transaction_begin(refs, &err);
3592 if (!transaction) {
3593 error("%s", err.buf);
3594 ret = -1;
3595 } else if (get_oid("HEAD", &head_oid)) {
3596 error(_("could not read HEAD"));
3597 ret = -1;
3598 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3599 NULL, 0, msg.buf, &err) < 0 ||
3600 ref_transaction_commit(transaction, &err)) {
3601 error("%s", err.buf);
3602 ret = -1;
3604 ref_transaction_free(transaction);
3605 strbuf_release(&err);
3606 strbuf_release(&msg);
3608 if (!ret)
3609 ret = safe_append(rebase_path_refs_to_delete(),
3610 "%s\n", ref_name.buf);
3611 strbuf_release(&ref_name);
3613 return ret;
3616 __attribute__((format (printf, 3, 4)))
3617 static const char *reflog_message(struct replay_opts *opts,
3618 const char *sub_action, const char *fmt, ...)
3620 va_list ap;
3621 static struct strbuf buf = STRBUF_INIT;
3622 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3624 va_start(ap, fmt);
3625 strbuf_reset(&buf);
3626 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3627 if (sub_action)
3628 strbuf_addf(&buf, " (%s)", sub_action);
3629 if (fmt) {
3630 strbuf_addstr(&buf, ": ");
3631 strbuf_vaddf(&buf, fmt, ap);
3633 va_end(ap);
3635 return buf.buf;
3638 static int do_reset(struct repository *r,
3639 const char *name, int len,
3640 struct replay_opts *opts)
3642 struct strbuf ref_name = STRBUF_INIT;
3643 struct object_id oid;
3644 struct lock_file lock = LOCK_INIT;
3645 struct tree_desc desc = { 0 };
3646 struct tree *tree;
3647 struct unpack_trees_options unpack_tree_opts = { 0 };
3648 int ret = 0;
3650 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3651 return -1;
3653 if (len == 10 && !strncmp("[new root]", name, len)) {
3654 if (!opts->have_squash_onto) {
3655 const char *hex;
3656 if (commit_tree("", 0, the_hash_algo->empty_tree,
3657 NULL, &opts->squash_onto,
3658 NULL, NULL))
3659 return error(_("writing fake root commit"));
3660 opts->have_squash_onto = 1;
3661 hex = oid_to_hex(&opts->squash_onto);
3662 if (write_message(hex, strlen(hex),
3663 rebase_path_squash_onto(), 0))
3664 return error(_("writing squash-onto"));
3666 oidcpy(&oid, &opts->squash_onto);
3667 } else {
3668 int i;
3670 /* Determine the length of the label */
3671 for (i = 0; i < len; i++)
3672 if (isspace(name[i]))
3673 break;
3674 len = i;
3676 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3677 if (get_oid(ref_name.buf, &oid) &&
3678 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3679 ret = error(_("could not read '%s'"), ref_name.buf);
3680 goto cleanup;
3684 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3685 unpack_tree_opts.head_idx = 1;
3686 unpack_tree_opts.src_index = r->index;
3687 unpack_tree_opts.dst_index = r->index;
3688 unpack_tree_opts.fn = oneway_merge;
3689 unpack_tree_opts.merge = 1;
3690 unpack_tree_opts.update = 1;
3691 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3692 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3694 if (repo_read_index_unmerged(r)) {
3695 ret = error_resolve_conflict(_(action_name(opts)));
3696 goto cleanup;
3699 if (!fill_tree_descriptor(r, &desc, &oid)) {
3700 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3701 goto cleanup;
3704 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3705 ret = -1;
3706 goto cleanup;
3709 tree = parse_tree_indirect(&oid);
3710 prime_cache_tree(r, r->index, tree);
3712 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3713 ret = error(_("could not write index"));
3715 if (!ret)
3716 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3717 len, name), "HEAD", &oid,
3718 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3719 cleanup:
3720 free((void *)desc.buffer);
3721 if (ret < 0)
3722 rollback_lock_file(&lock);
3723 strbuf_release(&ref_name);
3724 clear_unpack_trees_porcelain(&unpack_tree_opts);
3725 return ret;
3728 static struct commit *lookup_label(const char *label, int len,
3729 struct strbuf *buf)
3731 struct commit *commit;
3733 strbuf_reset(buf);
3734 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3735 commit = lookup_commit_reference_by_name(buf->buf);
3736 if (!commit) {
3737 /* fall back to non-rewritten ref or commit */
3738 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3739 commit = lookup_commit_reference_by_name(buf->buf);
3742 if (!commit)
3743 error(_("could not resolve '%s'"), buf->buf);
3745 return commit;
3748 static int do_merge(struct repository *r,
3749 struct commit *commit,
3750 const char *arg, int arg_len,
3751 int flags, int *check_todo, struct replay_opts *opts)
3753 int run_commit_flags = 0;
3754 struct strbuf ref_name = STRBUF_INIT;
3755 struct commit *head_commit, *merge_commit, *i;
3756 struct commit_list *bases, *j, *reversed = NULL;
3757 struct commit_list *to_merge = NULL, **tail = &to_merge;
3758 const char *strategy = !opts->xopts_nr &&
3759 (!opts->strategy ||
3760 !strcmp(opts->strategy, "recursive") ||
3761 !strcmp(opts->strategy, "ort")) ?
3762 NULL : opts->strategy;
3763 struct merge_options o;
3764 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3765 static struct lock_file lock;
3766 const char *p;
3768 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3769 ret = -1;
3770 goto leave_merge;
3773 head_commit = lookup_commit_reference_by_name("HEAD");
3774 if (!head_commit) {
3775 ret = error(_("cannot merge without a current revision"));
3776 goto leave_merge;
3780 * For octopus merges, the arg starts with the list of revisions to be
3781 * merged. The list is optionally followed by '#' and the oneline.
3783 merge_arg_len = oneline_offset = arg_len;
3784 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3785 if (!*p)
3786 break;
3787 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3788 p += 1 + strspn(p + 1, " \t\n");
3789 oneline_offset = p - arg;
3790 break;
3792 k = strcspn(p, " \t\n");
3793 if (!k)
3794 continue;
3795 merge_commit = lookup_label(p, k, &ref_name);
3796 if (!merge_commit) {
3797 ret = error(_("unable to parse '%.*s'"), k, p);
3798 goto leave_merge;
3800 tail = &commit_list_insert(merge_commit, tail)->next;
3801 p += k;
3802 merge_arg_len = p - arg;
3805 if (!to_merge) {
3806 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3807 goto leave_merge;
3810 if (opts->have_squash_onto &&
3811 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3813 * When the user tells us to "merge" something into a
3814 * "[new root]", let's simply fast-forward to the merge head.
3816 rollback_lock_file(&lock);
3817 if (to_merge->next)
3818 ret = error(_("octopus merge cannot be executed on "
3819 "top of a [new root]"));
3820 else
3821 ret = fast_forward_to(r, &to_merge->item->object.oid,
3822 &head_commit->object.oid, 0,
3823 opts);
3824 goto leave_merge;
3828 * If HEAD is not identical to the first parent of the original merge
3829 * commit, we cannot fast-forward.
3831 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3832 oideq(&commit->parents->item->object.oid,
3833 &head_commit->object.oid);
3836 * If any merge head is different from the original one, we cannot
3837 * fast-forward.
3839 if (can_fast_forward) {
3840 struct commit_list *p = commit->parents->next;
3842 for (j = to_merge; j && p; j = j->next, p = p->next)
3843 if (!oideq(&j->item->object.oid,
3844 &p->item->object.oid)) {
3845 can_fast_forward = 0;
3846 break;
3849 * If the number of merge heads differs from the original merge
3850 * commit, we cannot fast-forward.
3852 if (j || p)
3853 can_fast_forward = 0;
3856 if (can_fast_forward) {
3857 rollback_lock_file(&lock);
3858 ret = fast_forward_to(r, &commit->object.oid,
3859 &head_commit->object.oid, 0, opts);
3860 if (flags & TODO_EDIT_MERGE_MSG)
3861 goto fast_forward_edit;
3863 goto leave_merge;
3866 if (commit) {
3867 const char *encoding = get_commit_output_encoding();
3868 const char *message = logmsg_reencode(commit, NULL, encoding);
3869 const char *body;
3870 int len;
3872 if (!message) {
3873 ret = error(_("could not get commit message of '%s'"),
3874 oid_to_hex(&commit->object.oid));
3875 goto leave_merge;
3877 write_author_script(message);
3878 find_commit_subject(message, &body);
3879 len = strlen(body);
3880 ret = write_message(body, len, git_path_merge_msg(r), 0);
3881 unuse_commit_buffer(commit, message);
3882 if (ret) {
3883 error_errno(_("could not write '%s'"),
3884 git_path_merge_msg(r));
3885 goto leave_merge;
3887 } else {
3888 struct strbuf buf = STRBUF_INIT;
3889 int len;
3891 strbuf_addf(&buf, "author %s", git_author_info(0));
3892 write_author_script(buf.buf);
3893 strbuf_reset(&buf);
3895 if (oneline_offset < arg_len) {
3896 p = arg + oneline_offset;
3897 len = arg_len - oneline_offset;
3898 } else {
3899 strbuf_addf(&buf, "Merge %s '%.*s'",
3900 to_merge->next ? "branches" : "branch",
3901 merge_arg_len, arg);
3902 p = buf.buf;
3903 len = buf.len;
3906 ret = write_message(p, len, git_path_merge_msg(r), 0);
3907 strbuf_release(&buf);
3908 if (ret) {
3909 error_errno(_("could not write '%s'"),
3910 git_path_merge_msg(r));
3911 goto leave_merge;
3915 if (strategy || to_merge->next) {
3916 /* Octopus merge */
3917 struct child_process cmd = CHILD_PROCESS_INIT;
3919 if (read_env_script(&cmd.env_array)) {
3920 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3922 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3923 goto leave_merge;
3926 if (opts->committer_date_is_author_date)
3927 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3928 opts->ignore_date ?
3929 "" :
3930 author_date_from_env_array(&cmd.env_array));
3931 if (opts->ignore_date)
3932 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3934 cmd.git_cmd = 1;
3935 strvec_push(&cmd.args, "merge");
3936 strvec_push(&cmd.args, "-s");
3937 if (!strategy)
3938 strvec_push(&cmd.args, "octopus");
3939 else {
3940 strvec_push(&cmd.args, strategy);
3941 for (k = 0; k < opts->xopts_nr; k++)
3942 strvec_pushf(&cmd.args,
3943 "-X%s", opts->xopts[k]);
3945 if (!(flags & TODO_EDIT_MERGE_MSG))
3946 strvec_push(&cmd.args, "--no-edit");
3947 else
3948 strvec_push(&cmd.args, "--edit");
3949 strvec_push(&cmd.args, "--no-ff");
3950 strvec_push(&cmd.args, "--no-log");
3951 strvec_push(&cmd.args, "--no-stat");
3952 strvec_push(&cmd.args, "-F");
3953 strvec_push(&cmd.args, git_path_merge_msg(r));
3954 if (opts->gpg_sign)
3955 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3956 else
3957 strvec_push(&cmd.args, "--no-gpg-sign");
3959 /* Add the tips to be merged */
3960 for (j = to_merge; j; j = j->next)
3961 strvec_push(&cmd.args,
3962 oid_to_hex(&j->item->object.oid));
3964 strbuf_release(&ref_name);
3965 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3966 NULL, 0);
3967 rollback_lock_file(&lock);
3969 ret = run_command(&cmd);
3971 /* force re-reading of the cache */
3972 if (!ret && (discard_index(r->index) < 0 ||
3973 repo_read_index(r) < 0))
3974 ret = error(_("could not read index"));
3975 goto leave_merge;
3978 merge_commit = to_merge->item;
3979 bases = get_merge_bases(head_commit, merge_commit);
3980 if (bases && oideq(&merge_commit->object.oid,
3981 &bases->item->object.oid)) {
3982 ret = 0;
3983 /* skip merging an ancestor of HEAD */
3984 goto leave_merge;
3987 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3988 git_path_merge_head(r), 0);
3989 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3991 for (j = bases; j; j = j->next)
3992 commit_list_insert(j->item, &reversed);
3993 free_commit_list(bases);
3995 repo_read_index(r);
3996 init_merge_options(&o, r);
3997 o.branch1 = "HEAD";
3998 o.branch2 = ref_name.buf;
3999 o.buffer_output = 2;
4001 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4003 * TODO: Should use merge_incore_recursive() and
4004 * merge_switch_to_result(), skipping the call to
4005 * merge_switch_to_result() when we don't actually need to
4006 * update the index and working copy immediately.
4008 ret = merge_ort_recursive(&o,
4009 head_commit, merge_commit, reversed,
4010 &i);
4011 } else {
4012 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4013 &i);
4015 if (ret <= 0)
4016 fputs(o.obuf.buf, stdout);
4017 strbuf_release(&o.obuf);
4018 if (ret < 0) {
4019 error(_("could not even attempt to merge '%.*s'"),
4020 merge_arg_len, arg);
4021 goto leave_merge;
4024 * The return value of merge_recursive() is 1 on clean, and 0 on
4025 * unclean merge.
4027 * Let's reverse that, so that do_merge() returns 0 upon success and
4028 * 1 upon failed merge (keeping the return value -1 for the cases where
4029 * we will want to reschedule the `merge` command).
4031 ret = !ret;
4033 if (r->index->cache_changed &&
4034 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4035 ret = error(_("merge: Unable to write new index file"));
4036 goto leave_merge;
4039 rollback_lock_file(&lock);
4040 if (ret)
4041 repo_rerere(r, opts->allow_rerere_auto);
4042 else
4044 * In case of problems, we now want to return a positive
4045 * value (a negative one would indicate that the `merge`
4046 * command needs to be rescheduled).
4048 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4049 run_commit_flags);
4051 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4052 fast_forward_edit:
4053 *check_todo = 1;
4054 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4055 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4059 leave_merge:
4060 strbuf_release(&ref_name);
4061 rollback_lock_file(&lock);
4062 free_commit_list(to_merge);
4063 return ret;
4066 static int is_final_fixup(struct todo_list *todo_list)
4068 int i = todo_list->current;
4070 if (!is_fixup(todo_list->items[i].command))
4071 return 0;
4073 while (++i < todo_list->nr)
4074 if (is_fixup(todo_list->items[i].command))
4075 return 0;
4076 else if (!is_noop(todo_list->items[i].command))
4077 break;
4078 return 1;
4081 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4083 int i;
4085 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4086 if (!is_noop(todo_list->items[i].command))
4087 return todo_list->items[i].command;
4089 return -1;
4092 void create_autostash(struct repository *r, const char *path,
4093 const char *default_reflog_action)
4095 struct strbuf buf = STRBUF_INIT;
4096 struct lock_file lock_file = LOCK_INIT;
4097 int fd;
4099 fd = repo_hold_locked_index(r, &lock_file, 0);
4100 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4101 if (0 <= fd)
4102 repo_update_index_if_able(r, &lock_file);
4103 rollback_lock_file(&lock_file);
4105 if (has_unstaged_changes(r, 1) ||
4106 has_uncommitted_changes(r, 1)) {
4107 struct child_process stash = CHILD_PROCESS_INIT;
4108 struct object_id oid;
4110 strvec_pushl(&stash.args,
4111 "stash", "create", "autostash", NULL);
4112 stash.git_cmd = 1;
4113 stash.no_stdin = 1;
4114 strbuf_reset(&buf);
4115 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4116 die(_("Cannot autostash"));
4117 strbuf_trim_trailing_newline(&buf);
4118 if (get_oid(buf.buf, &oid))
4119 die(_("Unexpected stash response: '%s'"),
4120 buf.buf);
4121 strbuf_reset(&buf);
4122 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4124 if (safe_create_leading_directories_const(path))
4125 die(_("Could not create directory for '%s'"),
4126 path);
4127 write_file(path, "%s", oid_to_hex(&oid));
4128 printf(_("Created autostash: %s\n"), buf.buf);
4129 if (reset_head(r, NULL, "reset --hard",
4130 NULL, RESET_HEAD_HARD, NULL, NULL,
4131 default_reflog_action) < 0)
4132 die(_("could not reset --hard"));
4134 if (discard_index(r->index) < 0 ||
4135 repo_read_index(r) < 0)
4136 die(_("could not read index"));
4138 strbuf_release(&buf);
4141 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4143 struct child_process child = CHILD_PROCESS_INIT;
4144 int ret = 0;
4146 if (attempt_apply) {
4147 child.git_cmd = 1;
4148 child.no_stdout = 1;
4149 child.no_stderr = 1;
4150 strvec_push(&child.args, "stash");
4151 strvec_push(&child.args, "apply");
4152 strvec_push(&child.args, stash_oid);
4153 ret = run_command(&child);
4156 if (attempt_apply && !ret)
4157 fprintf(stderr, _("Applied autostash.\n"));
4158 else {
4159 struct child_process store = CHILD_PROCESS_INIT;
4161 store.git_cmd = 1;
4162 strvec_push(&store.args, "stash");
4163 strvec_push(&store.args, "store");
4164 strvec_push(&store.args, "-m");
4165 strvec_push(&store.args, "autostash");
4166 strvec_push(&store.args, "-q");
4167 strvec_push(&store.args, stash_oid);
4168 if (run_command(&store))
4169 ret = error(_("cannot store %s"), stash_oid);
4170 else
4171 fprintf(stderr,
4172 _("%s\n"
4173 "Your changes are safe in the stash.\n"
4174 "You can run \"git stash pop\" or"
4175 " \"git stash drop\" at any time.\n"),
4176 attempt_apply ?
4177 _("Applying autostash resulted in conflicts.") :
4178 _("Autostash exists; creating a new stash entry."));
4181 return ret;
4184 static int apply_save_autostash(const char *path, int attempt_apply)
4186 struct strbuf stash_oid = STRBUF_INIT;
4187 int ret = 0;
4189 if (!read_oneliner(&stash_oid, path,
4190 READ_ONELINER_SKIP_IF_EMPTY)) {
4191 strbuf_release(&stash_oid);
4192 return 0;
4194 strbuf_trim(&stash_oid);
4196 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4198 unlink(path);
4199 strbuf_release(&stash_oid);
4200 return ret;
4203 int save_autostash(const char *path)
4205 return apply_save_autostash(path, 0);
4208 int apply_autostash(const char *path)
4210 return apply_save_autostash(path, 1);
4213 int apply_autostash_oid(const char *stash_oid)
4215 return apply_save_autostash_oid(stash_oid, 1);
4218 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4219 const char *commit, const char *action)
4221 struct child_process cmd = CHILD_PROCESS_INIT;
4222 int ret;
4224 cmd.git_cmd = 1;
4226 strvec_push(&cmd.args, "checkout");
4227 strvec_push(&cmd.args, commit);
4228 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4230 if (opts->verbose)
4231 ret = run_command(&cmd);
4232 else
4233 ret = run_command_silent_on_success(&cmd);
4235 if (!ret)
4236 discard_index(r->index);
4238 return ret;
4241 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4242 const char *onto_name, const struct object_id *onto,
4243 const struct object_id *orig_head)
4245 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4247 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4248 apply_autostash(rebase_path_autostash());
4249 sequencer_remove_state(opts);
4250 return error(_("could not detach HEAD"));
4253 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4256 static int stopped_at_head(struct repository *r)
4258 struct object_id head;
4259 struct commit *commit;
4260 struct commit_message message;
4262 if (get_oid("HEAD", &head) ||
4263 !(commit = lookup_commit(r, &head)) ||
4264 parse_commit(commit) || get_message(commit, &message))
4265 fprintf(stderr, _("Stopped at HEAD\n"));
4266 else {
4267 fprintf(stderr, _("Stopped at %s\n"), message.label);
4268 free_message(commit, &message);
4270 return 0;
4274 static int reread_todo_if_changed(struct repository *r,
4275 struct todo_list *todo_list,
4276 struct replay_opts *opts)
4278 int offset;
4279 struct strbuf buf = STRBUF_INIT;
4281 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4282 return -1;
4283 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4284 if (buf.len != todo_list->buf.len - offset ||
4285 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4286 /* Reread the todo file if it has changed. */
4287 todo_list_release(todo_list);
4288 if (read_populate_todo(r, todo_list, opts))
4289 return -1; /* message was printed */
4290 /* `current` will be incremented on return */
4291 todo_list->current = -1;
4293 strbuf_release(&buf);
4295 return 0;
4298 static const char rescheduled_advice[] =
4299 N_("Could not execute the todo command\n"
4300 "\n"
4301 " %.*s"
4302 "\n"
4303 "It has been rescheduled; To edit the command before continuing, please\n"
4304 "edit the todo list first:\n"
4305 "\n"
4306 " git rebase --edit-todo\n"
4307 " git rebase --continue\n");
4309 static int pick_commits(struct repository *r,
4310 struct todo_list *todo_list,
4311 struct replay_opts *opts)
4313 int res = 0, reschedule = 0;
4314 char *prev_reflog_action;
4316 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4317 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4318 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4319 if (opts->allow_ff)
4320 assert(!(opts->signoff || opts->no_commit ||
4321 opts->record_origin || should_edit(opts) ||
4322 opts->committer_date_is_author_date ||
4323 opts->ignore_date));
4324 if (read_and_refresh_cache(r, opts))
4325 return -1;
4327 while (todo_list->current < todo_list->nr) {
4328 struct todo_item *item = todo_list->items + todo_list->current;
4329 const char *arg = todo_item_get_arg(todo_list, item);
4330 int check_todo = 0;
4332 if (save_todo(todo_list, opts))
4333 return -1;
4334 if (is_rebase_i(opts)) {
4335 if (item->command != TODO_COMMENT) {
4336 FILE *f = fopen(rebase_path_msgnum(), "w");
4338 todo_list->done_nr++;
4340 if (f) {
4341 fprintf(f, "%d\n", todo_list->done_nr);
4342 fclose(f);
4344 if (!opts->quiet)
4345 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4346 todo_list->done_nr,
4347 todo_list->total_nr,
4348 opts->verbose ? "\n" : "\r");
4350 unlink(rebase_path_message());
4351 unlink(rebase_path_author_script());
4352 unlink(rebase_path_stopped_sha());
4353 unlink(rebase_path_amend());
4354 unlink(git_path_merge_head(r));
4355 unlink(git_path_auto_merge(r));
4356 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4358 if (item->command == TODO_BREAK) {
4359 if (!opts->verbose)
4360 term_clear_line();
4361 return stopped_at_head(r);
4364 if (item->command <= TODO_SQUASH) {
4365 if (is_rebase_i(opts))
4366 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4367 command_to_string(item->command), NULL),
4369 res = do_pick_commit(r, item, opts,
4370 is_final_fixup(todo_list),
4371 &check_todo);
4372 if (is_rebase_i(opts))
4373 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4374 if (is_rebase_i(opts) && res < 0) {
4375 /* Reschedule */
4376 advise(_(rescheduled_advice),
4377 get_item_line_length(todo_list,
4378 todo_list->current),
4379 get_item_line(todo_list,
4380 todo_list->current));
4381 todo_list->current--;
4382 if (save_todo(todo_list, opts))
4383 return -1;
4385 if (item->command == TODO_EDIT) {
4386 struct commit *commit = item->commit;
4387 if (!res) {
4388 if (!opts->verbose)
4389 term_clear_line();
4390 fprintf(stderr,
4391 _("Stopped at %s... %.*s\n"),
4392 short_commit_name(commit),
4393 item->arg_len, arg);
4395 return error_with_patch(r, commit,
4396 arg, item->arg_len, opts, res, !res);
4398 if (is_rebase_i(opts) && !res)
4399 record_in_rewritten(&item->commit->object.oid,
4400 peek_command(todo_list, 1));
4401 if (res && is_fixup(item->command)) {
4402 if (res == 1)
4403 intend_to_amend();
4404 return error_failed_squash(r, item->commit, opts,
4405 item->arg_len, arg);
4406 } else if (res && is_rebase_i(opts) && item->commit) {
4407 int to_amend = 0;
4408 struct object_id oid;
4411 * If we are rewording and have either
4412 * fast-forwarded already, or are about to
4413 * create a new root commit, we want to amend,
4414 * otherwise we do not.
4416 if (item->command == TODO_REWORD &&
4417 !get_oid("HEAD", &oid) &&
4418 (oideq(&item->commit->object.oid, &oid) ||
4419 (opts->have_squash_onto &&
4420 oideq(&opts->squash_onto, &oid))))
4421 to_amend = 1;
4423 return res | error_with_patch(r, item->commit,
4424 arg, item->arg_len, opts,
4425 res, to_amend);
4427 } else if (item->command == TODO_EXEC) {
4428 char *end_of_arg = (char *)(arg + item->arg_len);
4429 int saved = *end_of_arg;
4431 if (!opts->verbose)
4432 term_clear_line();
4433 *end_of_arg = '\0';
4434 res = do_exec(r, arg);
4435 *end_of_arg = saved;
4437 if (res) {
4438 if (opts->reschedule_failed_exec)
4439 reschedule = 1;
4441 check_todo = 1;
4442 } else if (item->command == TODO_LABEL) {
4443 if ((res = do_label(r, arg, item->arg_len)))
4444 reschedule = 1;
4445 } else if (item->command == TODO_RESET) {
4446 if ((res = do_reset(r, arg, item->arg_len, opts)))
4447 reschedule = 1;
4448 } else if (item->command == TODO_MERGE) {
4449 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4450 item->flags, &check_todo, opts)) < 0)
4451 reschedule = 1;
4452 else if (item->commit)
4453 record_in_rewritten(&item->commit->object.oid,
4454 peek_command(todo_list, 1));
4455 if (res > 0)
4456 /* failed with merge conflicts */
4457 return error_with_patch(r, item->commit,
4458 arg, item->arg_len,
4459 opts, res, 0);
4460 } else if (!is_noop(item->command))
4461 return error(_("unknown command %d"), item->command);
4463 if (reschedule) {
4464 advise(_(rescheduled_advice),
4465 get_item_line_length(todo_list,
4466 todo_list->current),
4467 get_item_line(todo_list, todo_list->current));
4468 todo_list->current--;
4469 if (save_todo(todo_list, opts))
4470 return -1;
4471 if (item->commit)
4472 return error_with_patch(r,
4473 item->commit,
4474 arg, item->arg_len,
4475 opts, res, 0);
4476 } else if (is_rebase_i(opts) && check_todo && !res &&
4477 reread_todo_if_changed(r, todo_list, opts)) {
4478 return -1;
4481 todo_list->current++;
4482 if (res)
4483 return res;
4486 if (is_rebase_i(opts)) {
4487 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4488 struct stat st;
4490 /* Stopped in the middle, as planned? */
4491 if (todo_list->current < todo_list->nr)
4492 return 0;
4494 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4495 starts_with(head_ref.buf, "refs/")) {
4496 const char *msg;
4497 struct object_id head, orig;
4498 int res;
4500 if (get_oid("HEAD", &head)) {
4501 res = error(_("cannot read HEAD"));
4502 cleanup_head_ref:
4503 strbuf_release(&head_ref);
4504 strbuf_release(&buf);
4505 return res;
4507 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4508 get_oid_hex(buf.buf, &orig)) {
4509 res = error(_("could not read orig-head"));
4510 goto cleanup_head_ref;
4512 strbuf_reset(&buf);
4513 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4514 res = error(_("could not read 'onto'"));
4515 goto cleanup_head_ref;
4517 msg = reflog_message(opts, "finish", "%s onto %s",
4518 head_ref.buf, buf.buf);
4519 if (update_ref(msg, head_ref.buf, &head, &orig,
4520 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4521 res = error(_("could not update %s"),
4522 head_ref.buf);
4523 goto cleanup_head_ref;
4525 msg = reflog_message(opts, "finish", "returning to %s",
4526 head_ref.buf);
4527 if (create_symref("HEAD", head_ref.buf, msg)) {
4528 res = error(_("could not update HEAD to %s"),
4529 head_ref.buf);
4530 goto cleanup_head_ref;
4532 strbuf_reset(&buf);
4535 if (opts->verbose) {
4536 struct rev_info log_tree_opt;
4537 struct object_id orig, head;
4539 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4540 repo_init_revisions(r, &log_tree_opt, NULL);
4541 log_tree_opt.diff = 1;
4542 log_tree_opt.diffopt.output_format =
4543 DIFF_FORMAT_DIFFSTAT;
4544 log_tree_opt.disable_stdin = 1;
4546 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4547 !get_oid(buf.buf, &orig) &&
4548 !get_oid("HEAD", &head)) {
4549 diff_tree_oid(&orig, &head, "",
4550 &log_tree_opt.diffopt);
4551 log_tree_diff_flush(&log_tree_opt);
4554 flush_rewritten_pending();
4555 if (!stat(rebase_path_rewritten_list(), &st) &&
4556 st.st_size > 0) {
4557 struct child_process child = CHILD_PROCESS_INIT;
4558 const char *post_rewrite_hook =
4559 find_hook("post-rewrite");
4561 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4562 child.git_cmd = 1;
4563 strvec_push(&child.args, "notes");
4564 strvec_push(&child.args, "copy");
4565 strvec_push(&child.args, "--for-rewrite=rebase");
4566 /* we don't care if this copying failed */
4567 run_command(&child);
4569 if (post_rewrite_hook) {
4570 struct child_process hook = CHILD_PROCESS_INIT;
4572 hook.in = open(rebase_path_rewritten_list(),
4573 O_RDONLY);
4574 hook.stdout_to_stderr = 1;
4575 hook.trace2_hook_name = "post-rewrite";
4576 strvec_push(&hook.args, post_rewrite_hook);
4577 strvec_push(&hook.args, "rebase");
4578 /* we don't care if this hook failed */
4579 run_command(&hook);
4582 apply_autostash(rebase_path_autostash());
4584 if (!opts->quiet) {
4585 if (!opts->verbose)
4586 term_clear_line();
4587 fprintf(stderr,
4588 _("Successfully rebased and updated %s.\n"),
4589 head_ref.buf);
4592 strbuf_release(&buf);
4593 strbuf_release(&head_ref);
4597 * Sequence of picks finished successfully; cleanup by
4598 * removing the .git/sequencer directory
4600 return sequencer_remove_state(opts);
4603 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4605 struct strvec argv = STRVEC_INIT;
4606 int ret;
4608 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4609 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4610 return error(_("no cherry-pick or revert in progress"));
4612 strvec_push(&argv, "commit");
4615 * continue_single_pick() handles the case of recovering from a
4616 * conflict. should_edit() doesn't handle that case; for a conflict,
4617 * we want to edit if the user asked for it, or if they didn't specify
4618 * and stdin is a tty.
4620 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4622 * Include --cleanup=strip as well because we don't want the
4623 * "# Conflicts:" messages.
4625 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4627 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4628 strvec_clear(&argv);
4629 return ret;
4632 static int commit_staged_changes(struct repository *r,
4633 struct replay_opts *opts,
4634 struct todo_list *todo_list)
4636 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4637 unsigned int final_fixup = 0, is_clean;
4639 if (has_unstaged_changes(r, 1))
4640 return error(_("cannot rebase: You have unstaged changes."));
4642 is_clean = !has_uncommitted_changes(r, 0);
4644 if (file_exists(rebase_path_amend())) {
4645 struct strbuf rev = STRBUF_INIT;
4646 struct object_id head, to_amend;
4648 if (get_oid("HEAD", &head))
4649 return error(_("cannot amend non-existing commit"));
4650 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4651 return error(_("invalid file: '%s'"), rebase_path_amend());
4652 if (get_oid_hex(rev.buf, &to_amend))
4653 return error(_("invalid contents: '%s'"),
4654 rebase_path_amend());
4655 if (!is_clean && !oideq(&head, &to_amend))
4656 return error(_("\nYou have uncommitted changes in your "
4657 "working tree. Please, commit them\n"
4658 "first and then run 'git rebase "
4659 "--continue' again."));
4661 * When skipping a failed fixup/squash, we need to edit the
4662 * commit message, the current fixup list and count, and if it
4663 * was the last fixup/squash in the chain, we need to clean up
4664 * the commit message and if there was a squash, let the user
4665 * edit it.
4667 if (!is_clean || !opts->current_fixup_count)
4668 ; /* this is not the final fixup */
4669 else if (!oideq(&head, &to_amend) ||
4670 !file_exists(rebase_path_stopped_sha())) {
4671 /* was a final fixup or squash done manually? */
4672 if (!is_fixup(peek_command(todo_list, 0))) {
4673 unlink(rebase_path_fixup_msg());
4674 unlink(rebase_path_squash_msg());
4675 unlink(rebase_path_current_fixups());
4676 strbuf_reset(&opts->current_fixups);
4677 opts->current_fixup_count = 0;
4679 } else {
4680 /* we are in a fixup/squash chain */
4681 const char *p = opts->current_fixups.buf;
4682 int len = opts->current_fixups.len;
4684 opts->current_fixup_count--;
4685 if (!len)
4686 BUG("Incorrect current_fixups:\n%s", p);
4687 while (len && p[len - 1] != '\n')
4688 len--;
4689 strbuf_setlen(&opts->current_fixups, len);
4690 if (write_message(p, len, rebase_path_current_fixups(),
4691 0) < 0)
4692 return error(_("could not write file: '%s'"),
4693 rebase_path_current_fixups());
4696 * If a fixup/squash in a fixup/squash chain failed, the
4697 * commit message is already correct, no need to commit
4698 * it again.
4700 * Only if it is the final command in the fixup/squash
4701 * chain, and only if the chain is longer than a single
4702 * fixup/squash command (which was just skipped), do we
4703 * actually need to re-commit with a cleaned up commit
4704 * message.
4706 if (opts->current_fixup_count > 0 &&
4707 !is_fixup(peek_command(todo_list, 0))) {
4708 final_fixup = 1;
4710 * If there was not a single "squash" in the
4711 * chain, we only need to clean up the commit
4712 * message, no need to bother the user with
4713 * opening the commit message in the editor.
4715 if (!starts_with(p, "squash ") &&
4716 !strstr(p, "\nsquash "))
4717 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4718 } else if (is_fixup(peek_command(todo_list, 0))) {
4720 * We need to update the squash message to skip
4721 * the latest commit message.
4723 struct commit *commit;
4724 const char *path = rebase_path_squash_msg();
4725 const char *encoding = get_commit_output_encoding();
4727 if (parse_head(r, &commit) ||
4728 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4729 write_message(p, strlen(p), path, 0)) {
4730 unuse_commit_buffer(commit, p);
4731 return error(_("could not write file: "
4732 "'%s'"), path);
4734 unuse_commit_buffer(commit, p);
4738 strbuf_release(&rev);
4739 flags |= AMEND_MSG;
4742 if (is_clean) {
4743 if (refs_ref_exists(get_main_ref_store(r),
4744 "CHERRY_PICK_HEAD") &&
4745 refs_delete_ref(get_main_ref_store(r), "",
4746 "CHERRY_PICK_HEAD", NULL, 0))
4747 return error(_("could not remove CHERRY_PICK_HEAD"));
4748 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4749 return error_errno(_("could not remove '%s'"),
4750 git_path_merge_msg(r));
4751 if (!final_fixup)
4752 return 0;
4755 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4756 opts, flags))
4757 return error(_("could not commit staged changes."));
4758 unlink(rebase_path_amend());
4759 unlink(git_path_merge_head(r));
4760 unlink(git_path_auto_merge(r));
4761 if (final_fixup) {
4762 unlink(rebase_path_fixup_msg());
4763 unlink(rebase_path_squash_msg());
4765 if (opts->current_fixup_count > 0) {
4767 * Whether final fixup or not, we just cleaned up the commit
4768 * message...
4770 unlink(rebase_path_current_fixups());
4771 strbuf_reset(&opts->current_fixups);
4772 opts->current_fixup_count = 0;
4774 return 0;
4777 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4779 struct todo_list todo_list = TODO_LIST_INIT;
4780 int res;
4782 if (read_and_refresh_cache(r, opts))
4783 return -1;
4785 if (read_populate_opts(opts))
4786 return -1;
4787 if (is_rebase_i(opts)) {
4788 if ((res = read_populate_todo(r, &todo_list, opts)))
4789 goto release_todo_list;
4791 if (file_exists(rebase_path_dropped())) {
4792 if ((res = todo_list_check_against_backup(r, &todo_list)))
4793 goto release_todo_list;
4795 unlink(rebase_path_dropped());
4798 if (commit_staged_changes(r, opts, &todo_list)) {
4799 res = -1;
4800 goto release_todo_list;
4802 } else if (!file_exists(get_todo_path(opts)))
4803 return continue_single_pick(r, opts);
4804 else if ((res = read_populate_todo(r, &todo_list, opts)))
4805 goto release_todo_list;
4807 if (!is_rebase_i(opts)) {
4808 /* Verify that the conflict has been resolved */
4809 if (refs_ref_exists(get_main_ref_store(r),
4810 "CHERRY_PICK_HEAD") ||
4811 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4812 res = continue_single_pick(r, opts);
4813 if (res)
4814 goto release_todo_list;
4816 if (index_differs_from(r, "HEAD", NULL, 0)) {
4817 res = error_dirty_index(r, opts);
4818 goto release_todo_list;
4820 todo_list.current++;
4821 } else if (file_exists(rebase_path_stopped_sha())) {
4822 struct strbuf buf = STRBUF_INIT;
4823 struct object_id oid;
4825 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4826 READ_ONELINER_SKIP_IF_EMPTY) &&
4827 !get_oid_hex(buf.buf, &oid))
4828 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4829 strbuf_release(&buf);
4832 res = pick_commits(r, &todo_list, opts);
4833 release_todo_list:
4834 todo_list_release(&todo_list);
4835 return res;
4838 static int single_pick(struct repository *r,
4839 struct commit *cmit,
4840 struct replay_opts *opts)
4842 int check_todo;
4843 struct todo_item item;
4845 item.command = opts->action == REPLAY_PICK ?
4846 TODO_PICK : TODO_REVERT;
4847 item.commit = cmit;
4849 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4850 return do_pick_commit(r, &item, opts, 0, &check_todo);
4853 int sequencer_pick_revisions(struct repository *r,
4854 struct replay_opts *opts)
4856 struct todo_list todo_list = TODO_LIST_INIT;
4857 struct object_id oid;
4858 int i, res;
4860 assert(opts->revs);
4861 if (read_and_refresh_cache(r, opts))
4862 return -1;
4864 for (i = 0; i < opts->revs->pending.nr; i++) {
4865 struct object_id oid;
4866 const char *name = opts->revs->pending.objects[i].name;
4868 /* This happens when using --stdin. */
4869 if (!strlen(name))
4870 continue;
4872 if (!get_oid(name, &oid)) {
4873 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4874 enum object_type type = oid_object_info(r,
4875 &oid,
4876 NULL);
4877 return error(_("%s: can't cherry-pick a %s"),
4878 name, type_name(type));
4880 } else
4881 return error(_("%s: bad revision"), name);
4885 * If we were called as "git cherry-pick <commit>", just
4886 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4887 * REVERT_HEAD, and don't touch the sequencer state.
4888 * This means it is possible to cherry-pick in the middle
4889 * of a cherry-pick sequence.
4891 if (opts->revs->cmdline.nr == 1 &&
4892 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4893 opts->revs->no_walk &&
4894 !opts->revs->cmdline.rev->flags) {
4895 struct commit *cmit;
4896 if (prepare_revision_walk(opts->revs))
4897 return error(_("revision walk setup failed"));
4898 cmit = get_revision(opts->revs);
4899 if (!cmit)
4900 return error(_("empty commit set passed"));
4901 if (get_revision(opts->revs))
4902 BUG("unexpected extra commit from walk");
4903 return single_pick(r, cmit, opts);
4907 * Start a new cherry-pick/ revert sequence; but
4908 * first, make sure that an existing one isn't in
4909 * progress
4912 if (walk_revs_populate_todo(&todo_list, opts) ||
4913 create_seq_dir(r) < 0)
4914 return -1;
4915 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4916 return error(_("can't revert as initial commit"));
4917 if (save_head(oid_to_hex(&oid)))
4918 return -1;
4919 if (save_opts(opts))
4920 return -1;
4921 update_abort_safety_file();
4922 res = pick_commits(r, &todo_list, opts);
4923 todo_list_release(&todo_list);
4924 return res;
4927 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4929 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4930 struct strbuf sob = STRBUF_INIT;
4931 int has_footer;
4933 strbuf_addstr(&sob, sign_off_header);
4934 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4935 strbuf_addch(&sob, '\n');
4937 if (!ignore_footer)
4938 strbuf_complete_line(msgbuf);
4941 * If the whole message buffer is equal to the sob, pretend that we
4942 * found a conforming footer with a matching sob
4944 if (msgbuf->len - ignore_footer == sob.len &&
4945 !strncmp(msgbuf->buf, sob.buf, sob.len))
4946 has_footer = 3;
4947 else
4948 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4950 if (!has_footer) {
4951 const char *append_newlines = NULL;
4952 size_t len = msgbuf->len - ignore_footer;
4954 if (!len) {
4956 * The buffer is completely empty. Leave foom for
4957 * the title and body to be filled in by the user.
4959 append_newlines = "\n\n";
4960 } else if (len == 1) {
4962 * Buffer contains a single newline. Add another
4963 * so that we leave room for the title and body.
4965 append_newlines = "\n";
4966 } else if (msgbuf->buf[len - 2] != '\n') {
4968 * Buffer ends with a single newline. Add another
4969 * so that there is an empty line between the message
4970 * body and the sob.
4972 append_newlines = "\n";
4973 } /* else, the buffer already ends with two newlines. */
4975 if (append_newlines)
4976 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4977 append_newlines, strlen(append_newlines));
4980 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4981 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4982 sob.buf, sob.len);
4984 strbuf_release(&sob);
4987 struct labels_entry {
4988 struct hashmap_entry entry;
4989 char label[FLEX_ARRAY];
4992 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4993 const struct hashmap_entry *entry_or_key, const void *key)
4995 const struct labels_entry *a, *b;
4997 a = container_of(eptr, const struct labels_entry, entry);
4998 b = container_of(entry_or_key, const struct labels_entry, entry);
5000 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5003 struct string_entry {
5004 struct oidmap_entry entry;
5005 char string[FLEX_ARRAY];
5008 struct label_state {
5009 struct oidmap commit2label;
5010 struct hashmap labels;
5011 struct strbuf buf;
5014 static const char *label_oid(struct object_id *oid, const char *label,
5015 struct label_state *state)
5017 struct labels_entry *labels_entry;
5018 struct string_entry *string_entry;
5019 struct object_id dummy;
5020 int i;
5022 string_entry = oidmap_get(&state->commit2label, oid);
5023 if (string_entry)
5024 return string_entry->string;
5027 * For "uninteresting" commits, i.e. commits that are not to be
5028 * rebased, and which can therefore not be labeled, we use a unique
5029 * abbreviation of the commit name. This is slightly more complicated
5030 * than calling find_unique_abbrev() because we also need to make
5031 * sure that the abbreviation does not conflict with any other
5032 * label.
5034 * We disallow "interesting" commits to be labeled by a string that
5035 * is a valid full-length hash, to ensure that we always can find an
5036 * abbreviation for any uninteresting commit's names that does not
5037 * clash with any other label.
5039 strbuf_reset(&state->buf);
5040 if (!label) {
5041 char *p;
5043 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5044 label = p = state->buf.buf;
5046 find_unique_abbrev_r(p, oid, default_abbrev);
5049 * We may need to extend the abbreviated hash so that there is
5050 * no conflicting label.
5052 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5053 size_t i = strlen(p) + 1;
5055 oid_to_hex_r(p, oid);
5056 for (; i < the_hash_algo->hexsz; i++) {
5057 char save = p[i];
5058 p[i] = '\0';
5059 if (!hashmap_get_from_hash(&state->labels,
5060 strihash(p), p))
5061 break;
5062 p[i] = save;
5065 } else {
5066 struct strbuf *buf = &state->buf;
5069 * Sanitize labels by replacing non-alpha-numeric characters
5070 * (including white-space ones) by dashes, as they might be
5071 * illegal in file names (and hence in ref names).
5073 * Note that we retain non-ASCII UTF-8 characters (identified
5074 * via the most significant bit). They should be all acceptable
5075 * in file names. We do not validate the UTF-8 here, that's not
5076 * the job of this function.
5078 for (; *label; label++)
5079 if ((*label & 0x80) || isalnum(*label))
5080 strbuf_addch(buf, *label);
5081 /* avoid leading dash and double-dashes */
5082 else if (buf->len && buf->buf[buf->len - 1] != '-')
5083 strbuf_addch(buf, '-');
5084 if (!buf->len) {
5085 strbuf_addstr(buf, "rev-");
5086 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5088 label = buf->buf;
5090 if ((buf->len == the_hash_algo->hexsz &&
5091 !get_oid_hex(label, &dummy)) ||
5092 (buf->len == 1 && *label == '#') ||
5093 hashmap_get_from_hash(&state->labels,
5094 strihash(label), label)) {
5096 * If the label already exists, or if the label is a
5097 * valid full OID, or the label is a '#' (which we use
5098 * as a separator between merge heads and oneline), we
5099 * append a dash and a number to make it unique.
5101 size_t len = buf->len;
5103 for (i = 2; ; i++) {
5104 strbuf_setlen(buf, len);
5105 strbuf_addf(buf, "-%d", i);
5106 if (!hashmap_get_from_hash(&state->labels,
5107 strihash(buf->buf),
5108 buf->buf))
5109 break;
5112 label = buf->buf;
5116 FLEX_ALLOC_STR(labels_entry, label, label);
5117 hashmap_entry_init(&labels_entry->entry, strihash(label));
5118 hashmap_add(&state->labels, &labels_entry->entry);
5120 FLEX_ALLOC_STR(string_entry, string, label);
5121 oidcpy(&string_entry->entry.oid, oid);
5122 oidmap_put(&state->commit2label, string_entry);
5124 return string_entry->string;
5127 static int make_script_with_merges(struct pretty_print_context *pp,
5128 struct rev_info *revs, struct strbuf *out,
5129 unsigned flags)
5131 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5132 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5133 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5134 int skipped_commit = 0;
5135 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5136 struct strbuf label = STRBUF_INIT;
5137 struct commit_list *commits = NULL, **tail = &commits, *iter;
5138 struct commit_list *tips = NULL, **tips_tail = &tips;
5139 struct commit *commit;
5140 struct oidmap commit2todo = OIDMAP_INIT;
5141 struct string_entry *entry;
5142 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5143 shown = OIDSET_INIT;
5144 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5146 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5147 const char *cmd_pick = abbr ? "p" : "pick",
5148 *cmd_label = abbr ? "l" : "label",
5149 *cmd_reset = abbr ? "t" : "reset",
5150 *cmd_merge = abbr ? "m" : "merge";
5152 oidmap_init(&commit2todo, 0);
5153 oidmap_init(&state.commit2label, 0);
5154 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5155 strbuf_init(&state.buf, 32);
5157 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5158 struct labels_entry *onto_label_entry;
5159 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5160 FLEX_ALLOC_STR(entry, string, "onto");
5161 oidcpy(&entry->entry.oid, oid);
5162 oidmap_put(&state.commit2label, entry);
5164 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5165 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5166 hashmap_add(&state.labels, &onto_label_entry->entry);
5170 * First phase:
5171 * - get onelines for all commits
5172 * - gather all branch tips (i.e. 2nd or later parents of merges)
5173 * - label all branch tips
5175 while ((commit = get_revision(revs))) {
5176 struct commit_list *to_merge;
5177 const char *p1, *p2;
5178 struct object_id *oid;
5179 int is_empty;
5181 tail = &commit_list_insert(commit, tail)->next;
5182 oidset_insert(&interesting, &commit->object.oid);
5184 is_empty = is_original_commit_empty(commit);
5185 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5186 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5187 warning(_("skipped previously applied commit %s"),
5188 short_commit_name(commit));
5189 skipped_commit = 1;
5190 continue;
5192 if (is_empty && !keep_empty)
5193 continue;
5195 strbuf_reset(&oneline);
5196 pretty_print_commit(pp, commit, &oneline);
5198 to_merge = commit->parents ? commit->parents->next : NULL;
5199 if (!to_merge) {
5200 /* non-merge commit: easy case */
5201 strbuf_reset(&buf);
5202 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5203 oid_to_hex(&commit->object.oid),
5204 oneline.buf);
5205 if (is_empty)
5206 strbuf_addf(&buf, " %c empty",
5207 comment_line_char);
5209 FLEX_ALLOC_STR(entry, string, buf.buf);
5210 oidcpy(&entry->entry.oid, &commit->object.oid);
5211 oidmap_put(&commit2todo, entry);
5213 continue;
5216 /* Create a label */
5217 strbuf_reset(&label);
5218 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5219 (p1 = strchr(p1, '\'')) &&
5220 (p2 = strchr(++p1, '\'')))
5221 strbuf_add(&label, p1, p2 - p1);
5222 else if (skip_prefix(oneline.buf, "Merge pull request ",
5223 &p1) &&
5224 (p1 = strstr(p1, " from ")))
5225 strbuf_addstr(&label, p1 + strlen(" from "));
5226 else
5227 strbuf_addbuf(&label, &oneline);
5229 strbuf_reset(&buf);
5230 strbuf_addf(&buf, "%s -C %s",
5231 cmd_merge, oid_to_hex(&commit->object.oid));
5233 /* label the tips of merged branches */
5234 for (; to_merge; to_merge = to_merge->next) {
5235 oid = &to_merge->item->object.oid;
5236 strbuf_addch(&buf, ' ');
5238 if (!oidset_contains(&interesting, oid)) {
5239 strbuf_addstr(&buf, label_oid(oid, NULL,
5240 &state));
5241 continue;
5244 tips_tail = &commit_list_insert(to_merge->item,
5245 tips_tail)->next;
5247 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5249 strbuf_addf(&buf, " # %s", oneline.buf);
5251 FLEX_ALLOC_STR(entry, string, buf.buf);
5252 oidcpy(&entry->entry.oid, &commit->object.oid);
5253 oidmap_put(&commit2todo, entry);
5255 if (skipped_commit)
5256 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5257 _("use --reapply-cherry-picks to include skipped commits"));
5260 * Second phase:
5261 * - label branch points
5262 * - add HEAD to the branch tips
5264 for (iter = commits; iter; iter = iter->next) {
5265 struct commit_list *parent = iter->item->parents;
5266 for (; parent; parent = parent->next) {
5267 struct object_id *oid = &parent->item->object.oid;
5268 if (!oidset_contains(&interesting, oid))
5269 continue;
5270 if (oidset_insert(&child_seen, oid))
5271 label_oid(oid, "branch-point", &state);
5274 /* Add HEAD as implicit "tip of branch" */
5275 if (!iter->next)
5276 tips_tail = &commit_list_insert(iter->item,
5277 tips_tail)->next;
5281 * Third phase: output the todo list. This is a bit tricky, as we
5282 * want to avoid jumping back and forth between revisions. To
5283 * accomplish that goal, we walk backwards from the branch tips,
5284 * gathering commits not yet shown, reversing the list on the fly,
5285 * then outputting that list (labeling revisions as needed).
5287 strbuf_addf(out, "%s onto\n", cmd_label);
5288 for (iter = tips; iter; iter = iter->next) {
5289 struct commit_list *list = NULL, *iter2;
5291 commit = iter->item;
5292 if (oidset_contains(&shown, &commit->object.oid))
5293 continue;
5294 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5296 if (entry)
5297 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5298 else
5299 strbuf_addch(out, '\n');
5301 while (oidset_contains(&interesting, &commit->object.oid) &&
5302 !oidset_contains(&shown, &commit->object.oid)) {
5303 commit_list_insert(commit, &list);
5304 if (!commit->parents) {
5305 commit = NULL;
5306 break;
5308 commit = commit->parents->item;
5311 if (!commit)
5312 strbuf_addf(out, "%s %s\n", cmd_reset,
5313 rebase_cousins || root_with_onto ?
5314 "onto" : "[new root]");
5315 else {
5316 const char *to = NULL;
5318 entry = oidmap_get(&state.commit2label,
5319 &commit->object.oid);
5320 if (entry)
5321 to = entry->string;
5322 else if (!rebase_cousins)
5323 to = label_oid(&commit->object.oid, NULL,
5324 &state);
5326 if (!to || !strcmp(to, "onto"))
5327 strbuf_addf(out, "%s onto\n", cmd_reset);
5328 else {
5329 strbuf_reset(&oneline);
5330 pretty_print_commit(pp, commit, &oneline);
5331 strbuf_addf(out, "%s %s # %s\n",
5332 cmd_reset, to, oneline.buf);
5336 for (iter2 = list; iter2; iter2 = iter2->next) {
5337 struct object_id *oid = &iter2->item->object.oid;
5338 entry = oidmap_get(&commit2todo, oid);
5339 /* only show if not already upstream */
5340 if (entry)
5341 strbuf_addf(out, "%s\n", entry->string);
5342 entry = oidmap_get(&state.commit2label, oid);
5343 if (entry)
5344 strbuf_addf(out, "%s %s\n",
5345 cmd_label, entry->string);
5346 oidset_insert(&shown, oid);
5349 free_commit_list(list);
5352 free_commit_list(commits);
5353 free_commit_list(tips);
5355 strbuf_release(&label);
5356 strbuf_release(&oneline);
5357 strbuf_release(&buf);
5359 oidmap_free(&commit2todo, 1);
5360 oidmap_free(&state.commit2label, 1);
5361 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5362 strbuf_release(&state.buf);
5364 return 0;
5367 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5368 const char **argv, unsigned flags)
5370 char *format = NULL;
5371 struct pretty_print_context pp = {0};
5372 struct rev_info revs;
5373 struct commit *commit;
5374 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5375 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5376 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5377 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5378 int skipped_commit = 0;
5380 repo_init_revisions(r, &revs, NULL);
5381 revs.verbose_header = 1;
5382 if (!rebase_merges)
5383 revs.max_parents = 1;
5384 revs.cherry_mark = !reapply_cherry_picks;
5385 revs.limited = 1;
5386 revs.reverse = 1;
5387 revs.right_only = 1;
5388 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5389 revs.topo_order = 1;
5391 revs.pretty_given = 1;
5392 git_config_get_string("rebase.instructionFormat", &format);
5393 if (!format || !*format) {
5394 free(format);
5395 format = xstrdup("%s");
5397 get_commit_format(format, &revs);
5398 free(format);
5399 pp.fmt = revs.commit_format;
5400 pp.output_encoding = get_log_output_encoding();
5402 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5403 return error(_("make_script: unhandled options"));
5405 if (prepare_revision_walk(&revs) < 0)
5406 return error(_("make_script: error preparing revisions"));
5408 if (rebase_merges)
5409 return make_script_with_merges(&pp, &revs, out, flags);
5411 while ((commit = get_revision(&revs))) {
5412 int is_empty = is_original_commit_empty(commit);
5414 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5415 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5416 warning(_("skipped previously applied commit %s"),
5417 short_commit_name(commit));
5418 skipped_commit = 1;
5419 continue;
5421 if (is_empty && !keep_empty)
5422 continue;
5423 strbuf_addf(out, "%s %s ", insn,
5424 oid_to_hex(&commit->object.oid));
5425 pretty_print_commit(&pp, commit, out);
5426 if (is_empty)
5427 strbuf_addf(out, " %c empty", comment_line_char);
5428 strbuf_addch(out, '\n');
5430 if (skipped_commit)
5431 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5432 _("use --reapply-cherry-picks to include skipped commits"));
5433 return 0;
5437 * Add commands after pick and (series of) squash/fixup commands
5438 * in the todo list.
5440 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5441 struct string_list *commands)
5443 struct strbuf *buf = &todo_list->buf;
5444 size_t base_offset = buf->len;
5445 int i, insert, nr = 0, alloc = 0;
5446 struct todo_item *items = NULL, *base_items = NULL;
5448 CALLOC_ARRAY(base_items, commands->nr);
5449 for (i = 0; i < commands->nr; i++) {
5450 size_t command_len = strlen(commands->items[i].string);
5452 strbuf_addstr(buf, commands->items[i].string);
5453 strbuf_addch(buf, '\n');
5455 base_items[i].command = TODO_EXEC;
5456 base_items[i].offset_in_buf = base_offset;
5457 base_items[i].arg_offset = base_offset + strlen("exec ");
5458 base_items[i].arg_len = command_len - strlen("exec ");
5460 base_offset += command_len + 1;
5464 * Insert <commands> after every pick. Here, fixup/squash chains
5465 * are considered part of the pick, so we insert the commands *after*
5466 * those chains if there are any.
5468 * As we insert the exec commands immediately after rearranging
5469 * any fixups and before the user edits the list, a fixup chain
5470 * can never contain comments (any comments are empty picks that
5471 * have been commented out because the user did not specify
5472 * --keep-empty). So, it is safe to insert an exec command
5473 * without looking at the command following a comment.
5475 insert = 0;
5476 for (i = 0; i < todo_list->nr; i++) {
5477 enum todo_command command = todo_list->items[i].command;
5478 if (insert && !is_fixup(command)) {
5479 ALLOC_GROW(items, nr + commands->nr, alloc);
5480 COPY_ARRAY(items + nr, base_items, commands->nr);
5481 nr += commands->nr;
5483 insert = 0;
5486 ALLOC_GROW(items, nr + 1, alloc);
5487 items[nr++] = todo_list->items[i];
5489 if (command == TODO_PICK || command == TODO_MERGE)
5490 insert = 1;
5493 /* insert or append final <commands> */
5494 if (insert) {
5495 ALLOC_GROW(items, nr + commands->nr, alloc);
5496 COPY_ARRAY(items + nr, base_items, commands->nr);
5497 nr += commands->nr;
5500 free(base_items);
5501 FREE_AND_NULL(todo_list->items);
5502 todo_list->items = items;
5503 todo_list->nr = nr;
5504 todo_list->alloc = alloc;
5507 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5508 struct strbuf *buf, int num, unsigned flags)
5510 struct todo_item *item;
5511 int i, max = todo_list->nr;
5513 if (num > 0 && num < max)
5514 max = num;
5516 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5517 char cmd;
5519 /* if the item is not a command write it and continue */
5520 if (item->command >= TODO_COMMENT) {
5521 strbuf_addf(buf, "%.*s\n", item->arg_len,
5522 todo_item_get_arg(todo_list, item));
5523 continue;
5526 /* add command to the buffer */
5527 cmd = command_to_char(item->command);
5528 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5529 strbuf_addch(buf, cmd);
5530 else
5531 strbuf_addstr(buf, command_to_string(item->command));
5533 /* add commit id */
5534 if (item->commit) {
5535 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5536 short_commit_name(item->commit) :
5537 oid_to_hex(&item->commit->object.oid);
5539 if (item->command == TODO_FIXUP) {
5540 if (item->flags & TODO_EDIT_FIXUP_MSG)
5541 strbuf_addstr(buf, " -c");
5542 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5543 strbuf_addstr(buf, " -C");
5547 if (item->command == TODO_MERGE) {
5548 if (item->flags & TODO_EDIT_MERGE_MSG)
5549 strbuf_addstr(buf, " -c");
5550 else
5551 strbuf_addstr(buf, " -C");
5554 strbuf_addf(buf, " %s", oid);
5557 /* add all the rest */
5558 if (!item->arg_len)
5559 strbuf_addch(buf, '\n');
5560 else
5561 strbuf_addf(buf, " %.*s\n", item->arg_len,
5562 todo_item_get_arg(todo_list, item));
5566 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5567 const char *file, const char *shortrevisions,
5568 const char *shortonto, int num, unsigned flags)
5570 int res;
5571 struct strbuf buf = STRBUF_INIT;
5573 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5574 if (flags & TODO_LIST_APPEND_TODO_HELP)
5575 append_todo_help(count_commands(todo_list),
5576 shortrevisions, shortonto, &buf);
5578 res = write_message(buf.buf, buf.len, file, 0);
5579 strbuf_release(&buf);
5581 return res;
5584 /* skip picking commits whose parents are unchanged */
5585 static int skip_unnecessary_picks(struct repository *r,
5586 struct todo_list *todo_list,
5587 struct object_id *base_oid)
5589 struct object_id *parent_oid;
5590 int i;
5592 for (i = 0; i < todo_list->nr; i++) {
5593 struct todo_item *item = todo_list->items + i;
5595 if (item->command >= TODO_NOOP)
5596 continue;
5597 if (item->command != TODO_PICK)
5598 break;
5599 if (parse_commit(item->commit)) {
5600 return error(_("could not parse commit '%s'"),
5601 oid_to_hex(&item->commit->object.oid));
5603 if (!item->commit->parents)
5604 break; /* root commit */
5605 if (item->commit->parents->next)
5606 break; /* merge commit */
5607 parent_oid = &item->commit->parents->item->object.oid;
5608 if (!oideq(parent_oid, base_oid))
5609 break;
5610 oidcpy(base_oid, &item->commit->object.oid);
5612 if (i > 0) {
5613 const char *done_path = rebase_path_done();
5615 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5616 error_errno(_("could not write to '%s'"), done_path);
5617 return -1;
5620 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5621 todo_list->nr -= i;
5622 todo_list->current = 0;
5623 todo_list->done_nr += i;
5625 if (is_fixup(peek_command(todo_list, 0)))
5626 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5629 return 0;
5632 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5633 const char *shortrevisions, const char *onto_name,
5634 struct commit *onto, const struct object_id *orig_head,
5635 struct string_list *commands, unsigned autosquash,
5636 struct todo_list *todo_list)
5638 char shortonto[GIT_MAX_HEXSZ + 1];
5639 const char *todo_file = rebase_path_todo();
5640 struct todo_list new_todo = TODO_LIST_INIT;
5641 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5642 struct object_id oid = onto->object.oid;
5643 int res;
5645 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5647 if (buf->len == 0) {
5648 struct todo_item *item = append_new_todo(todo_list);
5649 item->command = TODO_NOOP;
5650 item->commit = NULL;
5651 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5654 if (autosquash && todo_list_rearrange_squash(todo_list))
5655 return -1;
5657 if (commands->nr)
5658 todo_list_add_exec_commands(todo_list, commands);
5660 if (count_commands(todo_list) == 0) {
5661 apply_autostash(rebase_path_autostash());
5662 sequencer_remove_state(opts);
5664 return error(_("nothing to do"));
5667 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5668 shortonto, flags);
5669 if (res == -1)
5670 return -1;
5671 else if (res == -2) {
5672 apply_autostash(rebase_path_autostash());
5673 sequencer_remove_state(opts);
5675 return -1;
5676 } else if (res == -3) {
5677 apply_autostash(rebase_path_autostash());
5678 sequencer_remove_state(opts);
5679 todo_list_release(&new_todo);
5681 return error(_("nothing to do"));
5682 } else if (res == -4) {
5683 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5684 todo_list_release(&new_todo);
5686 return -1;
5689 /* Expand the commit IDs */
5690 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5691 strbuf_swap(&new_todo.buf, &buf2);
5692 strbuf_release(&buf2);
5693 new_todo.total_nr -= new_todo.nr;
5694 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5695 BUG("invalid todo list after expanding IDs:\n%s",
5696 new_todo.buf.buf);
5698 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5699 todo_list_release(&new_todo);
5700 return error(_("could not skip unnecessary pick commands"));
5703 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5704 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5705 todo_list_release(&new_todo);
5706 return error_errno(_("could not write '%s'"), todo_file);
5709 res = -1;
5711 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5712 goto cleanup;
5714 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5715 goto cleanup;
5717 todo_list_write_total_nr(&new_todo);
5718 res = pick_commits(r, &new_todo, opts);
5720 cleanup:
5721 todo_list_release(&new_todo);
5723 return res;
5726 struct subject2item_entry {
5727 struct hashmap_entry entry;
5728 int i;
5729 char subject[FLEX_ARRAY];
5732 static int subject2item_cmp(const void *fndata,
5733 const struct hashmap_entry *eptr,
5734 const struct hashmap_entry *entry_or_key,
5735 const void *key)
5737 const struct subject2item_entry *a, *b;
5739 a = container_of(eptr, const struct subject2item_entry, entry);
5740 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5742 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5745 define_commit_slab(commit_todo_item, struct todo_item *);
5747 static int skip_fixupish(const char *subject, const char **p) {
5748 return skip_prefix(subject, "fixup! ", p) ||
5749 skip_prefix(subject, "amend! ", p) ||
5750 skip_prefix(subject, "squash! ", p);
5754 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5755 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5756 * after the former, and change "pick" to "fixup"/"squash".
5758 * Note that if the config has specified a custom instruction format, each log
5759 * message will have to be retrieved from the commit (as the oneline in the
5760 * script cannot be trusted) in order to normalize the autosquash arrangement.
5762 int todo_list_rearrange_squash(struct todo_list *todo_list)
5764 struct hashmap subject2item;
5765 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5766 char **subjects;
5767 struct commit_todo_item commit_todo;
5768 struct todo_item *items = NULL;
5770 init_commit_todo_item(&commit_todo);
5772 * The hashmap maps onelines to the respective todo list index.
5774 * If any items need to be rearranged, the next[i] value will indicate
5775 * which item was moved directly after the i'th.
5777 * In that case, last[i] will indicate the index of the latest item to
5778 * be moved to appear after the i'th.
5780 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5781 ALLOC_ARRAY(next, todo_list->nr);
5782 ALLOC_ARRAY(tail, todo_list->nr);
5783 ALLOC_ARRAY(subjects, todo_list->nr);
5784 for (i = 0; i < todo_list->nr; i++) {
5785 struct strbuf buf = STRBUF_INIT;
5786 struct todo_item *item = todo_list->items + i;
5787 const char *commit_buffer, *subject, *p;
5788 size_t subject_len;
5789 int i2 = -1;
5790 struct subject2item_entry *entry;
5792 next[i] = tail[i] = -1;
5793 if (!item->commit || item->command == TODO_DROP) {
5794 subjects[i] = NULL;
5795 continue;
5798 if (is_fixup(item->command)) {
5799 clear_commit_todo_item(&commit_todo);
5800 return error(_("the script was already rearranged."));
5803 *commit_todo_item_at(&commit_todo, item->commit) = item;
5805 parse_commit(item->commit);
5806 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5807 find_commit_subject(commit_buffer, &subject);
5808 format_subject(&buf, subject, " ");
5809 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5810 unuse_commit_buffer(item->commit, commit_buffer);
5811 if (skip_fixupish(subject, &p)) {
5812 struct commit *commit2;
5814 for (;;) {
5815 while (isspace(*p))
5816 p++;
5817 if (!skip_fixupish(p, &p))
5818 break;
5821 entry = hashmap_get_entry_from_hash(&subject2item,
5822 strhash(p), p,
5823 struct subject2item_entry,
5824 entry);
5825 if (entry)
5826 /* found by title */
5827 i2 = entry->i;
5828 else if (!strchr(p, ' ') &&
5829 (commit2 =
5830 lookup_commit_reference_by_name(p)) &&
5831 *commit_todo_item_at(&commit_todo, commit2))
5832 /* found by commit name */
5833 i2 = *commit_todo_item_at(&commit_todo, commit2)
5834 - todo_list->items;
5835 else {
5836 /* copy can be a prefix of the commit subject */
5837 for (i2 = 0; i2 < i; i2++)
5838 if (subjects[i2] &&
5839 starts_with(subjects[i2], p))
5840 break;
5841 if (i2 == i)
5842 i2 = -1;
5845 if (i2 >= 0) {
5846 rearranged = 1;
5847 if (starts_with(subject, "fixup!")) {
5848 todo_list->items[i].command = TODO_FIXUP;
5849 } else if (starts_with(subject, "amend!")) {
5850 todo_list->items[i].command = TODO_FIXUP;
5851 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5852 } else {
5853 todo_list->items[i].command = TODO_SQUASH;
5855 if (tail[i2] < 0) {
5856 next[i] = next[i2];
5857 next[i2] = i;
5858 } else {
5859 next[i] = next[tail[i2]];
5860 next[tail[i2]] = i;
5862 tail[i2] = i;
5863 } else if (!hashmap_get_from_hash(&subject2item,
5864 strhash(subject), subject)) {
5865 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5866 entry->i = i;
5867 hashmap_entry_init(&entry->entry,
5868 strhash(entry->subject));
5869 hashmap_put(&subject2item, &entry->entry);
5873 if (rearranged) {
5874 for (i = 0; i < todo_list->nr; i++) {
5875 enum todo_command command = todo_list->items[i].command;
5876 int cur = i;
5879 * Initially, all commands are 'pick's. If it is a
5880 * fixup or a squash now, we have rearranged it.
5882 if (is_fixup(command))
5883 continue;
5885 while (cur >= 0) {
5886 ALLOC_GROW(items, nr + 1, alloc);
5887 items[nr++] = todo_list->items[cur];
5888 cur = next[cur];
5892 FREE_AND_NULL(todo_list->items);
5893 todo_list->items = items;
5894 todo_list->nr = nr;
5895 todo_list->alloc = alloc;
5898 free(next);
5899 free(tail);
5900 for (i = 0; i < todo_list->nr; i++)
5901 free(subjects[i]);
5902 free(subjects);
5903 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5905 clear_commit_todo_item(&commit_todo);
5907 return 0;
5910 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5912 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5913 struct object_id cherry_pick_head, rebase_head;
5915 if (file_exists(git_path_seq_dir()))
5916 *whence = FROM_CHERRY_PICK_MULTI;
5917 if (file_exists(rebase_path()) &&
5918 !get_oid("REBASE_HEAD", &rebase_head) &&
5919 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5920 oideq(&rebase_head, &cherry_pick_head))
5921 *whence = FROM_REBASE_PICK;
5922 else
5923 *whence = FROM_CHERRY_PICK_SINGLE;
5925 return 1;
5928 return 0;