l10n: vi(5211t): Translation for v2.34.0 rd3
[git.git] / sequencer.c
blobea96837cde3bad6faa9cf016323fe3267a538cb4
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 const char *argv[3];
1168 int code;
1169 struct strbuf sb = STRBUF_INIT;
1171 argv[0] = find_hook("post-rewrite");
1172 if (!argv[0])
1173 return 0;
1175 argv[1] = "amend";
1176 argv[2] = NULL;
1178 proc.argv = argv;
1179 proc.in = -1;
1180 proc.stdout_to_stderr = 1;
1181 proc.trace2_hook_name = "post-rewrite";
1183 code = start_command(&proc);
1184 if (code)
1185 return code;
1186 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1187 sigchain_push(SIGPIPE, SIG_IGN);
1188 write_in_full(proc.in, sb.buf, sb.len);
1189 close(proc.in);
1190 strbuf_release(&sb);
1191 sigchain_pop(SIGPIPE);
1192 return finish_command(&proc);
1195 void commit_post_rewrite(struct repository *r,
1196 const struct commit *old_head,
1197 const struct object_id *new_head)
1199 struct notes_rewrite_cfg *cfg;
1201 cfg = init_copy_notes_for_rewrite("amend");
1202 if (cfg) {
1203 /* we are amending, so old_head is not NULL */
1204 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1205 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1207 run_rewrite_hook(&old_head->object.oid, new_head);
1210 static int run_prepare_commit_msg_hook(struct repository *r,
1211 struct strbuf *msg,
1212 const char *commit)
1214 int ret = 0;
1215 const char *name, *arg1 = NULL, *arg2 = NULL;
1217 name = git_path_commit_editmsg();
1218 if (write_message(msg->buf, msg->len, name, 0))
1219 return -1;
1221 if (commit) {
1222 arg1 = "commit";
1223 arg2 = commit;
1224 } else {
1225 arg1 = "message";
1227 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1228 arg1, arg2, NULL))
1229 ret = error(_("'prepare-commit-msg' hook failed"));
1231 return ret;
1234 static const char implicit_ident_advice_noconfig[] =
1235 N_("Your name and email address were configured automatically based\n"
1236 "on your username and hostname. Please check that they are accurate.\n"
1237 "You can suppress this message by setting them explicitly. Run the\n"
1238 "following command and follow the instructions in your editor to edit\n"
1239 "your configuration file:\n"
1240 "\n"
1241 " git config --global --edit\n"
1242 "\n"
1243 "After doing this, you may fix the identity used for this commit with:\n"
1244 "\n"
1245 " git commit --amend --reset-author\n");
1247 static const char implicit_ident_advice_config[] =
1248 N_("Your name and email address were configured automatically based\n"
1249 "on your username and hostname. Please check that they are accurate.\n"
1250 "You can suppress this message by setting them explicitly:\n"
1251 "\n"
1252 " git config --global user.name \"Your Name\"\n"
1253 " git config --global user.email you@example.com\n"
1254 "\n"
1255 "After doing this, you may fix the identity used for this commit with:\n"
1256 "\n"
1257 " git commit --amend --reset-author\n");
1259 static const char *implicit_ident_advice(void)
1261 char *user_config = interpolate_path("~/.gitconfig", 0);
1262 char *xdg_config = xdg_config_home("config");
1263 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1265 free(user_config);
1266 free(xdg_config);
1268 if (config_exists)
1269 return _(implicit_ident_advice_config);
1270 else
1271 return _(implicit_ident_advice_noconfig);
1275 void print_commit_summary(struct repository *r,
1276 const char *prefix,
1277 const struct object_id *oid,
1278 unsigned int flags)
1280 struct rev_info rev;
1281 struct commit *commit;
1282 struct strbuf format = STRBUF_INIT;
1283 const char *head;
1284 struct pretty_print_context pctx = {0};
1285 struct strbuf author_ident = STRBUF_INIT;
1286 struct strbuf committer_ident = STRBUF_INIT;
1288 commit = lookup_commit(r, oid);
1289 if (!commit)
1290 die(_("couldn't look up newly created commit"));
1291 if (parse_commit(commit))
1292 die(_("could not parse newly created commit"));
1294 strbuf_addstr(&format, "format:%h] %s");
1296 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1297 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1298 if (strbuf_cmp(&author_ident, &committer_ident)) {
1299 strbuf_addstr(&format, "\n Author: ");
1300 strbuf_addbuf_percentquote(&format, &author_ident);
1302 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1303 struct strbuf date = STRBUF_INIT;
1305 format_commit_message(commit, "%ad", &date, &pctx);
1306 strbuf_addstr(&format, "\n Date: ");
1307 strbuf_addbuf_percentquote(&format, &date);
1308 strbuf_release(&date);
1310 if (!committer_ident_sufficiently_given()) {
1311 strbuf_addstr(&format, "\n Committer: ");
1312 strbuf_addbuf_percentquote(&format, &committer_ident);
1313 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1314 strbuf_addch(&format, '\n');
1315 strbuf_addstr(&format, implicit_ident_advice());
1318 strbuf_release(&author_ident);
1319 strbuf_release(&committer_ident);
1321 repo_init_revisions(r, &rev, prefix);
1322 setup_revisions(0, NULL, &rev, NULL);
1324 rev.diff = 1;
1325 rev.diffopt.output_format =
1326 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1328 rev.verbose_header = 1;
1329 rev.show_root_diff = 1;
1330 get_commit_format(format.buf, &rev);
1331 rev.always_show_header = 0;
1332 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1333 rev.diffopt.break_opt = 0;
1334 diff_setup_done(&rev.diffopt);
1336 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1337 if (!head)
1338 die_errno(_("unable to resolve HEAD after creating commit"));
1339 if (!strcmp(head, "HEAD"))
1340 head = _("detached HEAD");
1341 else
1342 skip_prefix(head, "refs/heads/", &head);
1343 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1344 _(" (root-commit)") : "");
1346 if (!log_tree_commit(&rev, commit)) {
1347 rev.always_show_header = 1;
1348 rev.use_terminator = 1;
1349 log_tree_commit(&rev, commit);
1352 strbuf_release(&format);
1355 static int parse_head(struct repository *r, struct commit **head)
1357 struct commit *current_head;
1358 struct object_id oid;
1360 if (get_oid("HEAD", &oid)) {
1361 current_head = NULL;
1362 } else {
1363 current_head = lookup_commit_reference(r, &oid);
1364 if (!current_head)
1365 return error(_("could not parse HEAD"));
1366 if (!oideq(&oid, &current_head->object.oid)) {
1367 warning(_("HEAD %s is not a commit!"),
1368 oid_to_hex(&oid));
1370 if (parse_commit(current_head))
1371 return error(_("could not parse HEAD commit"));
1373 *head = current_head;
1375 return 0;
1379 * Try to commit without forking 'git commit'. In some cases we need
1380 * to run 'git commit' to display an error message
1382 * Returns:
1383 * -1 - error unable to commit
1384 * 0 - success
1385 * 1 - run 'git commit'
1387 static int try_to_commit(struct repository *r,
1388 struct strbuf *msg, const char *author,
1389 struct replay_opts *opts, unsigned int flags,
1390 struct object_id *oid)
1392 struct object_id tree;
1393 struct commit *current_head = NULL;
1394 struct commit_list *parents = NULL;
1395 struct commit_extra_header *extra = NULL;
1396 struct strbuf err = STRBUF_INIT;
1397 struct strbuf commit_msg = STRBUF_INIT;
1398 char *amend_author = NULL;
1399 const char *committer = NULL;
1400 const char *hook_commit = NULL;
1401 enum commit_msg_cleanup_mode cleanup;
1402 int res = 0;
1404 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1405 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1407 if (parse_head(r, &current_head))
1408 return -1;
1410 if (flags & AMEND_MSG) {
1411 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1412 const char *out_enc = get_commit_output_encoding();
1413 const char *message = logmsg_reencode(current_head, NULL,
1414 out_enc);
1416 if (!msg) {
1417 const char *orig_message = NULL;
1419 find_commit_subject(message, &orig_message);
1420 msg = &commit_msg;
1421 strbuf_addstr(msg, orig_message);
1422 hook_commit = "HEAD";
1424 author = amend_author = get_author(message);
1425 unuse_commit_buffer(current_head, message);
1426 if (!author) {
1427 res = error(_("unable to parse commit author"));
1428 goto out;
1430 parents = copy_commit_list(current_head->parents);
1431 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1432 } else if (current_head &&
1433 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1434 commit_list_insert(current_head, &parents);
1437 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1438 res = error(_("git write-tree failed to write a tree"));
1439 goto out;
1442 if (!(flags & ALLOW_EMPTY)) {
1443 struct commit *first_parent = current_head;
1445 if (flags & AMEND_MSG) {
1446 if (current_head->parents) {
1447 first_parent = current_head->parents->item;
1448 if (repo_parse_commit(r, first_parent)) {
1449 res = error(_("could not parse HEAD commit"));
1450 goto out;
1452 } else {
1453 first_parent = NULL;
1456 if (oideq(first_parent
1457 ? get_commit_tree_oid(first_parent)
1458 : the_hash_algo->empty_tree,
1459 &tree)) {
1460 res = 1; /* run 'git commit' to display error message */
1461 goto out;
1465 if (hook_exists("prepare-commit-msg")) {
1466 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1467 if (res)
1468 goto out;
1469 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1470 2048) < 0) {
1471 res = error_errno(_("unable to read commit message "
1472 "from '%s'"),
1473 git_path_commit_editmsg());
1474 goto out;
1476 msg = &commit_msg;
1479 if (flags & CLEANUP_MSG)
1480 cleanup = COMMIT_MSG_CLEANUP_ALL;
1481 else if (flags & VERBATIM_MSG)
1482 cleanup = COMMIT_MSG_CLEANUP_NONE;
1483 else if ((opts->signoff || opts->record_origin) &&
1484 !opts->explicit_cleanup)
1485 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1486 else
1487 cleanup = opts->default_msg_cleanup;
1489 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1490 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1491 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1492 res = 1; /* run 'git commit' to display error message */
1493 goto out;
1496 if (opts->committer_date_is_author_date) {
1497 struct ident_split id;
1498 struct strbuf date = STRBUF_INIT;
1500 if (!opts->ignore_date) {
1501 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1502 res = error(_("invalid author identity '%s'"),
1503 author);
1504 goto out;
1506 if (!id.date_begin) {
1507 res = error(_(
1508 "corrupt author: missing date information"));
1509 goto out;
1511 strbuf_addf(&date, "@%.*s %.*s",
1512 (int)(id.date_end - id.date_begin),
1513 id.date_begin,
1514 (int)(id.tz_end - id.tz_begin),
1515 id.tz_begin);
1516 } else {
1517 reset_ident_date();
1519 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1520 getenv("GIT_COMMITTER_EMAIL"),
1521 WANT_COMMITTER_IDENT,
1522 opts->ignore_date ? NULL : date.buf,
1523 IDENT_STRICT);
1524 strbuf_release(&date);
1525 } else {
1526 reset_ident_date();
1529 if (opts->ignore_date) {
1530 struct ident_split id;
1531 char *name, *email;
1533 if (split_ident_line(&id, author, strlen(author)) < 0) {
1534 error(_("invalid author identity '%s'"), author);
1535 goto out;
1537 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1538 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1539 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1540 IDENT_STRICT);
1541 free(name);
1542 free(email);
1545 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1546 author, committer, opts->gpg_sign, extra)) {
1547 res = error(_("failed to write commit object"));
1548 goto out;
1551 if (update_head_with_reflog(current_head, oid,
1552 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1553 res = error("%s", err.buf);
1554 goto out;
1557 run_commit_hook(0, r->index_file, "post-commit", NULL);
1558 if (flags & AMEND_MSG)
1559 commit_post_rewrite(r, current_head, oid);
1561 out:
1562 free_commit_extra_headers(extra);
1563 strbuf_release(&err);
1564 strbuf_release(&commit_msg);
1565 free(amend_author);
1567 return res;
1570 static int write_rebase_head(struct object_id *oid)
1572 if (update_ref("rebase", "REBASE_HEAD", oid,
1573 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1574 return error(_("could not update %s"), "REBASE_HEAD");
1576 return 0;
1579 static int do_commit(struct repository *r,
1580 const char *msg_file, const char *author,
1581 struct replay_opts *opts, unsigned int flags,
1582 struct object_id *oid)
1584 int res = 1;
1586 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1587 struct object_id oid;
1588 struct strbuf sb = STRBUF_INIT;
1590 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1591 return error_errno(_("unable to read commit message "
1592 "from '%s'"),
1593 msg_file);
1595 res = try_to_commit(r, msg_file ? &sb : NULL,
1596 author, opts, flags, &oid);
1597 strbuf_release(&sb);
1598 if (!res) {
1599 refs_delete_ref(get_main_ref_store(r), "",
1600 "CHERRY_PICK_HEAD", NULL, 0);
1601 unlink(git_path_merge_msg(r));
1602 if (!is_rebase_i(opts))
1603 print_commit_summary(r, NULL, &oid,
1604 SUMMARY_SHOW_AUTHOR_DATE);
1605 return res;
1608 if (res == 1) {
1609 if (is_rebase_i(opts) && oid)
1610 if (write_rebase_head(oid))
1611 return -1;
1612 return run_git_commit(msg_file, opts, flags);
1615 return res;
1618 static int is_original_commit_empty(struct commit *commit)
1620 const struct object_id *ptree_oid;
1622 if (parse_commit(commit))
1623 return error(_("could not parse commit %s"),
1624 oid_to_hex(&commit->object.oid));
1625 if (commit->parents) {
1626 struct commit *parent = commit->parents->item;
1627 if (parse_commit(parent))
1628 return error(_("could not parse parent commit %s"),
1629 oid_to_hex(&parent->object.oid));
1630 ptree_oid = get_commit_tree_oid(parent);
1631 } else {
1632 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1635 return oideq(ptree_oid, get_commit_tree_oid(commit));
1639 * Should empty commits be allowed? Return status:
1640 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1641 * 0: Halt on empty commit
1642 * 1: Allow empty commit
1643 * 2: Drop empty commit
1645 static int allow_empty(struct repository *r,
1646 struct replay_opts *opts,
1647 struct commit *commit)
1649 int index_unchanged, originally_empty;
1652 * Four cases:
1654 * (1) we do not allow empty at all and error out.
1656 * (2) we allow ones that were initially empty, and
1657 * just drop the ones that become empty
1659 * (3) we allow ones that were initially empty, but
1660 * halt for the ones that become empty;
1662 * (4) we allow both.
1664 if (!opts->allow_empty)
1665 return 0; /* let "git commit" barf as necessary */
1667 index_unchanged = is_index_unchanged(r);
1668 if (index_unchanged < 0)
1669 return index_unchanged;
1670 if (!index_unchanged)
1671 return 0; /* we do not have to say --allow-empty */
1673 if (opts->keep_redundant_commits)
1674 return 1;
1676 originally_empty = is_original_commit_empty(commit);
1677 if (originally_empty < 0)
1678 return originally_empty;
1679 if (originally_empty)
1680 return 1;
1681 else if (opts->drop_redundant_commits)
1682 return 2;
1683 else
1684 return 0;
1687 static struct {
1688 char c;
1689 const char *str;
1690 } todo_command_info[] = {
1691 { 'p', "pick" },
1692 { 0, "revert" },
1693 { 'e', "edit" },
1694 { 'r', "reword" },
1695 { 'f', "fixup" },
1696 { 's', "squash" },
1697 { 'x', "exec" },
1698 { 'b', "break" },
1699 { 'l', "label" },
1700 { 't', "reset" },
1701 { 'm', "merge" },
1702 { 0, "noop" },
1703 { 'd', "drop" },
1704 { 0, NULL }
1707 static const char *command_to_string(const enum todo_command command)
1709 if (command < TODO_COMMENT)
1710 return todo_command_info[command].str;
1711 die(_("unknown command: %d"), command);
1714 static char command_to_char(const enum todo_command command)
1716 if (command < TODO_COMMENT)
1717 return todo_command_info[command].c;
1718 return comment_line_char;
1721 static int is_noop(const enum todo_command command)
1723 return TODO_NOOP <= command;
1726 static int is_fixup(enum todo_command command)
1728 return command == TODO_FIXUP || command == TODO_SQUASH;
1731 /* Does this command create a (non-merge) commit? */
1732 static int is_pick_or_similar(enum todo_command command)
1734 switch (command) {
1735 case TODO_PICK:
1736 case TODO_REVERT:
1737 case TODO_EDIT:
1738 case TODO_REWORD:
1739 case TODO_FIXUP:
1740 case TODO_SQUASH:
1741 return 1;
1742 default:
1743 return 0;
1747 enum todo_item_flags {
1748 TODO_EDIT_MERGE_MSG = (1 << 0),
1749 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1750 TODO_EDIT_FIXUP_MSG = (1 << 2),
1753 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1754 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1755 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1756 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1757 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1759 static int is_fixup_flag(enum todo_command command, unsigned flag)
1761 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1762 (flag & TODO_EDIT_FIXUP_MSG));
1766 * Wrapper around strbuf_add_commented_lines() which avoids double
1767 * commenting commit subjects.
1769 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1771 const char *s = str;
1772 while (len > 0 && s[0] == comment_line_char) {
1773 size_t count;
1774 const char *n = memchr(s, '\n', len);
1775 if (!n)
1776 count = len;
1777 else
1778 count = n - s + 1;
1779 strbuf_add(buf, s, count);
1780 s += count;
1781 len -= count;
1783 strbuf_add_commented_lines(buf, s, len);
1786 /* Does the current fixup chain contain a squash command? */
1787 static int seen_squash(struct replay_opts *opts)
1789 return starts_with(opts->current_fixups.buf, "squash") ||
1790 strstr(opts->current_fixups.buf, "\nsquash");
1793 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1795 strbuf_setlen(buf1, 2);
1796 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1797 strbuf_addch(buf1, '\n');
1798 strbuf_setlen(buf2, 2);
1799 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1800 strbuf_addch(buf2, '\n');
1804 * Comment out any un-commented commit messages, updating the message comments
1805 * to say they will be skipped but do not comment out the empty lines that
1806 * surround commit messages and their comments.
1808 static void update_squash_message_for_fixup(struct strbuf *msg)
1810 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1811 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1812 const char *s, *start;
1813 char *orig_msg;
1814 size_t orig_msg_len;
1815 int i = 1;
1817 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1818 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1819 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1820 while (s) {
1821 const char *next;
1822 size_t off;
1823 if (skip_prefix(s, buf1.buf, &next)) {
1825 * Copy the last message, preserving the blank line
1826 * preceding the current line
1828 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1829 copy_lines(msg, start, s - start - off);
1830 if (off)
1831 strbuf_addch(msg, '\n');
1833 * The next message needs to be commented out but the
1834 * message header is already commented out so just copy
1835 * it and the blank line that follows it.
1837 strbuf_addbuf(msg, &buf2);
1838 if (*next == '\n')
1839 strbuf_addch(msg, *next++);
1840 start = s = next;
1841 copy_lines = add_commented_lines;
1842 update_comment_bufs(&buf1, &buf2, ++i);
1843 } else if (skip_prefix(s, buf2.buf, &next)) {
1844 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1845 copy_lines(msg, start, s - start - off);
1846 start = s - off;
1847 s = next;
1848 copy_lines = strbuf_add;
1849 update_comment_bufs(&buf1, &buf2, ++i);
1850 } else {
1851 s = strchr(s, '\n');
1852 if (s)
1853 s++;
1856 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1857 free(orig_msg);
1858 strbuf_release(&buf1);
1859 strbuf_release(&buf2);
1862 static int append_squash_message(struct strbuf *buf, const char *body,
1863 enum todo_command command, struct replay_opts *opts,
1864 unsigned flag)
1866 const char *fixup_msg;
1867 size_t commented_len = 0, fixup_off;
1869 * amend is non-interactive and not normally used with fixup!
1870 * or squash! commits, so only comment out those subjects when
1871 * squashing commit messages.
1873 if (starts_with(body, "amend!") ||
1874 ((command == TODO_SQUASH || seen_squash(opts)) &&
1875 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1876 commented_len = commit_subject_length(body);
1878 strbuf_addf(buf, "\n%c ", comment_line_char);
1879 strbuf_addf(buf, _(nth_commit_msg_fmt),
1880 ++opts->current_fixup_count + 1);
1881 strbuf_addstr(buf, "\n\n");
1882 strbuf_add_commented_lines(buf, body, commented_len);
1883 /* buf->buf may be reallocated so store an offset into the buffer */
1884 fixup_off = buf->len;
1885 strbuf_addstr(buf, body + commented_len);
1887 /* fixup -C after squash behaves like squash */
1888 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1890 * We're replacing the commit message so we need to
1891 * append the Signed-off-by: trailer if the user
1892 * requested '--signoff'.
1894 if (opts->signoff)
1895 append_signoff(buf, 0, 0);
1897 if ((command == TODO_FIXUP) &&
1898 (flag & TODO_REPLACE_FIXUP_MSG) &&
1899 (file_exists(rebase_path_fixup_msg()) ||
1900 !file_exists(rebase_path_squash_msg()))) {
1901 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1902 if (write_message(fixup_msg, strlen(fixup_msg),
1903 rebase_path_fixup_msg(), 0) < 0)
1904 return error(_("cannot write '%s'"),
1905 rebase_path_fixup_msg());
1906 } else {
1907 unlink(rebase_path_fixup_msg());
1909 } else {
1910 unlink(rebase_path_fixup_msg());
1913 return 0;
1916 static int update_squash_messages(struct repository *r,
1917 enum todo_command command,
1918 struct commit *commit,
1919 struct replay_opts *opts,
1920 unsigned flag)
1922 struct strbuf buf = STRBUF_INIT;
1923 int res = 0;
1924 const char *message, *body;
1925 const char *encoding = get_commit_output_encoding();
1927 if (opts->current_fixup_count > 0) {
1928 struct strbuf header = STRBUF_INIT;
1929 char *eol;
1931 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1932 return error(_("could not read '%s'"),
1933 rebase_path_squash_msg());
1935 eol = buf.buf[0] != comment_line_char ?
1936 buf.buf : strchrnul(buf.buf, '\n');
1938 strbuf_addf(&header, "%c ", comment_line_char);
1939 strbuf_addf(&header, _(combined_commit_msg_fmt),
1940 opts->current_fixup_count + 2);
1941 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1942 strbuf_release(&header);
1943 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1944 update_squash_message_for_fixup(&buf);
1945 } else {
1946 struct object_id head;
1947 struct commit *head_commit;
1948 const char *head_message, *body;
1950 if (get_oid("HEAD", &head))
1951 return error(_("need a HEAD to fixup"));
1952 if (!(head_commit = lookup_commit_reference(r, &head)))
1953 return error(_("could not read HEAD"));
1954 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1955 return error(_("could not read HEAD's commit message"));
1957 find_commit_subject(head_message, &body);
1958 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1959 rebase_path_fixup_msg(), 0) < 0) {
1960 unuse_commit_buffer(head_commit, head_message);
1961 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1963 strbuf_addf(&buf, "%c ", comment_line_char);
1964 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1965 strbuf_addf(&buf, "\n%c ", comment_line_char);
1966 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1967 _(skip_first_commit_msg_str) :
1968 _(first_commit_msg_str));
1969 strbuf_addstr(&buf, "\n\n");
1970 if (is_fixup_flag(command, flag))
1971 strbuf_add_commented_lines(&buf, body, strlen(body));
1972 else
1973 strbuf_addstr(&buf, body);
1975 unuse_commit_buffer(head_commit, head_message);
1978 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1979 return error(_("could not read commit message of %s"),
1980 oid_to_hex(&commit->object.oid));
1981 find_commit_subject(message, &body);
1983 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1984 res = append_squash_message(&buf, body, command, opts, flag);
1985 } else if (command == TODO_FIXUP) {
1986 strbuf_addf(&buf, "\n%c ", comment_line_char);
1987 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1988 ++opts->current_fixup_count + 1);
1989 strbuf_addstr(&buf, "\n\n");
1990 strbuf_add_commented_lines(&buf, body, strlen(body));
1991 } else
1992 return error(_("unknown command: %d"), command);
1993 unuse_commit_buffer(commit, message);
1995 if (!res)
1996 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1998 strbuf_release(&buf);
2000 if (!res) {
2001 strbuf_addf(&opts->current_fixups, "%s%s %s",
2002 opts->current_fixups.len ? "\n" : "",
2003 command_to_string(command),
2004 oid_to_hex(&commit->object.oid));
2005 res = write_message(opts->current_fixups.buf,
2006 opts->current_fixups.len,
2007 rebase_path_current_fixups(), 0);
2010 return res;
2013 static void flush_rewritten_pending(void)
2015 struct strbuf buf = STRBUF_INIT;
2016 struct object_id newoid;
2017 FILE *out;
2019 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2020 !get_oid("HEAD", &newoid) &&
2021 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2022 char *bol = buf.buf, *eol;
2024 while (*bol) {
2025 eol = strchrnul(bol, '\n');
2026 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2027 bol, oid_to_hex(&newoid));
2028 if (!*eol)
2029 break;
2030 bol = eol + 1;
2032 fclose(out);
2033 unlink(rebase_path_rewritten_pending());
2035 strbuf_release(&buf);
2038 static void record_in_rewritten(struct object_id *oid,
2039 enum todo_command next_command)
2041 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2043 if (!out)
2044 return;
2046 fprintf(out, "%s\n", oid_to_hex(oid));
2047 fclose(out);
2049 if (!is_fixup(next_command))
2050 flush_rewritten_pending();
2053 static int should_edit(struct replay_opts *opts) {
2054 if (opts->edit < 0)
2056 * Note that we only handle the case of non-conflicted
2057 * commits; continue_single_pick() handles the conflicted
2058 * commits itself instead of calling this function.
2060 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2061 return opts->edit;
2064 static int do_pick_commit(struct repository *r,
2065 struct todo_item *item,
2066 struct replay_opts *opts,
2067 int final_fixup, int *check_todo)
2069 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2070 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2071 struct object_id head;
2072 struct commit *base, *next, *parent;
2073 const char *base_label, *next_label;
2074 char *author = NULL;
2075 struct commit_message msg = { NULL, NULL, NULL, NULL };
2076 struct strbuf msgbuf = STRBUF_INIT;
2077 int res, unborn = 0, reword = 0, allow, drop_commit;
2078 enum todo_command command = item->command;
2079 struct commit *commit = item->commit;
2081 if (opts->no_commit) {
2083 * We do not intend to commit immediately. We just want to
2084 * merge the differences in, so let's compute the tree
2085 * that represents the "current" state for the merge machinery
2086 * to work on.
2088 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2089 return error(_("your index file is unmerged."));
2090 } else {
2091 unborn = get_oid("HEAD", &head);
2092 /* Do we want to generate a root commit? */
2093 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2094 oideq(&head, &opts->squash_onto)) {
2095 if (is_fixup(command))
2096 return error(_("cannot fixup root commit"));
2097 flags |= CREATE_ROOT_COMMIT;
2098 unborn = 1;
2099 } else if (unborn)
2100 oidcpy(&head, the_hash_algo->empty_tree);
2101 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2102 NULL, 0))
2103 return error_dirty_index(r, opts);
2105 discard_index(r->index);
2107 if (!commit->parents)
2108 parent = NULL;
2109 else if (commit->parents->next) {
2110 /* Reverting or cherry-picking a merge commit */
2111 int cnt;
2112 struct commit_list *p;
2114 if (!opts->mainline)
2115 return error(_("commit %s is a merge but no -m option was given."),
2116 oid_to_hex(&commit->object.oid));
2118 for (cnt = 1, p = commit->parents;
2119 cnt != opts->mainline && p;
2120 cnt++)
2121 p = p->next;
2122 if (cnt != opts->mainline || !p)
2123 return error(_("commit %s does not have parent %d"),
2124 oid_to_hex(&commit->object.oid), opts->mainline);
2125 parent = p->item;
2126 } else if (1 < opts->mainline)
2128 * Non-first parent explicitly specified as mainline for
2129 * non-merge commit
2131 return error(_("commit %s does not have parent %d"),
2132 oid_to_hex(&commit->object.oid), opts->mainline);
2133 else
2134 parent = commit->parents->item;
2136 if (get_message(commit, &msg) != 0)
2137 return error(_("cannot get commit message for %s"),
2138 oid_to_hex(&commit->object.oid));
2140 if (opts->allow_ff && !is_fixup(command) &&
2141 ((parent && oideq(&parent->object.oid, &head)) ||
2142 (!parent && unborn))) {
2143 if (is_rebase_i(opts))
2144 write_author_script(msg.message);
2145 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2146 opts);
2147 if (res || command != TODO_REWORD)
2148 goto leave;
2149 reword = 1;
2150 msg_file = NULL;
2151 goto fast_forward_edit;
2153 if (parent && parse_commit(parent) < 0)
2154 /* TRANSLATORS: The first %s will be a "todo" command like
2155 "revert" or "pick", the second %s a SHA1. */
2156 return error(_("%s: cannot parse parent commit %s"),
2157 command_to_string(command),
2158 oid_to_hex(&parent->object.oid));
2161 * "commit" is an existing commit. We would want to apply
2162 * the difference it introduces since its first parent "prev"
2163 * on top of the current HEAD if we are cherry-pick. Or the
2164 * reverse of it if we are revert.
2167 if (command == TODO_REVERT) {
2168 base = commit;
2169 base_label = msg.label;
2170 next = parent;
2171 next_label = msg.parent_label;
2172 strbuf_addstr(&msgbuf, "Revert \"");
2173 strbuf_addstr(&msgbuf, msg.subject);
2174 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2175 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2177 if (commit->parents && commit->parents->next) {
2178 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2179 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2181 strbuf_addstr(&msgbuf, ".\n");
2182 } else {
2183 const char *p;
2185 base = parent;
2186 base_label = msg.parent_label;
2187 next = commit;
2188 next_label = msg.label;
2190 /* Append the commit log message to msgbuf. */
2191 if (find_commit_subject(msg.message, &p))
2192 strbuf_addstr(&msgbuf, p);
2194 if (opts->record_origin) {
2195 strbuf_complete_line(&msgbuf);
2196 if (!has_conforming_footer(&msgbuf, NULL, 0))
2197 strbuf_addch(&msgbuf, '\n');
2198 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2199 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2200 strbuf_addstr(&msgbuf, ")\n");
2202 if (!is_fixup(command))
2203 author = get_author(msg.message);
2206 if (command == TODO_REWORD)
2207 reword = 1;
2208 else if (is_fixup(command)) {
2209 if (update_squash_messages(r, command, commit,
2210 opts, item->flags))
2211 return -1;
2212 flags |= AMEND_MSG;
2213 if (!final_fixup)
2214 msg_file = rebase_path_squash_msg();
2215 else if (file_exists(rebase_path_fixup_msg())) {
2216 flags |= VERBATIM_MSG;
2217 msg_file = rebase_path_fixup_msg();
2218 } else {
2219 const char *dest = git_path_squash_msg(r);
2220 unlink(dest);
2221 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2222 return error(_("could not rename '%s' to '%s'"),
2223 rebase_path_squash_msg(), dest);
2224 unlink(git_path_merge_msg(r));
2225 msg_file = dest;
2226 flags |= EDIT_MSG;
2230 if (opts->signoff && !is_fixup(command))
2231 append_signoff(&msgbuf, 0, 0);
2233 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2234 res = -1;
2235 else if (!opts->strategy ||
2236 !strcmp(opts->strategy, "recursive") ||
2237 !strcmp(opts->strategy, "ort") ||
2238 command == TODO_REVERT) {
2239 res = do_recursive_merge(r, base, next, base_label, next_label,
2240 &head, &msgbuf, opts);
2241 if (res < 0)
2242 goto leave;
2244 res |= write_message(msgbuf.buf, msgbuf.len,
2245 git_path_merge_msg(r), 0);
2246 } else {
2247 struct commit_list *common = NULL;
2248 struct commit_list *remotes = NULL;
2250 res = write_message(msgbuf.buf, msgbuf.len,
2251 git_path_merge_msg(r), 0);
2253 commit_list_insert(base, &common);
2254 commit_list_insert(next, &remotes);
2255 res |= try_merge_command(r, opts->strategy,
2256 opts->xopts_nr, (const char **)opts->xopts,
2257 common, oid_to_hex(&head), remotes);
2258 free_commit_list(common);
2259 free_commit_list(remotes);
2261 strbuf_release(&msgbuf);
2264 * If the merge was clean or if it failed due to conflict, we write
2265 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2266 * However, if the merge did not even start, then we don't want to
2267 * write it at all.
2269 if ((command == TODO_PICK || command == TODO_REWORD ||
2270 command == TODO_EDIT) && !opts->no_commit &&
2271 (res == 0 || res == 1) &&
2272 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2273 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2274 res = -1;
2275 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2276 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2277 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2278 res = -1;
2280 if (res) {
2281 error(command == TODO_REVERT
2282 ? _("could not revert %s... %s")
2283 : _("could not apply %s... %s"),
2284 short_commit_name(commit), msg.subject);
2285 print_advice(r, res == 1, opts);
2286 repo_rerere(r, opts->allow_rerere_auto);
2287 goto leave;
2290 drop_commit = 0;
2291 allow = allow_empty(r, opts, commit);
2292 if (allow < 0) {
2293 res = allow;
2294 goto leave;
2295 } else if (allow == 1) {
2296 flags |= ALLOW_EMPTY;
2297 } else if (allow == 2) {
2298 drop_commit = 1;
2299 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2300 NULL, 0);
2301 unlink(git_path_merge_msg(r));
2302 unlink(git_path_auto_merge(r));
2303 fprintf(stderr,
2304 _("dropping %s %s -- patch contents already upstream\n"),
2305 oid_to_hex(&commit->object.oid), msg.subject);
2306 } /* else allow == 0 and there's nothing special to do */
2307 if (!opts->no_commit && !drop_commit) {
2308 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2309 res = do_commit(r, msg_file, author, opts, flags,
2310 commit? &commit->object.oid : NULL);
2311 else
2312 res = error(_("unable to parse commit author"));
2313 *check_todo = !!(flags & EDIT_MSG);
2314 if (!res && reword) {
2315 fast_forward_edit:
2316 res = run_git_commit(NULL, opts, EDIT_MSG |
2317 VERIFY_MSG | AMEND_MSG |
2318 (flags & ALLOW_EMPTY));
2319 *check_todo = 1;
2324 if (!res && final_fixup) {
2325 unlink(rebase_path_fixup_msg());
2326 unlink(rebase_path_squash_msg());
2327 unlink(rebase_path_current_fixups());
2328 strbuf_reset(&opts->current_fixups);
2329 opts->current_fixup_count = 0;
2332 leave:
2333 free_message(commit, &msg);
2334 free(author);
2335 update_abort_safety_file();
2337 return res;
2340 static int prepare_revs(struct replay_opts *opts)
2343 * picking (but not reverting) ranges (but not individual revisions)
2344 * should be done in reverse
2346 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2347 opts->revs->reverse ^= 1;
2349 if (prepare_revision_walk(opts->revs))
2350 return error(_("revision walk setup failed"));
2352 return 0;
2355 static int read_and_refresh_cache(struct repository *r,
2356 struct replay_opts *opts)
2358 struct lock_file index_lock = LOCK_INIT;
2359 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2360 if (repo_read_index(r) < 0) {
2361 rollback_lock_file(&index_lock);
2362 return error(_("git %s: failed to read the index"),
2363 _(action_name(opts)));
2365 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2367 if (index_fd >= 0) {
2368 if (write_locked_index(r->index, &index_lock,
2369 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2370 return error(_("git %s: failed to refresh the index"),
2371 _(action_name(opts)));
2376 * If we are resolving merges in any way other than "ort", then
2377 * expand the sparse index.
2379 if (opts->strategy && strcmp(opts->strategy, "ort"))
2380 ensure_full_index(r->index);
2381 return 0;
2384 void todo_list_release(struct todo_list *todo_list)
2386 strbuf_release(&todo_list->buf);
2387 FREE_AND_NULL(todo_list->items);
2388 todo_list->nr = todo_list->alloc = 0;
2391 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2393 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2394 todo_list->total_nr++;
2395 return todo_list->items + todo_list->nr++;
2398 const char *todo_item_get_arg(struct todo_list *todo_list,
2399 struct todo_item *item)
2401 return todo_list->buf.buf + item->arg_offset;
2404 static int is_command(enum todo_command command, const char **bol)
2406 const char *str = todo_command_info[command].str;
2407 const char nick = todo_command_info[command].c;
2408 const char *p = *bol + 1;
2410 return skip_prefix(*bol, str, bol) ||
2411 ((nick && **bol == nick) &&
2412 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2413 (*bol = p));
2416 static int parse_insn_line(struct repository *r, struct todo_item *item,
2417 const char *buf, const char *bol, char *eol)
2419 struct object_id commit_oid;
2420 char *end_of_object_name;
2421 int i, saved, status, padding;
2423 item->flags = 0;
2425 /* left-trim */
2426 bol += strspn(bol, " \t");
2428 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2429 item->command = TODO_COMMENT;
2430 item->commit = NULL;
2431 item->arg_offset = bol - buf;
2432 item->arg_len = eol - bol;
2433 return 0;
2436 for (i = 0; i < TODO_COMMENT; i++)
2437 if (is_command(i, &bol)) {
2438 item->command = i;
2439 break;
2441 if (i >= TODO_COMMENT)
2442 return -1;
2444 /* Eat up extra spaces/ tabs before object name */
2445 padding = strspn(bol, " \t");
2446 bol += padding;
2448 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2449 if (bol != eol)
2450 return error(_("%s does not accept arguments: '%s'"),
2451 command_to_string(item->command), bol);
2452 item->commit = NULL;
2453 item->arg_offset = bol - buf;
2454 item->arg_len = eol - bol;
2455 return 0;
2458 if (!padding)
2459 return error(_("missing arguments for %s"),
2460 command_to_string(item->command));
2462 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2463 item->command == TODO_RESET) {
2464 item->commit = NULL;
2465 item->arg_offset = bol - buf;
2466 item->arg_len = (int)(eol - bol);
2467 return 0;
2470 if (item->command == TODO_FIXUP) {
2471 if (skip_prefix(bol, "-C", &bol) &&
2472 (*bol == ' ' || *bol == '\t')) {
2473 bol += strspn(bol, " \t");
2474 item->flags |= TODO_REPLACE_FIXUP_MSG;
2475 } else if (skip_prefix(bol, "-c", &bol) &&
2476 (*bol == ' ' || *bol == '\t')) {
2477 bol += strspn(bol, " \t");
2478 item->flags |= TODO_EDIT_FIXUP_MSG;
2482 if (item->command == TODO_MERGE) {
2483 if (skip_prefix(bol, "-C", &bol))
2484 bol += strspn(bol, " \t");
2485 else if (skip_prefix(bol, "-c", &bol)) {
2486 bol += strspn(bol, " \t");
2487 item->flags |= TODO_EDIT_MERGE_MSG;
2488 } else {
2489 item->flags |= TODO_EDIT_MERGE_MSG;
2490 item->commit = NULL;
2491 item->arg_offset = bol - buf;
2492 item->arg_len = (int)(eol - bol);
2493 return 0;
2497 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2498 saved = *end_of_object_name;
2499 *end_of_object_name = '\0';
2500 status = get_oid(bol, &commit_oid);
2501 if (status < 0)
2502 error(_("could not parse '%s'"), bol); /* return later */
2503 *end_of_object_name = saved;
2505 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2506 item->arg_offset = bol - buf;
2507 item->arg_len = (int)(eol - bol);
2509 if (status < 0)
2510 return status;
2512 item->commit = lookup_commit_reference(r, &commit_oid);
2513 return item->commit ? 0 : -1;
2516 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2518 const char *todo_file, *bol;
2519 struct strbuf buf = STRBUF_INIT;
2520 int ret = 0;
2522 todo_file = git_path_todo_file();
2523 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2524 if (errno == ENOENT || errno == ENOTDIR)
2525 return -1;
2526 else
2527 return error_errno("unable to open '%s'", todo_file);
2529 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2530 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2531 *action = REPLAY_PICK;
2532 else if (is_command(TODO_REVERT, &bol) &&
2533 (*bol == ' ' || *bol == '\t'))
2534 *action = REPLAY_REVERT;
2535 else
2536 ret = -1;
2538 strbuf_release(&buf);
2540 return ret;
2543 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2544 struct todo_list *todo_list)
2546 struct todo_item *item;
2547 char *p = buf, *next_p;
2548 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2550 todo_list->current = todo_list->nr = 0;
2552 for (i = 1; *p; i++, p = next_p) {
2553 char *eol = strchrnul(p, '\n');
2555 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2557 if (p != eol && eol[-1] == '\r')
2558 eol--; /* strip Carriage Return */
2560 item = append_new_todo(todo_list);
2561 item->offset_in_buf = p - todo_list->buf.buf;
2562 if (parse_insn_line(r, item, buf, p, eol)) {
2563 res = error(_("invalid line %d: %.*s"),
2564 i, (int)(eol - p), p);
2565 item->command = TODO_COMMENT + 1;
2566 item->arg_offset = p - buf;
2567 item->arg_len = (int)(eol - p);
2568 item->commit = NULL;
2571 if (fixup_okay)
2572 ; /* do nothing */
2573 else if (is_fixup(item->command))
2574 return error(_("cannot '%s' without a previous commit"),
2575 command_to_string(item->command));
2576 else if (!is_noop(item->command))
2577 fixup_okay = 1;
2580 return res;
2583 static int count_commands(struct todo_list *todo_list)
2585 int count = 0, i;
2587 for (i = 0; i < todo_list->nr; i++)
2588 if (todo_list->items[i].command != TODO_COMMENT)
2589 count++;
2591 return count;
2594 static int get_item_line_offset(struct todo_list *todo_list, int index)
2596 return index < todo_list->nr ?
2597 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2600 static const char *get_item_line(struct todo_list *todo_list, int index)
2602 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2605 static int get_item_line_length(struct todo_list *todo_list, int index)
2607 return get_item_line_offset(todo_list, index + 1)
2608 - get_item_line_offset(todo_list, index);
2611 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2613 int fd;
2614 ssize_t len;
2616 fd = open(path, O_RDONLY);
2617 if (fd < 0)
2618 return error_errno(_("could not open '%s'"), path);
2619 len = strbuf_read(sb, fd, 0);
2620 close(fd);
2621 if (len < 0)
2622 return error(_("could not read '%s'."), path);
2623 return len;
2626 static int have_finished_the_last_pick(void)
2628 struct strbuf buf = STRBUF_INIT;
2629 const char *eol;
2630 const char *todo_path = git_path_todo_file();
2631 int ret = 0;
2633 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2634 if (errno == ENOENT) {
2635 return 0;
2636 } else {
2637 error_errno("unable to open '%s'", todo_path);
2638 return 0;
2641 /* If there is only one line then we are done */
2642 eol = strchr(buf.buf, '\n');
2643 if (!eol || !eol[1])
2644 ret = 1;
2646 strbuf_release(&buf);
2648 return ret;
2651 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2653 struct replay_opts opts = REPLAY_OPTS_INIT;
2654 int need_cleanup = 0;
2656 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2657 if (!refs_delete_ref(get_main_ref_store(r), "",
2658 "CHERRY_PICK_HEAD", NULL, 0) &&
2659 verbose)
2660 warning(_("cancelling a cherry picking in progress"));
2661 opts.action = REPLAY_PICK;
2662 need_cleanup = 1;
2665 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2666 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2667 NULL, 0) &&
2668 verbose)
2669 warning(_("cancelling a revert in progress"));
2670 opts.action = REPLAY_REVERT;
2671 need_cleanup = 1;
2674 unlink(git_path_auto_merge(r));
2676 if (!need_cleanup)
2677 return;
2679 if (!have_finished_the_last_pick())
2680 return;
2682 sequencer_remove_state(&opts);
2685 static void todo_list_write_total_nr(struct todo_list *todo_list)
2687 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2689 if (f) {
2690 fprintf(f, "%d\n", todo_list->total_nr);
2691 fclose(f);
2695 static int read_populate_todo(struct repository *r,
2696 struct todo_list *todo_list,
2697 struct replay_opts *opts)
2699 const char *todo_file = get_todo_path(opts);
2700 int res;
2702 strbuf_reset(&todo_list->buf);
2703 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2704 return -1;
2706 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2707 if (res) {
2708 if (is_rebase_i(opts))
2709 return error(_("please fix this using "
2710 "'git rebase --edit-todo'."));
2711 return error(_("unusable instruction sheet: '%s'"), todo_file);
2714 if (!todo_list->nr &&
2715 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2716 return error(_("no commits parsed."));
2718 if (!is_rebase_i(opts)) {
2719 enum todo_command valid =
2720 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2721 int i;
2723 for (i = 0; i < todo_list->nr; i++)
2724 if (valid == todo_list->items[i].command)
2725 continue;
2726 else if (valid == TODO_PICK)
2727 return error(_("cannot cherry-pick during a revert."));
2728 else
2729 return error(_("cannot revert during a cherry-pick."));
2732 if (is_rebase_i(opts)) {
2733 struct todo_list done = TODO_LIST_INIT;
2735 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2736 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2737 todo_list->done_nr = count_commands(&done);
2738 else
2739 todo_list->done_nr = 0;
2741 todo_list->total_nr = todo_list->done_nr
2742 + count_commands(todo_list);
2743 todo_list_release(&done);
2745 todo_list_write_total_nr(todo_list);
2748 return 0;
2751 static int git_config_string_dup(char **dest,
2752 const char *var, const char *value)
2754 if (!value)
2755 return config_error_nonbool(var);
2756 free(*dest);
2757 *dest = xstrdup(value);
2758 return 0;
2761 static int populate_opts_cb(const char *key, const char *value, void *data)
2763 struct replay_opts *opts = data;
2764 int error_flag = 1;
2766 if (!value)
2767 error_flag = 0;
2768 else if (!strcmp(key, "options.no-commit"))
2769 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2770 else if (!strcmp(key, "options.edit"))
2771 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2772 else if (!strcmp(key, "options.allow-empty"))
2773 opts->allow_empty =
2774 git_config_bool_or_int(key, value, &error_flag);
2775 else if (!strcmp(key, "options.allow-empty-message"))
2776 opts->allow_empty_message =
2777 git_config_bool_or_int(key, value, &error_flag);
2778 else if (!strcmp(key, "options.keep-redundant-commits"))
2779 opts->keep_redundant_commits =
2780 git_config_bool_or_int(key, value, &error_flag);
2781 else if (!strcmp(key, "options.signoff"))
2782 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2783 else if (!strcmp(key, "options.record-origin"))
2784 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2785 else if (!strcmp(key, "options.allow-ff"))
2786 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2787 else if (!strcmp(key, "options.mainline"))
2788 opts->mainline = git_config_int(key, value);
2789 else if (!strcmp(key, "options.strategy"))
2790 git_config_string_dup(&opts->strategy, key, value);
2791 else if (!strcmp(key, "options.gpg-sign"))
2792 git_config_string_dup(&opts->gpg_sign, key, value);
2793 else if (!strcmp(key, "options.strategy-option")) {
2794 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2795 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2796 } else if (!strcmp(key, "options.allow-rerere-auto"))
2797 opts->allow_rerere_auto =
2798 git_config_bool_or_int(key, value, &error_flag) ?
2799 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2800 else if (!strcmp(key, "options.default-msg-cleanup")) {
2801 opts->explicit_cleanup = 1;
2802 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2803 } else
2804 return error(_("invalid key: %s"), key);
2806 if (!error_flag)
2807 return error(_("invalid value for %s: %s"), key, value);
2809 return 0;
2812 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2814 int i;
2815 char *strategy_opts_string = raw_opts;
2817 if (*strategy_opts_string == ' ')
2818 strategy_opts_string++;
2820 opts->xopts_nr = split_cmdline(strategy_opts_string,
2821 (const char ***)&opts->xopts);
2822 for (i = 0; i < opts->xopts_nr; i++) {
2823 const char *arg = opts->xopts[i];
2825 skip_prefix(arg, "--", &arg);
2826 opts->xopts[i] = xstrdup(arg);
2830 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2832 strbuf_reset(buf);
2833 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2834 return;
2835 opts->strategy = strbuf_detach(buf, NULL);
2836 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2837 return;
2839 parse_strategy_opts(opts, buf->buf);
2842 static int read_populate_opts(struct replay_opts *opts)
2844 if (is_rebase_i(opts)) {
2845 struct strbuf buf = STRBUF_INIT;
2846 int ret = 0;
2848 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2849 READ_ONELINER_SKIP_IF_EMPTY)) {
2850 if (!starts_with(buf.buf, "-S"))
2851 strbuf_reset(&buf);
2852 else {
2853 free(opts->gpg_sign);
2854 opts->gpg_sign = xstrdup(buf.buf + 2);
2856 strbuf_reset(&buf);
2859 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2860 READ_ONELINER_SKIP_IF_EMPTY)) {
2861 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2862 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2863 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2864 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2865 strbuf_reset(&buf);
2868 if (file_exists(rebase_path_verbose()))
2869 opts->verbose = 1;
2871 if (file_exists(rebase_path_quiet()))
2872 opts->quiet = 1;
2874 if (file_exists(rebase_path_signoff())) {
2875 opts->allow_ff = 0;
2876 opts->signoff = 1;
2879 if (file_exists(rebase_path_cdate_is_adate())) {
2880 opts->allow_ff = 0;
2881 opts->committer_date_is_author_date = 1;
2884 if (file_exists(rebase_path_ignore_date())) {
2885 opts->allow_ff = 0;
2886 opts->ignore_date = 1;
2889 if (file_exists(rebase_path_reschedule_failed_exec()))
2890 opts->reschedule_failed_exec = 1;
2891 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2892 opts->reschedule_failed_exec = 0;
2894 if (file_exists(rebase_path_drop_redundant_commits()))
2895 opts->drop_redundant_commits = 1;
2897 if (file_exists(rebase_path_keep_redundant_commits()))
2898 opts->keep_redundant_commits = 1;
2900 read_strategy_opts(opts, &buf);
2901 strbuf_reset(&buf);
2903 if (read_oneliner(&opts->current_fixups,
2904 rebase_path_current_fixups(),
2905 READ_ONELINER_SKIP_IF_EMPTY)) {
2906 const char *p = opts->current_fixups.buf;
2907 opts->current_fixup_count = 1;
2908 while ((p = strchr(p, '\n'))) {
2909 opts->current_fixup_count++;
2910 p++;
2914 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2915 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2916 ret = error(_("unusable squash-onto"));
2917 goto done_rebase_i;
2919 opts->have_squash_onto = 1;
2922 done_rebase_i:
2923 strbuf_release(&buf);
2924 return ret;
2927 if (!file_exists(git_path_opts_file()))
2928 return 0;
2930 * The function git_parse_source(), called from git_config_from_file(),
2931 * may die() in case of a syntactically incorrect file. We do not care
2932 * about this case, though, because we wrote that file ourselves, so we
2933 * are pretty certain that it is syntactically correct.
2935 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2936 return error(_("malformed options sheet: '%s'"),
2937 git_path_opts_file());
2938 return 0;
2941 static void write_strategy_opts(struct replay_opts *opts)
2943 int i;
2944 struct strbuf buf = STRBUF_INIT;
2946 for (i = 0; i < opts->xopts_nr; ++i)
2947 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2949 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2950 strbuf_release(&buf);
2953 int write_basic_state(struct replay_opts *opts, const char *head_name,
2954 struct commit *onto, const struct object_id *orig_head)
2956 if (head_name)
2957 write_file(rebase_path_head_name(), "%s\n", head_name);
2958 if (onto)
2959 write_file(rebase_path_onto(), "%s\n",
2960 oid_to_hex(&onto->object.oid));
2961 if (orig_head)
2962 write_file(rebase_path_orig_head(), "%s\n",
2963 oid_to_hex(orig_head));
2965 if (opts->quiet)
2966 write_file(rebase_path_quiet(), "%s", "");
2967 if (opts->verbose)
2968 write_file(rebase_path_verbose(), "%s", "");
2969 if (opts->strategy)
2970 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2971 if (opts->xopts_nr > 0)
2972 write_strategy_opts(opts);
2974 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2975 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2976 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2977 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2979 if (opts->gpg_sign)
2980 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2981 if (opts->signoff)
2982 write_file(rebase_path_signoff(), "--signoff\n");
2983 if (opts->drop_redundant_commits)
2984 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2985 if (opts->keep_redundant_commits)
2986 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2987 if (opts->committer_date_is_author_date)
2988 write_file(rebase_path_cdate_is_adate(), "%s", "");
2989 if (opts->ignore_date)
2990 write_file(rebase_path_ignore_date(), "%s", "");
2991 if (opts->reschedule_failed_exec)
2992 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2993 else
2994 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2996 return 0;
2999 static int walk_revs_populate_todo(struct todo_list *todo_list,
3000 struct replay_opts *opts)
3002 enum todo_command command = opts->action == REPLAY_PICK ?
3003 TODO_PICK : TODO_REVERT;
3004 const char *command_string = todo_command_info[command].str;
3005 const char *encoding;
3006 struct commit *commit;
3008 if (prepare_revs(opts))
3009 return -1;
3011 encoding = get_log_output_encoding();
3013 while ((commit = get_revision(opts->revs))) {
3014 struct todo_item *item = append_new_todo(todo_list);
3015 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3016 const char *subject;
3017 int subject_len;
3019 item->command = command;
3020 item->commit = commit;
3021 item->arg_offset = 0;
3022 item->arg_len = 0;
3023 item->offset_in_buf = todo_list->buf.len;
3024 subject_len = find_commit_subject(commit_buffer, &subject);
3025 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3026 short_commit_name(commit), subject_len, subject);
3027 unuse_commit_buffer(commit, commit_buffer);
3030 if (!todo_list->nr)
3031 return error(_("empty commit set passed"));
3033 return 0;
3036 static int create_seq_dir(struct repository *r)
3038 enum replay_action action;
3039 const char *in_progress_error = NULL;
3040 const char *in_progress_advice = NULL;
3041 unsigned int advise_skip =
3042 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3043 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3045 if (!sequencer_get_last_command(r, &action)) {
3046 switch (action) {
3047 case REPLAY_REVERT:
3048 in_progress_error = _("revert is already in progress");
3049 in_progress_advice =
3050 _("try \"git revert (--continue | %s--abort | --quit)\"");
3051 break;
3052 case REPLAY_PICK:
3053 in_progress_error = _("cherry-pick is already in progress");
3054 in_progress_advice =
3055 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3056 break;
3057 default:
3058 BUG("unexpected action in create_seq_dir");
3061 if (in_progress_error) {
3062 error("%s", in_progress_error);
3063 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3064 advise(in_progress_advice,
3065 advise_skip ? "--skip | " : "");
3066 return -1;
3068 if (mkdir(git_path_seq_dir(), 0777) < 0)
3069 return error_errno(_("could not create sequencer directory '%s'"),
3070 git_path_seq_dir());
3072 return 0;
3075 static int save_head(const char *head)
3077 struct lock_file head_lock = LOCK_INIT;
3078 struct strbuf buf = STRBUF_INIT;
3079 int fd;
3080 ssize_t written;
3082 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3083 if (fd < 0)
3084 return error_errno(_("could not lock HEAD"));
3085 strbuf_addf(&buf, "%s\n", head);
3086 written = write_in_full(fd, buf.buf, buf.len);
3087 strbuf_release(&buf);
3088 if (written < 0) {
3089 error_errno(_("could not write to '%s'"), git_path_head_file());
3090 rollback_lock_file(&head_lock);
3091 return -1;
3093 if (commit_lock_file(&head_lock) < 0)
3094 return error(_("failed to finalize '%s'"), git_path_head_file());
3095 return 0;
3098 static int rollback_is_safe(void)
3100 struct strbuf sb = STRBUF_INIT;
3101 struct object_id expected_head, actual_head;
3103 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3104 strbuf_trim(&sb);
3105 if (get_oid_hex(sb.buf, &expected_head)) {
3106 strbuf_release(&sb);
3107 die(_("could not parse %s"), git_path_abort_safety_file());
3109 strbuf_release(&sb);
3111 else if (errno == ENOENT)
3112 oidclr(&expected_head);
3113 else
3114 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3116 if (get_oid("HEAD", &actual_head))
3117 oidclr(&actual_head);
3119 return oideq(&actual_head, &expected_head);
3122 static int reset_merge(const struct object_id *oid)
3124 int ret;
3125 struct strvec argv = STRVEC_INIT;
3127 strvec_pushl(&argv, "reset", "--merge", NULL);
3129 if (!is_null_oid(oid))
3130 strvec_push(&argv, oid_to_hex(oid));
3132 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3133 strvec_clear(&argv);
3135 return ret;
3138 static int rollback_single_pick(struct repository *r)
3140 struct object_id head_oid;
3142 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3143 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3144 return error(_("no cherry-pick or revert in progress"));
3145 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3146 return error(_("cannot resolve HEAD"));
3147 if (is_null_oid(&head_oid))
3148 return error(_("cannot abort from a branch yet to be born"));
3149 return reset_merge(&head_oid);
3152 static int skip_single_pick(void)
3154 struct object_id head;
3156 if (read_ref_full("HEAD", 0, &head, NULL))
3157 return error(_("cannot resolve HEAD"));
3158 return reset_merge(&head);
3161 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3163 FILE *f;
3164 struct object_id oid;
3165 struct strbuf buf = STRBUF_INIT;
3166 const char *p;
3168 f = fopen(git_path_head_file(), "r");
3169 if (!f && errno == ENOENT) {
3171 * There is no multiple-cherry-pick in progress.
3172 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3173 * a single-cherry-pick in progress, abort that.
3175 return rollback_single_pick(r);
3177 if (!f)
3178 return error_errno(_("cannot open '%s'"), git_path_head_file());
3179 if (strbuf_getline_lf(&buf, f)) {
3180 error(_("cannot read '%s': %s"), git_path_head_file(),
3181 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3182 fclose(f);
3183 goto fail;
3185 fclose(f);
3186 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3187 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3188 git_path_head_file());
3189 goto fail;
3191 if (is_null_oid(&oid)) {
3192 error(_("cannot abort from a branch yet to be born"));
3193 goto fail;
3196 if (!rollback_is_safe()) {
3197 /* Do not error, just do not rollback */
3198 warning(_("You seem to have moved HEAD. "
3199 "Not rewinding, check your HEAD!"));
3200 } else
3201 if (reset_merge(&oid))
3202 goto fail;
3203 strbuf_release(&buf);
3204 return sequencer_remove_state(opts);
3205 fail:
3206 strbuf_release(&buf);
3207 return -1;
3210 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3212 enum replay_action action = -1;
3213 sequencer_get_last_command(r, &action);
3216 * Check whether the subcommand requested to skip the commit is actually
3217 * in progress and that it's safe to skip the commit.
3219 * opts->action tells us which subcommand requested to skip the commit.
3220 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3221 * action is in progress and we can skip the commit.
3223 * Otherwise we check that the last instruction was related to the
3224 * particular subcommand we're trying to execute and barf if that's not
3225 * the case.
3227 * Finally we check that the rollback is "safe", i.e., has the HEAD
3228 * moved? In this case, it doesn't make sense to "reset the merge" and
3229 * "skip the commit" as the user already handled this by committing. But
3230 * we'd not want to barf here, instead give advice on how to proceed. We
3231 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3232 * it gets removed when the user commits, so if it still exists we're
3233 * sure the user can't have committed before.
3235 switch (opts->action) {
3236 case REPLAY_REVERT:
3237 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3238 if (action != REPLAY_REVERT)
3239 return error(_("no revert in progress"));
3240 if (!rollback_is_safe())
3241 goto give_advice;
3243 break;
3244 case REPLAY_PICK:
3245 if (!refs_ref_exists(get_main_ref_store(r),
3246 "CHERRY_PICK_HEAD")) {
3247 if (action != REPLAY_PICK)
3248 return error(_("no cherry-pick in progress"));
3249 if (!rollback_is_safe())
3250 goto give_advice;
3252 break;
3253 default:
3254 BUG("unexpected action in sequencer_skip");
3257 if (skip_single_pick())
3258 return error(_("failed to skip the commit"));
3259 if (!is_directory(git_path_seq_dir()))
3260 return 0;
3262 return sequencer_continue(r, opts);
3264 give_advice:
3265 error(_("there is nothing to skip"));
3267 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3268 advise(_("have you committed already?\n"
3269 "try \"git %s --continue\""),
3270 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3272 return -1;
3275 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3277 struct lock_file todo_lock = LOCK_INIT;
3278 const char *todo_path = get_todo_path(opts);
3279 int next = todo_list->current, offset, fd;
3282 * rebase -i writes "git-rebase-todo" without the currently executing
3283 * command, appending it to "done" instead.
3285 if (is_rebase_i(opts))
3286 next++;
3288 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3289 if (fd < 0)
3290 return error_errno(_("could not lock '%s'"), todo_path);
3291 offset = get_item_line_offset(todo_list, next);
3292 if (write_in_full(fd, todo_list->buf.buf + offset,
3293 todo_list->buf.len - offset) < 0)
3294 return error_errno(_("could not write to '%s'"), todo_path);
3295 if (commit_lock_file(&todo_lock) < 0)
3296 return error(_("failed to finalize '%s'"), todo_path);
3298 if (is_rebase_i(opts) && next > 0) {
3299 const char *done = rebase_path_done();
3300 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3301 int ret = 0;
3303 if (fd < 0)
3304 return 0;
3305 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3306 get_item_line_length(todo_list, next - 1))
3307 < 0)
3308 ret = error_errno(_("could not write to '%s'"), done);
3309 if (close(fd) < 0)
3310 ret = error_errno(_("failed to finalize '%s'"), done);
3311 return ret;
3313 return 0;
3316 static int save_opts(struct replay_opts *opts)
3318 const char *opts_file = git_path_opts_file();
3319 int res = 0;
3321 if (opts->no_commit)
3322 res |= git_config_set_in_file_gently(opts_file,
3323 "options.no-commit", "true");
3324 if (opts->edit >= 0)
3325 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3326 opts->edit ? "true" : "false");
3327 if (opts->allow_empty)
3328 res |= git_config_set_in_file_gently(opts_file,
3329 "options.allow-empty", "true");
3330 if (opts->allow_empty_message)
3331 res |= git_config_set_in_file_gently(opts_file,
3332 "options.allow-empty-message", "true");
3333 if (opts->keep_redundant_commits)
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.keep-redundant-commits", "true");
3336 if (opts->signoff)
3337 res |= git_config_set_in_file_gently(opts_file,
3338 "options.signoff", "true");
3339 if (opts->record_origin)
3340 res |= git_config_set_in_file_gently(opts_file,
3341 "options.record-origin", "true");
3342 if (opts->allow_ff)
3343 res |= git_config_set_in_file_gently(opts_file,
3344 "options.allow-ff", "true");
3345 if (opts->mainline) {
3346 struct strbuf buf = STRBUF_INIT;
3347 strbuf_addf(&buf, "%d", opts->mainline);
3348 res |= git_config_set_in_file_gently(opts_file,
3349 "options.mainline", buf.buf);
3350 strbuf_release(&buf);
3352 if (opts->strategy)
3353 res |= git_config_set_in_file_gently(opts_file,
3354 "options.strategy", opts->strategy);
3355 if (opts->gpg_sign)
3356 res |= git_config_set_in_file_gently(opts_file,
3357 "options.gpg-sign", opts->gpg_sign);
3358 if (opts->xopts) {
3359 int i;
3360 for (i = 0; i < opts->xopts_nr; i++)
3361 res |= git_config_set_multivar_in_file_gently(opts_file,
3362 "options.strategy-option",
3363 opts->xopts[i], "^$", 0);
3365 if (opts->allow_rerere_auto)
3366 res |= git_config_set_in_file_gently(opts_file,
3367 "options.allow-rerere-auto",
3368 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3369 "true" : "false");
3371 if (opts->explicit_cleanup)
3372 res |= git_config_set_in_file_gently(opts_file,
3373 "options.default-msg-cleanup",
3374 describe_cleanup_mode(opts->default_msg_cleanup));
3375 return res;
3378 static int make_patch(struct repository *r,
3379 struct commit *commit,
3380 struct replay_opts *opts)
3382 struct strbuf buf = STRBUF_INIT;
3383 struct rev_info log_tree_opt;
3384 const char *subject;
3385 char hex[GIT_MAX_HEXSZ + 1];
3386 int res = 0;
3388 oid_to_hex_r(hex, &commit->object.oid);
3389 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3390 return -1;
3391 res |= write_rebase_head(&commit->object.oid);
3393 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3394 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3395 repo_init_revisions(r, &log_tree_opt, NULL);
3396 log_tree_opt.abbrev = 0;
3397 log_tree_opt.diff = 1;
3398 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3399 log_tree_opt.disable_stdin = 1;
3400 log_tree_opt.no_commit_id = 1;
3401 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3402 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3403 if (!log_tree_opt.diffopt.file)
3404 res |= error_errno(_("could not open '%s'"), buf.buf);
3405 else {
3406 res |= log_tree_commit(&log_tree_opt, commit);
3407 fclose(log_tree_opt.diffopt.file);
3409 strbuf_reset(&buf);
3411 strbuf_addf(&buf, "%s/message", get_dir(opts));
3412 if (!file_exists(buf.buf)) {
3413 const char *encoding = get_commit_output_encoding();
3414 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3415 find_commit_subject(commit_buffer, &subject);
3416 res |= write_message(subject, strlen(subject), buf.buf, 1);
3417 unuse_commit_buffer(commit, commit_buffer);
3419 strbuf_release(&buf);
3421 return res;
3424 static int intend_to_amend(void)
3426 struct object_id head;
3427 char *p;
3429 if (get_oid("HEAD", &head))
3430 return error(_("cannot read HEAD"));
3432 p = oid_to_hex(&head);
3433 return write_message(p, strlen(p), rebase_path_amend(), 1);
3436 static int error_with_patch(struct repository *r,
3437 struct commit *commit,
3438 const char *subject, int subject_len,
3439 struct replay_opts *opts,
3440 int exit_code, int to_amend)
3442 if (commit) {
3443 if (make_patch(r, commit, opts))
3444 return -1;
3445 } else if (copy_file(rebase_path_message(),
3446 git_path_merge_msg(r), 0666))
3447 return error(_("unable to copy '%s' to '%s'"),
3448 git_path_merge_msg(r), rebase_path_message());
3450 if (to_amend) {
3451 if (intend_to_amend())
3452 return -1;
3454 fprintf(stderr,
3455 _("You can amend the commit now, with\n"
3456 "\n"
3457 " git commit --amend %s\n"
3458 "\n"
3459 "Once you are satisfied with your changes, run\n"
3460 "\n"
3461 " git rebase --continue\n"),
3462 gpg_sign_opt_quoted(opts));
3463 } else if (exit_code) {
3464 if (commit)
3465 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3466 short_commit_name(commit), subject_len, subject);
3467 else
3469 * We don't have the hash of the parent so
3470 * just print the line from the todo file.
3472 fprintf_ln(stderr, _("Could not merge %.*s"),
3473 subject_len, subject);
3476 return exit_code;
3479 static int error_failed_squash(struct repository *r,
3480 struct commit *commit,
3481 struct replay_opts *opts,
3482 int subject_len,
3483 const char *subject)
3485 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3486 return error(_("could not copy '%s' to '%s'"),
3487 rebase_path_squash_msg(), rebase_path_message());
3488 unlink(git_path_merge_msg(r));
3489 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3490 return error(_("could not copy '%s' to '%s'"),
3491 rebase_path_message(),
3492 git_path_merge_msg(r));
3493 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3496 static int do_exec(struct repository *r, const char *command_line)
3498 struct strvec child_env = STRVEC_INIT;
3499 const char *child_argv[] = { NULL, NULL };
3500 int dirty, status;
3502 fprintf(stderr, _("Executing: %s\n"), command_line);
3503 child_argv[0] = command_line;
3504 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3505 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3506 absolute_path(get_git_work_tree()));
3507 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3508 child_env.v);
3510 /* force re-reading of the cache */
3511 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3512 return error(_("could not read index"));
3514 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3516 if (status) {
3517 warning(_("execution failed: %s\n%s"
3518 "You can fix the problem, and then run\n"
3519 "\n"
3520 " git rebase --continue\n"
3521 "\n"),
3522 command_line,
3523 dirty ? N_("and made changes to the index and/or the "
3524 "working tree\n") : "");
3525 if (status == 127)
3526 /* command not found */
3527 status = 1;
3528 } else if (dirty) {
3529 warning(_("execution succeeded: %s\nbut "
3530 "left changes to the index and/or the working tree\n"
3531 "Commit or stash your changes, and then run\n"
3532 "\n"
3533 " git rebase --continue\n"
3534 "\n"), command_line);
3535 status = 1;
3538 strvec_clear(&child_env);
3540 return status;
3543 __attribute__((format (printf, 2, 3)))
3544 static int safe_append(const char *filename, const char *fmt, ...)
3546 va_list ap;
3547 struct lock_file lock = LOCK_INIT;
3548 int fd = hold_lock_file_for_update(&lock, filename,
3549 LOCK_REPORT_ON_ERROR);
3550 struct strbuf buf = STRBUF_INIT;
3552 if (fd < 0)
3553 return -1;
3555 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3556 error_errno(_("could not read '%s'"), filename);
3557 rollback_lock_file(&lock);
3558 return -1;
3560 strbuf_complete(&buf, '\n');
3561 va_start(ap, fmt);
3562 strbuf_vaddf(&buf, fmt, ap);
3563 va_end(ap);
3565 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3566 error_errno(_("could not write to '%s'"), filename);
3567 strbuf_release(&buf);
3568 rollback_lock_file(&lock);
3569 return -1;
3571 if (commit_lock_file(&lock) < 0) {
3572 strbuf_release(&buf);
3573 rollback_lock_file(&lock);
3574 return error(_("failed to finalize '%s'"), filename);
3577 strbuf_release(&buf);
3578 return 0;
3581 static int do_label(struct repository *r, const char *name, int len)
3583 struct ref_store *refs = get_main_ref_store(r);
3584 struct ref_transaction *transaction;
3585 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3586 struct strbuf msg = STRBUF_INIT;
3587 int ret = 0;
3588 struct object_id head_oid;
3590 if (len == 1 && *name == '#')
3591 return error(_("illegal label name: '%.*s'"), len, name);
3593 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3594 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3596 transaction = ref_store_transaction_begin(refs, &err);
3597 if (!transaction) {
3598 error("%s", err.buf);
3599 ret = -1;
3600 } else if (get_oid("HEAD", &head_oid)) {
3601 error(_("could not read HEAD"));
3602 ret = -1;
3603 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3604 NULL, 0, msg.buf, &err) < 0 ||
3605 ref_transaction_commit(transaction, &err)) {
3606 error("%s", err.buf);
3607 ret = -1;
3609 ref_transaction_free(transaction);
3610 strbuf_release(&err);
3611 strbuf_release(&msg);
3613 if (!ret)
3614 ret = safe_append(rebase_path_refs_to_delete(),
3615 "%s\n", ref_name.buf);
3616 strbuf_release(&ref_name);
3618 return ret;
3621 __attribute__((format (printf, 3, 4)))
3622 static const char *reflog_message(struct replay_opts *opts,
3623 const char *sub_action, const char *fmt, ...)
3625 va_list ap;
3626 static struct strbuf buf = STRBUF_INIT;
3627 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3629 va_start(ap, fmt);
3630 strbuf_reset(&buf);
3631 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3632 if (sub_action)
3633 strbuf_addf(&buf, " (%s)", sub_action);
3634 if (fmt) {
3635 strbuf_addstr(&buf, ": ");
3636 strbuf_vaddf(&buf, fmt, ap);
3638 va_end(ap);
3640 return buf.buf;
3643 static int do_reset(struct repository *r,
3644 const char *name, int len,
3645 struct replay_opts *opts)
3647 struct strbuf ref_name = STRBUF_INIT;
3648 struct object_id oid;
3649 struct lock_file lock = LOCK_INIT;
3650 struct tree_desc desc = { 0 };
3651 struct tree *tree;
3652 struct unpack_trees_options unpack_tree_opts = { 0 };
3653 int ret = 0;
3655 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3656 return -1;
3658 if (len == 10 && !strncmp("[new root]", name, len)) {
3659 if (!opts->have_squash_onto) {
3660 const char *hex;
3661 if (commit_tree("", 0, the_hash_algo->empty_tree,
3662 NULL, &opts->squash_onto,
3663 NULL, NULL))
3664 return error(_("writing fake root commit"));
3665 opts->have_squash_onto = 1;
3666 hex = oid_to_hex(&opts->squash_onto);
3667 if (write_message(hex, strlen(hex),
3668 rebase_path_squash_onto(), 0))
3669 return error(_("writing squash-onto"));
3671 oidcpy(&oid, &opts->squash_onto);
3672 } else {
3673 int i;
3675 /* Determine the length of the label */
3676 for (i = 0; i < len; i++)
3677 if (isspace(name[i]))
3678 break;
3679 len = i;
3681 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3682 if (get_oid(ref_name.buf, &oid) &&
3683 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3684 ret = error(_("could not read '%s'"), ref_name.buf);
3685 goto cleanup;
3689 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3690 unpack_tree_opts.head_idx = 1;
3691 unpack_tree_opts.src_index = r->index;
3692 unpack_tree_opts.dst_index = r->index;
3693 unpack_tree_opts.fn = oneway_merge;
3694 unpack_tree_opts.merge = 1;
3695 unpack_tree_opts.update = 1;
3696 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3697 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3699 if (repo_read_index_unmerged(r)) {
3700 ret = error_resolve_conflict(_(action_name(opts)));
3701 goto cleanup;
3704 if (!fill_tree_descriptor(r, &desc, &oid)) {
3705 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3706 goto cleanup;
3709 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3710 ret = -1;
3711 goto cleanup;
3714 tree = parse_tree_indirect(&oid);
3715 prime_cache_tree(r, r->index, tree);
3717 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3718 ret = error(_("could not write index"));
3720 if (!ret)
3721 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3722 len, name), "HEAD", &oid,
3723 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3724 cleanup:
3725 free((void *)desc.buffer);
3726 if (ret < 0)
3727 rollback_lock_file(&lock);
3728 strbuf_release(&ref_name);
3729 clear_unpack_trees_porcelain(&unpack_tree_opts);
3730 return ret;
3733 static struct commit *lookup_label(const char *label, int len,
3734 struct strbuf *buf)
3736 struct commit *commit;
3738 strbuf_reset(buf);
3739 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3740 commit = lookup_commit_reference_by_name(buf->buf);
3741 if (!commit) {
3742 /* fall back to non-rewritten ref or commit */
3743 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3744 commit = lookup_commit_reference_by_name(buf->buf);
3747 if (!commit)
3748 error(_("could not resolve '%s'"), buf->buf);
3750 return commit;
3753 static int do_merge(struct repository *r,
3754 struct commit *commit,
3755 const char *arg, int arg_len,
3756 int flags, int *check_todo, struct replay_opts *opts)
3758 int run_commit_flags = 0;
3759 struct strbuf ref_name = STRBUF_INIT;
3760 struct commit *head_commit, *merge_commit, *i;
3761 struct commit_list *bases, *j, *reversed = NULL;
3762 struct commit_list *to_merge = NULL, **tail = &to_merge;
3763 const char *strategy = !opts->xopts_nr &&
3764 (!opts->strategy ||
3765 !strcmp(opts->strategy, "recursive") ||
3766 !strcmp(opts->strategy, "ort")) ?
3767 NULL : opts->strategy;
3768 struct merge_options o;
3769 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3770 static struct lock_file lock;
3771 const char *p;
3773 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3774 ret = -1;
3775 goto leave_merge;
3778 head_commit = lookup_commit_reference_by_name("HEAD");
3779 if (!head_commit) {
3780 ret = error(_("cannot merge without a current revision"));
3781 goto leave_merge;
3785 * For octopus merges, the arg starts with the list of revisions to be
3786 * merged. The list is optionally followed by '#' and the oneline.
3788 merge_arg_len = oneline_offset = arg_len;
3789 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3790 if (!*p)
3791 break;
3792 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3793 p += 1 + strspn(p + 1, " \t\n");
3794 oneline_offset = p - arg;
3795 break;
3797 k = strcspn(p, " \t\n");
3798 if (!k)
3799 continue;
3800 merge_commit = lookup_label(p, k, &ref_name);
3801 if (!merge_commit) {
3802 ret = error(_("unable to parse '%.*s'"), k, p);
3803 goto leave_merge;
3805 tail = &commit_list_insert(merge_commit, tail)->next;
3806 p += k;
3807 merge_arg_len = p - arg;
3810 if (!to_merge) {
3811 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3812 goto leave_merge;
3815 if (opts->have_squash_onto &&
3816 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3818 * When the user tells us to "merge" something into a
3819 * "[new root]", let's simply fast-forward to the merge head.
3821 rollback_lock_file(&lock);
3822 if (to_merge->next)
3823 ret = error(_("octopus merge cannot be executed on "
3824 "top of a [new root]"));
3825 else
3826 ret = fast_forward_to(r, &to_merge->item->object.oid,
3827 &head_commit->object.oid, 0,
3828 opts);
3829 goto leave_merge;
3833 * If HEAD is not identical to the first parent of the original merge
3834 * commit, we cannot fast-forward.
3836 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3837 oideq(&commit->parents->item->object.oid,
3838 &head_commit->object.oid);
3841 * If any merge head is different from the original one, we cannot
3842 * fast-forward.
3844 if (can_fast_forward) {
3845 struct commit_list *p = commit->parents->next;
3847 for (j = to_merge; j && p; j = j->next, p = p->next)
3848 if (!oideq(&j->item->object.oid,
3849 &p->item->object.oid)) {
3850 can_fast_forward = 0;
3851 break;
3854 * If the number of merge heads differs from the original merge
3855 * commit, we cannot fast-forward.
3857 if (j || p)
3858 can_fast_forward = 0;
3861 if (can_fast_forward) {
3862 rollback_lock_file(&lock);
3863 ret = fast_forward_to(r, &commit->object.oid,
3864 &head_commit->object.oid, 0, opts);
3865 if (flags & TODO_EDIT_MERGE_MSG)
3866 goto fast_forward_edit;
3868 goto leave_merge;
3871 if (commit) {
3872 const char *encoding = get_commit_output_encoding();
3873 const char *message = logmsg_reencode(commit, NULL, encoding);
3874 const char *body;
3875 int len;
3877 if (!message) {
3878 ret = error(_("could not get commit message of '%s'"),
3879 oid_to_hex(&commit->object.oid));
3880 goto leave_merge;
3882 write_author_script(message);
3883 find_commit_subject(message, &body);
3884 len = strlen(body);
3885 ret = write_message(body, len, git_path_merge_msg(r), 0);
3886 unuse_commit_buffer(commit, message);
3887 if (ret) {
3888 error_errno(_("could not write '%s'"),
3889 git_path_merge_msg(r));
3890 goto leave_merge;
3892 } else {
3893 struct strbuf buf = STRBUF_INIT;
3894 int len;
3896 strbuf_addf(&buf, "author %s", git_author_info(0));
3897 write_author_script(buf.buf);
3898 strbuf_reset(&buf);
3900 if (oneline_offset < arg_len) {
3901 p = arg + oneline_offset;
3902 len = arg_len - oneline_offset;
3903 } else {
3904 strbuf_addf(&buf, "Merge %s '%.*s'",
3905 to_merge->next ? "branches" : "branch",
3906 merge_arg_len, arg);
3907 p = buf.buf;
3908 len = buf.len;
3911 ret = write_message(p, len, git_path_merge_msg(r), 0);
3912 strbuf_release(&buf);
3913 if (ret) {
3914 error_errno(_("could not write '%s'"),
3915 git_path_merge_msg(r));
3916 goto leave_merge;
3920 if (strategy || to_merge->next) {
3921 /* Octopus merge */
3922 struct child_process cmd = CHILD_PROCESS_INIT;
3924 if (read_env_script(&cmd.env_array)) {
3925 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3927 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3928 goto leave_merge;
3931 if (opts->committer_date_is_author_date)
3932 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3933 opts->ignore_date ?
3934 "" :
3935 author_date_from_env_array(&cmd.env_array));
3936 if (opts->ignore_date)
3937 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3939 cmd.git_cmd = 1;
3940 strvec_push(&cmd.args, "merge");
3941 strvec_push(&cmd.args, "-s");
3942 if (!strategy)
3943 strvec_push(&cmd.args, "octopus");
3944 else {
3945 strvec_push(&cmd.args, strategy);
3946 for (k = 0; k < opts->xopts_nr; k++)
3947 strvec_pushf(&cmd.args,
3948 "-X%s", opts->xopts[k]);
3950 if (!(flags & TODO_EDIT_MERGE_MSG))
3951 strvec_push(&cmd.args, "--no-edit");
3952 else
3953 strvec_push(&cmd.args, "--edit");
3954 strvec_push(&cmd.args, "--no-ff");
3955 strvec_push(&cmd.args, "--no-log");
3956 strvec_push(&cmd.args, "--no-stat");
3957 strvec_push(&cmd.args, "-F");
3958 strvec_push(&cmd.args, git_path_merge_msg(r));
3959 if (opts->gpg_sign)
3960 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3961 else
3962 strvec_push(&cmd.args, "--no-gpg-sign");
3964 /* Add the tips to be merged */
3965 for (j = to_merge; j; j = j->next)
3966 strvec_push(&cmd.args,
3967 oid_to_hex(&j->item->object.oid));
3969 strbuf_release(&ref_name);
3970 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3971 NULL, 0);
3972 rollback_lock_file(&lock);
3974 ret = run_command(&cmd);
3976 /* force re-reading of the cache */
3977 if (!ret && (discard_index(r->index) < 0 ||
3978 repo_read_index(r) < 0))
3979 ret = error(_("could not read index"));
3980 goto leave_merge;
3983 merge_commit = to_merge->item;
3984 bases = get_merge_bases(head_commit, merge_commit);
3985 if (bases && oideq(&merge_commit->object.oid,
3986 &bases->item->object.oid)) {
3987 ret = 0;
3988 /* skip merging an ancestor of HEAD */
3989 goto leave_merge;
3992 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3993 git_path_merge_head(r), 0);
3994 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3996 for (j = bases; j; j = j->next)
3997 commit_list_insert(j->item, &reversed);
3998 free_commit_list(bases);
4000 repo_read_index(r);
4001 init_merge_options(&o, r);
4002 o.branch1 = "HEAD";
4003 o.branch2 = ref_name.buf;
4004 o.buffer_output = 2;
4006 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4008 * TODO: Should use merge_incore_recursive() and
4009 * merge_switch_to_result(), skipping the call to
4010 * merge_switch_to_result() when we don't actually need to
4011 * update the index and working copy immediately.
4013 ret = merge_ort_recursive(&o,
4014 head_commit, merge_commit, reversed,
4015 &i);
4016 } else {
4017 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4018 &i);
4020 if (ret <= 0)
4021 fputs(o.obuf.buf, stdout);
4022 strbuf_release(&o.obuf);
4023 if (ret < 0) {
4024 error(_("could not even attempt to merge '%.*s'"),
4025 merge_arg_len, arg);
4026 goto leave_merge;
4029 * The return value of merge_recursive() is 1 on clean, and 0 on
4030 * unclean merge.
4032 * Let's reverse that, so that do_merge() returns 0 upon success and
4033 * 1 upon failed merge (keeping the return value -1 for the cases where
4034 * we will want to reschedule the `merge` command).
4036 ret = !ret;
4038 if (r->index->cache_changed &&
4039 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4040 ret = error(_("merge: Unable to write new index file"));
4041 goto leave_merge;
4044 rollback_lock_file(&lock);
4045 if (ret)
4046 repo_rerere(r, opts->allow_rerere_auto);
4047 else
4049 * In case of problems, we now want to return a positive
4050 * value (a negative one would indicate that the `merge`
4051 * command needs to be rescheduled).
4053 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4054 run_commit_flags);
4056 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4057 fast_forward_edit:
4058 *check_todo = 1;
4059 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4060 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4064 leave_merge:
4065 strbuf_release(&ref_name);
4066 rollback_lock_file(&lock);
4067 free_commit_list(to_merge);
4068 return ret;
4071 static int is_final_fixup(struct todo_list *todo_list)
4073 int i = todo_list->current;
4075 if (!is_fixup(todo_list->items[i].command))
4076 return 0;
4078 while (++i < todo_list->nr)
4079 if (is_fixup(todo_list->items[i].command))
4080 return 0;
4081 else if (!is_noop(todo_list->items[i].command))
4082 break;
4083 return 1;
4086 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4088 int i;
4090 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4091 if (!is_noop(todo_list->items[i].command))
4092 return todo_list->items[i].command;
4094 return -1;
4097 void create_autostash(struct repository *r, const char *path,
4098 const char *default_reflog_action)
4100 struct strbuf buf = STRBUF_INIT;
4101 struct lock_file lock_file = LOCK_INIT;
4102 int fd;
4104 fd = repo_hold_locked_index(r, &lock_file, 0);
4105 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4106 if (0 <= fd)
4107 repo_update_index_if_able(r, &lock_file);
4108 rollback_lock_file(&lock_file);
4110 if (has_unstaged_changes(r, 1) ||
4111 has_uncommitted_changes(r, 1)) {
4112 struct child_process stash = CHILD_PROCESS_INIT;
4113 struct object_id oid;
4115 strvec_pushl(&stash.args,
4116 "stash", "create", "autostash", NULL);
4117 stash.git_cmd = 1;
4118 stash.no_stdin = 1;
4119 strbuf_reset(&buf);
4120 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4121 die(_("Cannot autostash"));
4122 strbuf_trim_trailing_newline(&buf);
4123 if (get_oid(buf.buf, &oid))
4124 die(_("Unexpected stash response: '%s'"),
4125 buf.buf);
4126 strbuf_reset(&buf);
4127 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4129 if (safe_create_leading_directories_const(path))
4130 die(_("Could not create directory for '%s'"),
4131 path);
4132 write_file(path, "%s", oid_to_hex(&oid));
4133 printf(_("Created autostash: %s\n"), buf.buf);
4134 if (reset_head(r, NULL, "reset --hard",
4135 NULL, RESET_HEAD_HARD, NULL, NULL,
4136 default_reflog_action) < 0)
4137 die(_("could not reset --hard"));
4139 if (discard_index(r->index) < 0 ||
4140 repo_read_index(r) < 0)
4141 die(_("could not read index"));
4143 strbuf_release(&buf);
4146 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4148 struct child_process child = CHILD_PROCESS_INIT;
4149 int ret = 0;
4151 if (attempt_apply) {
4152 child.git_cmd = 1;
4153 child.no_stdout = 1;
4154 child.no_stderr = 1;
4155 strvec_push(&child.args, "stash");
4156 strvec_push(&child.args, "apply");
4157 strvec_push(&child.args, stash_oid);
4158 ret = run_command(&child);
4161 if (attempt_apply && !ret)
4162 fprintf(stderr, _("Applied autostash.\n"));
4163 else {
4164 struct child_process store = CHILD_PROCESS_INIT;
4166 store.git_cmd = 1;
4167 strvec_push(&store.args, "stash");
4168 strvec_push(&store.args, "store");
4169 strvec_push(&store.args, "-m");
4170 strvec_push(&store.args, "autostash");
4171 strvec_push(&store.args, "-q");
4172 strvec_push(&store.args, stash_oid);
4173 if (run_command(&store))
4174 ret = error(_("cannot store %s"), stash_oid);
4175 else
4176 fprintf(stderr,
4177 _("%s\n"
4178 "Your changes are safe in the stash.\n"
4179 "You can run \"git stash pop\" or"
4180 " \"git stash drop\" at any time.\n"),
4181 attempt_apply ?
4182 _("Applying autostash resulted in conflicts.") :
4183 _("Autostash exists; creating a new stash entry."));
4186 return ret;
4189 static int apply_save_autostash(const char *path, int attempt_apply)
4191 struct strbuf stash_oid = STRBUF_INIT;
4192 int ret = 0;
4194 if (!read_oneliner(&stash_oid, path,
4195 READ_ONELINER_SKIP_IF_EMPTY)) {
4196 strbuf_release(&stash_oid);
4197 return 0;
4199 strbuf_trim(&stash_oid);
4201 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4203 unlink(path);
4204 strbuf_release(&stash_oid);
4205 return ret;
4208 int save_autostash(const char *path)
4210 return apply_save_autostash(path, 0);
4213 int apply_autostash(const char *path)
4215 return apply_save_autostash(path, 1);
4218 int apply_autostash_oid(const char *stash_oid)
4220 return apply_save_autostash_oid(stash_oid, 1);
4223 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4224 const char *commit, const char *action)
4226 struct child_process cmd = CHILD_PROCESS_INIT;
4227 int ret;
4229 cmd.git_cmd = 1;
4231 strvec_push(&cmd.args, "checkout");
4232 strvec_push(&cmd.args, commit);
4233 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4235 if (opts->verbose)
4236 ret = run_command(&cmd);
4237 else
4238 ret = run_command_silent_on_success(&cmd);
4240 if (!ret)
4241 discard_index(r->index);
4243 return ret;
4246 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4247 const char *onto_name, const struct object_id *onto,
4248 const struct object_id *orig_head)
4250 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4252 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4253 apply_autostash(rebase_path_autostash());
4254 sequencer_remove_state(opts);
4255 return error(_("could not detach HEAD"));
4258 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4261 static int stopped_at_head(struct repository *r)
4263 struct object_id head;
4264 struct commit *commit;
4265 struct commit_message message;
4267 if (get_oid("HEAD", &head) ||
4268 !(commit = lookup_commit(r, &head)) ||
4269 parse_commit(commit) || get_message(commit, &message))
4270 fprintf(stderr, _("Stopped at HEAD\n"));
4271 else {
4272 fprintf(stderr, _("Stopped at %s\n"), message.label);
4273 free_message(commit, &message);
4275 return 0;
4279 static int reread_todo_if_changed(struct repository *r,
4280 struct todo_list *todo_list,
4281 struct replay_opts *opts)
4283 int offset;
4284 struct strbuf buf = STRBUF_INIT;
4286 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4287 return -1;
4288 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4289 if (buf.len != todo_list->buf.len - offset ||
4290 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4291 /* Reread the todo file if it has changed. */
4292 todo_list_release(todo_list);
4293 if (read_populate_todo(r, todo_list, opts))
4294 return -1; /* message was printed */
4295 /* `current` will be incremented on return */
4296 todo_list->current = -1;
4298 strbuf_release(&buf);
4300 return 0;
4303 static const char rescheduled_advice[] =
4304 N_("Could not execute the todo command\n"
4305 "\n"
4306 " %.*s"
4307 "\n"
4308 "It has been rescheduled; To edit the command before continuing, please\n"
4309 "edit the todo list first:\n"
4310 "\n"
4311 " git rebase --edit-todo\n"
4312 " git rebase --continue\n");
4314 static int pick_commits(struct repository *r,
4315 struct todo_list *todo_list,
4316 struct replay_opts *opts)
4318 int res = 0, reschedule = 0;
4319 char *prev_reflog_action;
4321 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4322 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4323 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4324 if (opts->allow_ff)
4325 assert(!(opts->signoff || opts->no_commit ||
4326 opts->record_origin || should_edit(opts) ||
4327 opts->committer_date_is_author_date ||
4328 opts->ignore_date));
4329 if (read_and_refresh_cache(r, opts))
4330 return -1;
4332 while (todo_list->current < todo_list->nr) {
4333 struct todo_item *item = todo_list->items + todo_list->current;
4334 const char *arg = todo_item_get_arg(todo_list, item);
4335 int check_todo = 0;
4337 if (save_todo(todo_list, opts))
4338 return -1;
4339 if (is_rebase_i(opts)) {
4340 if (item->command != TODO_COMMENT) {
4341 FILE *f = fopen(rebase_path_msgnum(), "w");
4343 todo_list->done_nr++;
4345 if (f) {
4346 fprintf(f, "%d\n", todo_list->done_nr);
4347 fclose(f);
4349 if (!opts->quiet)
4350 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4351 todo_list->done_nr,
4352 todo_list->total_nr,
4353 opts->verbose ? "\n" : "\r");
4355 unlink(rebase_path_message());
4356 unlink(rebase_path_author_script());
4357 unlink(rebase_path_stopped_sha());
4358 unlink(rebase_path_amend());
4359 unlink(git_path_merge_head(r));
4360 unlink(git_path_auto_merge(r));
4361 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4363 if (item->command == TODO_BREAK) {
4364 if (!opts->verbose)
4365 term_clear_line();
4366 return stopped_at_head(r);
4369 if (item->command <= TODO_SQUASH) {
4370 if (is_rebase_i(opts))
4371 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4372 command_to_string(item->command), NULL),
4374 res = do_pick_commit(r, item, opts,
4375 is_final_fixup(todo_list),
4376 &check_todo);
4377 if (is_rebase_i(opts))
4378 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4379 if (is_rebase_i(opts) && res < 0) {
4380 /* Reschedule */
4381 advise(_(rescheduled_advice),
4382 get_item_line_length(todo_list,
4383 todo_list->current),
4384 get_item_line(todo_list,
4385 todo_list->current));
4386 todo_list->current--;
4387 if (save_todo(todo_list, opts))
4388 return -1;
4390 if (item->command == TODO_EDIT) {
4391 struct commit *commit = item->commit;
4392 if (!res) {
4393 if (!opts->verbose)
4394 term_clear_line();
4395 fprintf(stderr,
4396 _("Stopped at %s... %.*s\n"),
4397 short_commit_name(commit),
4398 item->arg_len, arg);
4400 return error_with_patch(r, commit,
4401 arg, item->arg_len, opts, res, !res);
4403 if (is_rebase_i(opts) && !res)
4404 record_in_rewritten(&item->commit->object.oid,
4405 peek_command(todo_list, 1));
4406 if (res && is_fixup(item->command)) {
4407 if (res == 1)
4408 intend_to_amend();
4409 return error_failed_squash(r, item->commit, opts,
4410 item->arg_len, arg);
4411 } else if (res && is_rebase_i(opts) && item->commit) {
4412 int to_amend = 0;
4413 struct object_id oid;
4416 * If we are rewording and have either
4417 * fast-forwarded already, or are about to
4418 * create a new root commit, we want to amend,
4419 * otherwise we do not.
4421 if (item->command == TODO_REWORD &&
4422 !get_oid("HEAD", &oid) &&
4423 (oideq(&item->commit->object.oid, &oid) ||
4424 (opts->have_squash_onto &&
4425 oideq(&opts->squash_onto, &oid))))
4426 to_amend = 1;
4428 return res | error_with_patch(r, item->commit,
4429 arg, item->arg_len, opts,
4430 res, to_amend);
4432 } else if (item->command == TODO_EXEC) {
4433 char *end_of_arg = (char *)(arg + item->arg_len);
4434 int saved = *end_of_arg;
4436 if (!opts->verbose)
4437 term_clear_line();
4438 *end_of_arg = '\0';
4439 res = do_exec(r, arg);
4440 *end_of_arg = saved;
4442 if (res) {
4443 if (opts->reschedule_failed_exec)
4444 reschedule = 1;
4446 check_todo = 1;
4447 } else if (item->command == TODO_LABEL) {
4448 if ((res = do_label(r, arg, item->arg_len)))
4449 reschedule = 1;
4450 } else if (item->command == TODO_RESET) {
4451 if ((res = do_reset(r, arg, item->arg_len, opts)))
4452 reschedule = 1;
4453 } else if (item->command == TODO_MERGE) {
4454 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4455 item->flags, &check_todo, opts)) < 0)
4456 reschedule = 1;
4457 else if (item->commit)
4458 record_in_rewritten(&item->commit->object.oid,
4459 peek_command(todo_list, 1));
4460 if (res > 0)
4461 /* failed with merge conflicts */
4462 return error_with_patch(r, item->commit,
4463 arg, item->arg_len,
4464 opts, res, 0);
4465 } else if (!is_noop(item->command))
4466 return error(_("unknown command %d"), item->command);
4468 if (reschedule) {
4469 advise(_(rescheduled_advice),
4470 get_item_line_length(todo_list,
4471 todo_list->current),
4472 get_item_line(todo_list, todo_list->current));
4473 todo_list->current--;
4474 if (save_todo(todo_list, opts))
4475 return -1;
4476 if (item->commit)
4477 return error_with_patch(r,
4478 item->commit,
4479 arg, item->arg_len,
4480 opts, res, 0);
4481 } else if (is_rebase_i(opts) && check_todo && !res &&
4482 reread_todo_if_changed(r, todo_list, opts)) {
4483 return -1;
4486 todo_list->current++;
4487 if (res)
4488 return res;
4491 if (is_rebase_i(opts)) {
4492 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4493 struct stat st;
4495 /* Stopped in the middle, as planned? */
4496 if (todo_list->current < todo_list->nr)
4497 return 0;
4499 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4500 starts_with(head_ref.buf, "refs/")) {
4501 const char *msg;
4502 struct object_id head, orig;
4503 int res;
4505 if (get_oid("HEAD", &head)) {
4506 res = error(_("cannot read HEAD"));
4507 cleanup_head_ref:
4508 strbuf_release(&head_ref);
4509 strbuf_release(&buf);
4510 return res;
4512 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4513 get_oid_hex(buf.buf, &orig)) {
4514 res = error(_("could not read orig-head"));
4515 goto cleanup_head_ref;
4517 strbuf_reset(&buf);
4518 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4519 res = error(_("could not read 'onto'"));
4520 goto cleanup_head_ref;
4522 msg = reflog_message(opts, "finish", "%s onto %s",
4523 head_ref.buf, buf.buf);
4524 if (update_ref(msg, head_ref.buf, &head, &orig,
4525 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4526 res = error(_("could not update %s"),
4527 head_ref.buf);
4528 goto cleanup_head_ref;
4530 msg = reflog_message(opts, "finish", "returning to %s",
4531 head_ref.buf);
4532 if (create_symref("HEAD", head_ref.buf, msg)) {
4533 res = error(_("could not update HEAD to %s"),
4534 head_ref.buf);
4535 goto cleanup_head_ref;
4537 strbuf_reset(&buf);
4540 if (opts->verbose) {
4541 struct rev_info log_tree_opt;
4542 struct object_id orig, head;
4544 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4545 repo_init_revisions(r, &log_tree_opt, NULL);
4546 log_tree_opt.diff = 1;
4547 log_tree_opt.diffopt.output_format =
4548 DIFF_FORMAT_DIFFSTAT;
4549 log_tree_opt.disable_stdin = 1;
4551 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4552 !get_oid(buf.buf, &orig) &&
4553 !get_oid("HEAD", &head)) {
4554 diff_tree_oid(&orig, &head, "",
4555 &log_tree_opt.diffopt);
4556 log_tree_diff_flush(&log_tree_opt);
4559 flush_rewritten_pending();
4560 if (!stat(rebase_path_rewritten_list(), &st) &&
4561 st.st_size > 0) {
4562 struct child_process child = CHILD_PROCESS_INIT;
4563 const char *post_rewrite_hook =
4564 find_hook("post-rewrite");
4566 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4567 child.git_cmd = 1;
4568 strvec_push(&child.args, "notes");
4569 strvec_push(&child.args, "copy");
4570 strvec_push(&child.args, "--for-rewrite=rebase");
4571 /* we don't care if this copying failed */
4572 run_command(&child);
4574 if (post_rewrite_hook) {
4575 struct child_process hook = CHILD_PROCESS_INIT;
4577 hook.in = open(rebase_path_rewritten_list(),
4578 O_RDONLY);
4579 hook.stdout_to_stderr = 1;
4580 hook.trace2_hook_name = "post-rewrite";
4581 strvec_push(&hook.args, post_rewrite_hook);
4582 strvec_push(&hook.args, "rebase");
4583 /* we don't care if this hook failed */
4584 run_command(&hook);
4587 apply_autostash(rebase_path_autostash());
4589 if (!opts->quiet) {
4590 if (!opts->verbose)
4591 term_clear_line();
4592 fprintf(stderr,
4593 _("Successfully rebased and updated %s.\n"),
4594 head_ref.buf);
4597 strbuf_release(&buf);
4598 strbuf_release(&head_ref);
4602 * Sequence of picks finished successfully; cleanup by
4603 * removing the .git/sequencer directory
4605 return sequencer_remove_state(opts);
4608 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4610 struct strvec argv = STRVEC_INIT;
4611 int ret;
4613 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4614 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4615 return error(_("no cherry-pick or revert in progress"));
4617 strvec_push(&argv, "commit");
4620 * continue_single_pick() handles the case of recovering from a
4621 * conflict. should_edit() doesn't handle that case; for a conflict,
4622 * we want to edit if the user asked for it, or if they didn't specify
4623 * and stdin is a tty.
4625 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4627 * Include --cleanup=strip as well because we don't want the
4628 * "# Conflicts:" messages.
4630 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4632 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4633 strvec_clear(&argv);
4634 return ret;
4637 static int commit_staged_changes(struct repository *r,
4638 struct replay_opts *opts,
4639 struct todo_list *todo_list)
4641 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4642 unsigned int final_fixup = 0, is_clean;
4644 if (has_unstaged_changes(r, 1))
4645 return error(_("cannot rebase: You have unstaged changes."));
4647 is_clean = !has_uncommitted_changes(r, 0);
4649 if (file_exists(rebase_path_amend())) {
4650 struct strbuf rev = STRBUF_INIT;
4651 struct object_id head, to_amend;
4653 if (get_oid("HEAD", &head))
4654 return error(_("cannot amend non-existing commit"));
4655 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4656 return error(_("invalid file: '%s'"), rebase_path_amend());
4657 if (get_oid_hex(rev.buf, &to_amend))
4658 return error(_("invalid contents: '%s'"),
4659 rebase_path_amend());
4660 if (!is_clean && !oideq(&head, &to_amend))
4661 return error(_("\nYou have uncommitted changes in your "
4662 "working tree. Please, commit them\n"
4663 "first and then run 'git rebase "
4664 "--continue' again."));
4666 * When skipping a failed fixup/squash, we need to edit the
4667 * commit message, the current fixup list and count, and if it
4668 * was the last fixup/squash in the chain, we need to clean up
4669 * the commit message and if there was a squash, let the user
4670 * edit it.
4672 if (!is_clean || !opts->current_fixup_count)
4673 ; /* this is not the final fixup */
4674 else if (!oideq(&head, &to_amend) ||
4675 !file_exists(rebase_path_stopped_sha())) {
4676 /* was a final fixup or squash done manually? */
4677 if (!is_fixup(peek_command(todo_list, 0))) {
4678 unlink(rebase_path_fixup_msg());
4679 unlink(rebase_path_squash_msg());
4680 unlink(rebase_path_current_fixups());
4681 strbuf_reset(&opts->current_fixups);
4682 opts->current_fixup_count = 0;
4684 } else {
4685 /* we are in a fixup/squash chain */
4686 const char *p = opts->current_fixups.buf;
4687 int len = opts->current_fixups.len;
4689 opts->current_fixup_count--;
4690 if (!len)
4691 BUG("Incorrect current_fixups:\n%s", p);
4692 while (len && p[len - 1] != '\n')
4693 len--;
4694 strbuf_setlen(&opts->current_fixups, len);
4695 if (write_message(p, len, rebase_path_current_fixups(),
4696 0) < 0)
4697 return error(_("could not write file: '%s'"),
4698 rebase_path_current_fixups());
4701 * If a fixup/squash in a fixup/squash chain failed, the
4702 * commit message is already correct, no need to commit
4703 * it again.
4705 * Only if it is the final command in the fixup/squash
4706 * chain, and only if the chain is longer than a single
4707 * fixup/squash command (which was just skipped), do we
4708 * actually need to re-commit with a cleaned up commit
4709 * message.
4711 if (opts->current_fixup_count > 0 &&
4712 !is_fixup(peek_command(todo_list, 0))) {
4713 final_fixup = 1;
4715 * If there was not a single "squash" in the
4716 * chain, we only need to clean up the commit
4717 * message, no need to bother the user with
4718 * opening the commit message in the editor.
4720 if (!starts_with(p, "squash ") &&
4721 !strstr(p, "\nsquash "))
4722 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4723 } else if (is_fixup(peek_command(todo_list, 0))) {
4725 * We need to update the squash message to skip
4726 * the latest commit message.
4728 struct commit *commit;
4729 const char *path = rebase_path_squash_msg();
4730 const char *encoding = get_commit_output_encoding();
4732 if (parse_head(r, &commit) ||
4733 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4734 write_message(p, strlen(p), path, 0)) {
4735 unuse_commit_buffer(commit, p);
4736 return error(_("could not write file: "
4737 "'%s'"), path);
4739 unuse_commit_buffer(commit, p);
4743 strbuf_release(&rev);
4744 flags |= AMEND_MSG;
4747 if (is_clean) {
4748 if (refs_ref_exists(get_main_ref_store(r),
4749 "CHERRY_PICK_HEAD") &&
4750 refs_delete_ref(get_main_ref_store(r), "",
4751 "CHERRY_PICK_HEAD", NULL, 0))
4752 return error(_("could not remove CHERRY_PICK_HEAD"));
4753 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4754 return error_errno(_("could not remove '%s'"),
4755 git_path_merge_msg(r));
4756 if (!final_fixup)
4757 return 0;
4760 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4761 opts, flags))
4762 return error(_("could not commit staged changes."));
4763 unlink(rebase_path_amend());
4764 unlink(git_path_merge_head(r));
4765 unlink(git_path_auto_merge(r));
4766 if (final_fixup) {
4767 unlink(rebase_path_fixup_msg());
4768 unlink(rebase_path_squash_msg());
4770 if (opts->current_fixup_count > 0) {
4772 * Whether final fixup or not, we just cleaned up the commit
4773 * message...
4775 unlink(rebase_path_current_fixups());
4776 strbuf_reset(&opts->current_fixups);
4777 opts->current_fixup_count = 0;
4779 return 0;
4782 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4784 struct todo_list todo_list = TODO_LIST_INIT;
4785 int res;
4787 if (read_and_refresh_cache(r, opts))
4788 return -1;
4790 if (read_populate_opts(opts))
4791 return -1;
4792 if (is_rebase_i(opts)) {
4793 if ((res = read_populate_todo(r, &todo_list, opts)))
4794 goto release_todo_list;
4796 if (file_exists(rebase_path_dropped())) {
4797 if ((res = todo_list_check_against_backup(r, &todo_list)))
4798 goto release_todo_list;
4800 unlink(rebase_path_dropped());
4803 if (commit_staged_changes(r, opts, &todo_list)) {
4804 res = -1;
4805 goto release_todo_list;
4807 } else if (!file_exists(get_todo_path(opts)))
4808 return continue_single_pick(r, opts);
4809 else if ((res = read_populate_todo(r, &todo_list, opts)))
4810 goto release_todo_list;
4812 if (!is_rebase_i(opts)) {
4813 /* Verify that the conflict has been resolved */
4814 if (refs_ref_exists(get_main_ref_store(r),
4815 "CHERRY_PICK_HEAD") ||
4816 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4817 res = continue_single_pick(r, opts);
4818 if (res)
4819 goto release_todo_list;
4821 if (index_differs_from(r, "HEAD", NULL, 0)) {
4822 res = error_dirty_index(r, opts);
4823 goto release_todo_list;
4825 todo_list.current++;
4826 } else if (file_exists(rebase_path_stopped_sha())) {
4827 struct strbuf buf = STRBUF_INIT;
4828 struct object_id oid;
4830 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4831 READ_ONELINER_SKIP_IF_EMPTY) &&
4832 !get_oid_hex(buf.buf, &oid))
4833 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4834 strbuf_release(&buf);
4837 res = pick_commits(r, &todo_list, opts);
4838 release_todo_list:
4839 todo_list_release(&todo_list);
4840 return res;
4843 static int single_pick(struct repository *r,
4844 struct commit *cmit,
4845 struct replay_opts *opts)
4847 int check_todo;
4848 struct todo_item item;
4850 item.command = opts->action == REPLAY_PICK ?
4851 TODO_PICK : TODO_REVERT;
4852 item.commit = cmit;
4854 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4855 return do_pick_commit(r, &item, opts, 0, &check_todo);
4858 int sequencer_pick_revisions(struct repository *r,
4859 struct replay_opts *opts)
4861 struct todo_list todo_list = TODO_LIST_INIT;
4862 struct object_id oid;
4863 int i, res;
4865 assert(opts->revs);
4866 if (read_and_refresh_cache(r, opts))
4867 return -1;
4869 for (i = 0; i < opts->revs->pending.nr; i++) {
4870 struct object_id oid;
4871 const char *name = opts->revs->pending.objects[i].name;
4873 /* This happens when using --stdin. */
4874 if (!strlen(name))
4875 continue;
4877 if (!get_oid(name, &oid)) {
4878 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4879 enum object_type type = oid_object_info(r,
4880 &oid,
4881 NULL);
4882 return error(_("%s: can't cherry-pick a %s"),
4883 name, type_name(type));
4885 } else
4886 return error(_("%s: bad revision"), name);
4890 * If we were called as "git cherry-pick <commit>", just
4891 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4892 * REVERT_HEAD, and don't touch the sequencer state.
4893 * This means it is possible to cherry-pick in the middle
4894 * of a cherry-pick sequence.
4896 if (opts->revs->cmdline.nr == 1 &&
4897 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4898 opts->revs->no_walk &&
4899 !opts->revs->cmdline.rev->flags) {
4900 struct commit *cmit;
4901 if (prepare_revision_walk(opts->revs))
4902 return error(_("revision walk setup failed"));
4903 cmit = get_revision(opts->revs);
4904 if (!cmit)
4905 return error(_("empty commit set passed"));
4906 if (get_revision(opts->revs))
4907 BUG("unexpected extra commit from walk");
4908 return single_pick(r, cmit, opts);
4912 * Start a new cherry-pick/ revert sequence; but
4913 * first, make sure that an existing one isn't in
4914 * progress
4917 if (walk_revs_populate_todo(&todo_list, opts) ||
4918 create_seq_dir(r) < 0)
4919 return -1;
4920 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4921 return error(_("can't revert as initial commit"));
4922 if (save_head(oid_to_hex(&oid)))
4923 return -1;
4924 if (save_opts(opts))
4925 return -1;
4926 update_abort_safety_file();
4927 res = pick_commits(r, &todo_list, opts);
4928 todo_list_release(&todo_list);
4929 return res;
4932 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4934 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4935 struct strbuf sob = STRBUF_INIT;
4936 int has_footer;
4938 strbuf_addstr(&sob, sign_off_header);
4939 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4940 strbuf_addch(&sob, '\n');
4942 if (!ignore_footer)
4943 strbuf_complete_line(msgbuf);
4946 * If the whole message buffer is equal to the sob, pretend that we
4947 * found a conforming footer with a matching sob
4949 if (msgbuf->len - ignore_footer == sob.len &&
4950 !strncmp(msgbuf->buf, sob.buf, sob.len))
4951 has_footer = 3;
4952 else
4953 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4955 if (!has_footer) {
4956 const char *append_newlines = NULL;
4957 size_t len = msgbuf->len - ignore_footer;
4959 if (!len) {
4961 * The buffer is completely empty. Leave foom for
4962 * the title and body to be filled in by the user.
4964 append_newlines = "\n\n";
4965 } else if (len == 1) {
4967 * Buffer contains a single newline. Add another
4968 * so that we leave room for the title and body.
4970 append_newlines = "\n";
4971 } else if (msgbuf->buf[len - 2] != '\n') {
4973 * Buffer ends with a single newline. Add another
4974 * so that there is an empty line between the message
4975 * body and the sob.
4977 append_newlines = "\n";
4978 } /* else, the buffer already ends with two newlines. */
4980 if (append_newlines)
4981 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4982 append_newlines, strlen(append_newlines));
4985 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4986 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4987 sob.buf, sob.len);
4989 strbuf_release(&sob);
4992 struct labels_entry {
4993 struct hashmap_entry entry;
4994 char label[FLEX_ARRAY];
4997 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4998 const struct hashmap_entry *entry_or_key, const void *key)
5000 const struct labels_entry *a, *b;
5002 a = container_of(eptr, const struct labels_entry, entry);
5003 b = container_of(entry_or_key, const struct labels_entry, entry);
5005 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5008 struct string_entry {
5009 struct oidmap_entry entry;
5010 char string[FLEX_ARRAY];
5013 struct label_state {
5014 struct oidmap commit2label;
5015 struct hashmap labels;
5016 struct strbuf buf;
5019 static const char *label_oid(struct object_id *oid, const char *label,
5020 struct label_state *state)
5022 struct labels_entry *labels_entry;
5023 struct string_entry *string_entry;
5024 struct object_id dummy;
5025 int i;
5027 string_entry = oidmap_get(&state->commit2label, oid);
5028 if (string_entry)
5029 return string_entry->string;
5032 * For "uninteresting" commits, i.e. commits that are not to be
5033 * rebased, and which can therefore not be labeled, we use a unique
5034 * abbreviation of the commit name. This is slightly more complicated
5035 * than calling find_unique_abbrev() because we also need to make
5036 * sure that the abbreviation does not conflict with any other
5037 * label.
5039 * We disallow "interesting" commits to be labeled by a string that
5040 * is a valid full-length hash, to ensure that we always can find an
5041 * abbreviation for any uninteresting commit's names that does not
5042 * clash with any other label.
5044 strbuf_reset(&state->buf);
5045 if (!label) {
5046 char *p;
5048 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5049 label = p = state->buf.buf;
5051 find_unique_abbrev_r(p, oid, default_abbrev);
5054 * We may need to extend the abbreviated hash so that there is
5055 * no conflicting label.
5057 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5058 size_t i = strlen(p) + 1;
5060 oid_to_hex_r(p, oid);
5061 for (; i < the_hash_algo->hexsz; i++) {
5062 char save = p[i];
5063 p[i] = '\0';
5064 if (!hashmap_get_from_hash(&state->labels,
5065 strihash(p), p))
5066 break;
5067 p[i] = save;
5070 } else {
5071 struct strbuf *buf = &state->buf;
5074 * Sanitize labels by replacing non-alpha-numeric characters
5075 * (including white-space ones) by dashes, as they might be
5076 * illegal in file names (and hence in ref names).
5078 * Note that we retain non-ASCII UTF-8 characters (identified
5079 * via the most significant bit). They should be all acceptable
5080 * in file names. We do not validate the UTF-8 here, that's not
5081 * the job of this function.
5083 for (; *label; label++)
5084 if ((*label & 0x80) || isalnum(*label))
5085 strbuf_addch(buf, *label);
5086 /* avoid leading dash and double-dashes */
5087 else if (buf->len && buf->buf[buf->len - 1] != '-')
5088 strbuf_addch(buf, '-');
5089 if (!buf->len) {
5090 strbuf_addstr(buf, "rev-");
5091 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5093 label = buf->buf;
5095 if ((buf->len == the_hash_algo->hexsz &&
5096 !get_oid_hex(label, &dummy)) ||
5097 (buf->len == 1 && *label == '#') ||
5098 hashmap_get_from_hash(&state->labels,
5099 strihash(label), label)) {
5101 * If the label already exists, or if the label is a
5102 * valid full OID, or the label is a '#' (which we use
5103 * as a separator between merge heads and oneline), we
5104 * append a dash and a number to make it unique.
5106 size_t len = buf->len;
5108 for (i = 2; ; i++) {
5109 strbuf_setlen(buf, len);
5110 strbuf_addf(buf, "-%d", i);
5111 if (!hashmap_get_from_hash(&state->labels,
5112 strihash(buf->buf),
5113 buf->buf))
5114 break;
5117 label = buf->buf;
5121 FLEX_ALLOC_STR(labels_entry, label, label);
5122 hashmap_entry_init(&labels_entry->entry, strihash(label));
5123 hashmap_add(&state->labels, &labels_entry->entry);
5125 FLEX_ALLOC_STR(string_entry, string, label);
5126 oidcpy(&string_entry->entry.oid, oid);
5127 oidmap_put(&state->commit2label, string_entry);
5129 return string_entry->string;
5132 static int make_script_with_merges(struct pretty_print_context *pp,
5133 struct rev_info *revs, struct strbuf *out,
5134 unsigned flags)
5136 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5137 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5138 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5139 int skipped_commit = 0;
5140 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5141 struct strbuf label = STRBUF_INIT;
5142 struct commit_list *commits = NULL, **tail = &commits, *iter;
5143 struct commit_list *tips = NULL, **tips_tail = &tips;
5144 struct commit *commit;
5145 struct oidmap commit2todo = OIDMAP_INIT;
5146 struct string_entry *entry;
5147 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5148 shown = OIDSET_INIT;
5149 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5151 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5152 const char *cmd_pick = abbr ? "p" : "pick",
5153 *cmd_label = abbr ? "l" : "label",
5154 *cmd_reset = abbr ? "t" : "reset",
5155 *cmd_merge = abbr ? "m" : "merge";
5157 oidmap_init(&commit2todo, 0);
5158 oidmap_init(&state.commit2label, 0);
5159 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5160 strbuf_init(&state.buf, 32);
5162 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5163 struct labels_entry *onto_label_entry;
5164 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5165 FLEX_ALLOC_STR(entry, string, "onto");
5166 oidcpy(&entry->entry.oid, oid);
5167 oidmap_put(&state.commit2label, entry);
5169 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5170 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5171 hashmap_add(&state.labels, &onto_label_entry->entry);
5175 * First phase:
5176 * - get onelines for all commits
5177 * - gather all branch tips (i.e. 2nd or later parents of merges)
5178 * - label all branch tips
5180 while ((commit = get_revision(revs))) {
5181 struct commit_list *to_merge;
5182 const char *p1, *p2;
5183 struct object_id *oid;
5184 int is_empty;
5186 tail = &commit_list_insert(commit, tail)->next;
5187 oidset_insert(&interesting, &commit->object.oid);
5189 is_empty = is_original_commit_empty(commit);
5190 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5191 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5192 warning(_("skipped previously applied commit %s"),
5193 short_commit_name(commit));
5194 skipped_commit = 1;
5195 continue;
5197 if (is_empty && !keep_empty)
5198 continue;
5200 strbuf_reset(&oneline);
5201 pretty_print_commit(pp, commit, &oneline);
5203 to_merge = commit->parents ? commit->parents->next : NULL;
5204 if (!to_merge) {
5205 /* non-merge commit: easy case */
5206 strbuf_reset(&buf);
5207 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5208 oid_to_hex(&commit->object.oid),
5209 oneline.buf);
5210 if (is_empty)
5211 strbuf_addf(&buf, " %c empty",
5212 comment_line_char);
5214 FLEX_ALLOC_STR(entry, string, buf.buf);
5215 oidcpy(&entry->entry.oid, &commit->object.oid);
5216 oidmap_put(&commit2todo, entry);
5218 continue;
5221 /* Create a label */
5222 strbuf_reset(&label);
5223 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5224 (p1 = strchr(p1, '\'')) &&
5225 (p2 = strchr(++p1, '\'')))
5226 strbuf_add(&label, p1, p2 - p1);
5227 else if (skip_prefix(oneline.buf, "Merge pull request ",
5228 &p1) &&
5229 (p1 = strstr(p1, " from ")))
5230 strbuf_addstr(&label, p1 + strlen(" from "));
5231 else
5232 strbuf_addbuf(&label, &oneline);
5234 strbuf_reset(&buf);
5235 strbuf_addf(&buf, "%s -C %s",
5236 cmd_merge, oid_to_hex(&commit->object.oid));
5238 /* label the tips of merged branches */
5239 for (; to_merge; to_merge = to_merge->next) {
5240 oid = &to_merge->item->object.oid;
5241 strbuf_addch(&buf, ' ');
5243 if (!oidset_contains(&interesting, oid)) {
5244 strbuf_addstr(&buf, label_oid(oid, NULL,
5245 &state));
5246 continue;
5249 tips_tail = &commit_list_insert(to_merge->item,
5250 tips_tail)->next;
5252 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5254 strbuf_addf(&buf, " # %s", oneline.buf);
5256 FLEX_ALLOC_STR(entry, string, buf.buf);
5257 oidcpy(&entry->entry.oid, &commit->object.oid);
5258 oidmap_put(&commit2todo, entry);
5260 if (skipped_commit)
5261 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5262 _("use --reapply-cherry-picks to include skipped commits"));
5265 * Second phase:
5266 * - label branch points
5267 * - add HEAD to the branch tips
5269 for (iter = commits; iter; iter = iter->next) {
5270 struct commit_list *parent = iter->item->parents;
5271 for (; parent; parent = parent->next) {
5272 struct object_id *oid = &parent->item->object.oid;
5273 if (!oidset_contains(&interesting, oid))
5274 continue;
5275 if (oidset_insert(&child_seen, oid))
5276 label_oid(oid, "branch-point", &state);
5279 /* Add HEAD as implicit "tip of branch" */
5280 if (!iter->next)
5281 tips_tail = &commit_list_insert(iter->item,
5282 tips_tail)->next;
5286 * Third phase: output the todo list. This is a bit tricky, as we
5287 * want to avoid jumping back and forth between revisions. To
5288 * accomplish that goal, we walk backwards from the branch tips,
5289 * gathering commits not yet shown, reversing the list on the fly,
5290 * then outputting that list (labeling revisions as needed).
5292 strbuf_addf(out, "%s onto\n", cmd_label);
5293 for (iter = tips; iter; iter = iter->next) {
5294 struct commit_list *list = NULL, *iter2;
5296 commit = iter->item;
5297 if (oidset_contains(&shown, &commit->object.oid))
5298 continue;
5299 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5301 if (entry)
5302 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5303 else
5304 strbuf_addch(out, '\n');
5306 while (oidset_contains(&interesting, &commit->object.oid) &&
5307 !oidset_contains(&shown, &commit->object.oid)) {
5308 commit_list_insert(commit, &list);
5309 if (!commit->parents) {
5310 commit = NULL;
5311 break;
5313 commit = commit->parents->item;
5316 if (!commit)
5317 strbuf_addf(out, "%s %s\n", cmd_reset,
5318 rebase_cousins || root_with_onto ?
5319 "onto" : "[new root]");
5320 else {
5321 const char *to = NULL;
5323 entry = oidmap_get(&state.commit2label,
5324 &commit->object.oid);
5325 if (entry)
5326 to = entry->string;
5327 else if (!rebase_cousins)
5328 to = label_oid(&commit->object.oid, NULL,
5329 &state);
5331 if (!to || !strcmp(to, "onto"))
5332 strbuf_addf(out, "%s onto\n", cmd_reset);
5333 else {
5334 strbuf_reset(&oneline);
5335 pretty_print_commit(pp, commit, &oneline);
5336 strbuf_addf(out, "%s %s # %s\n",
5337 cmd_reset, to, oneline.buf);
5341 for (iter2 = list; iter2; iter2 = iter2->next) {
5342 struct object_id *oid = &iter2->item->object.oid;
5343 entry = oidmap_get(&commit2todo, oid);
5344 /* only show if not already upstream */
5345 if (entry)
5346 strbuf_addf(out, "%s\n", entry->string);
5347 entry = oidmap_get(&state.commit2label, oid);
5348 if (entry)
5349 strbuf_addf(out, "%s %s\n",
5350 cmd_label, entry->string);
5351 oidset_insert(&shown, oid);
5354 free_commit_list(list);
5357 free_commit_list(commits);
5358 free_commit_list(tips);
5360 strbuf_release(&label);
5361 strbuf_release(&oneline);
5362 strbuf_release(&buf);
5364 oidmap_free(&commit2todo, 1);
5365 oidmap_free(&state.commit2label, 1);
5366 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5367 strbuf_release(&state.buf);
5369 return 0;
5372 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5373 const char **argv, unsigned flags)
5375 char *format = NULL;
5376 struct pretty_print_context pp = {0};
5377 struct rev_info revs;
5378 struct commit *commit;
5379 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5380 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5381 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5382 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5383 int skipped_commit = 0;
5385 repo_init_revisions(r, &revs, NULL);
5386 revs.verbose_header = 1;
5387 if (!rebase_merges)
5388 revs.max_parents = 1;
5389 revs.cherry_mark = !reapply_cherry_picks;
5390 revs.limited = 1;
5391 revs.reverse = 1;
5392 revs.right_only = 1;
5393 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5394 revs.topo_order = 1;
5396 revs.pretty_given = 1;
5397 git_config_get_string("rebase.instructionFormat", &format);
5398 if (!format || !*format) {
5399 free(format);
5400 format = xstrdup("%s");
5402 get_commit_format(format, &revs);
5403 free(format);
5404 pp.fmt = revs.commit_format;
5405 pp.output_encoding = get_log_output_encoding();
5407 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5408 return error(_("make_script: unhandled options"));
5410 if (prepare_revision_walk(&revs) < 0)
5411 return error(_("make_script: error preparing revisions"));
5413 if (rebase_merges)
5414 return make_script_with_merges(&pp, &revs, out, flags);
5416 while ((commit = get_revision(&revs))) {
5417 int is_empty = is_original_commit_empty(commit);
5419 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5420 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5421 warning(_("skipped previously applied commit %s"),
5422 short_commit_name(commit));
5423 skipped_commit = 1;
5424 continue;
5426 if (is_empty && !keep_empty)
5427 continue;
5428 strbuf_addf(out, "%s %s ", insn,
5429 oid_to_hex(&commit->object.oid));
5430 pretty_print_commit(&pp, commit, out);
5431 if (is_empty)
5432 strbuf_addf(out, " %c empty", comment_line_char);
5433 strbuf_addch(out, '\n');
5435 if (skipped_commit)
5436 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5437 _("use --reapply-cherry-picks to include skipped commits"));
5438 return 0;
5442 * Add commands after pick and (series of) squash/fixup commands
5443 * in the todo list.
5445 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5446 struct string_list *commands)
5448 struct strbuf *buf = &todo_list->buf;
5449 size_t base_offset = buf->len;
5450 int i, insert, nr = 0, alloc = 0;
5451 struct todo_item *items = NULL, *base_items = NULL;
5453 CALLOC_ARRAY(base_items, commands->nr);
5454 for (i = 0; i < commands->nr; i++) {
5455 size_t command_len = strlen(commands->items[i].string);
5457 strbuf_addstr(buf, commands->items[i].string);
5458 strbuf_addch(buf, '\n');
5460 base_items[i].command = TODO_EXEC;
5461 base_items[i].offset_in_buf = base_offset;
5462 base_items[i].arg_offset = base_offset + strlen("exec ");
5463 base_items[i].arg_len = command_len - strlen("exec ");
5465 base_offset += command_len + 1;
5469 * Insert <commands> after every pick. Here, fixup/squash chains
5470 * are considered part of the pick, so we insert the commands *after*
5471 * those chains if there are any.
5473 * As we insert the exec commands immediately after rearranging
5474 * any fixups and before the user edits the list, a fixup chain
5475 * can never contain comments (any comments are empty picks that
5476 * have been commented out because the user did not specify
5477 * --keep-empty). So, it is safe to insert an exec command
5478 * without looking at the command following a comment.
5480 insert = 0;
5481 for (i = 0; i < todo_list->nr; i++) {
5482 enum todo_command command = todo_list->items[i].command;
5483 if (insert && !is_fixup(command)) {
5484 ALLOC_GROW(items, nr + commands->nr, alloc);
5485 COPY_ARRAY(items + nr, base_items, commands->nr);
5486 nr += commands->nr;
5488 insert = 0;
5491 ALLOC_GROW(items, nr + 1, alloc);
5492 items[nr++] = todo_list->items[i];
5494 if (command == TODO_PICK || command == TODO_MERGE)
5495 insert = 1;
5498 /* insert or append final <commands> */
5499 if (insert || nr == todo_list->nr) {
5500 ALLOC_GROW(items, nr + commands->nr, alloc);
5501 COPY_ARRAY(items + nr, base_items, commands->nr);
5502 nr += commands->nr;
5505 free(base_items);
5506 FREE_AND_NULL(todo_list->items);
5507 todo_list->items = items;
5508 todo_list->nr = nr;
5509 todo_list->alloc = alloc;
5512 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5513 struct strbuf *buf, int num, unsigned flags)
5515 struct todo_item *item;
5516 int i, max = todo_list->nr;
5518 if (num > 0 && num < max)
5519 max = num;
5521 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5522 char cmd;
5524 /* if the item is not a command write it and continue */
5525 if (item->command >= TODO_COMMENT) {
5526 strbuf_addf(buf, "%.*s\n", item->arg_len,
5527 todo_item_get_arg(todo_list, item));
5528 continue;
5531 /* add command to the buffer */
5532 cmd = command_to_char(item->command);
5533 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5534 strbuf_addch(buf, cmd);
5535 else
5536 strbuf_addstr(buf, command_to_string(item->command));
5538 /* add commit id */
5539 if (item->commit) {
5540 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5541 short_commit_name(item->commit) :
5542 oid_to_hex(&item->commit->object.oid);
5544 if (item->command == TODO_FIXUP) {
5545 if (item->flags & TODO_EDIT_FIXUP_MSG)
5546 strbuf_addstr(buf, " -c");
5547 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5548 strbuf_addstr(buf, " -C");
5552 if (item->command == TODO_MERGE) {
5553 if (item->flags & TODO_EDIT_MERGE_MSG)
5554 strbuf_addstr(buf, " -c");
5555 else
5556 strbuf_addstr(buf, " -C");
5559 strbuf_addf(buf, " %s", oid);
5562 /* add all the rest */
5563 if (!item->arg_len)
5564 strbuf_addch(buf, '\n');
5565 else
5566 strbuf_addf(buf, " %.*s\n", item->arg_len,
5567 todo_item_get_arg(todo_list, item));
5571 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5572 const char *file, const char *shortrevisions,
5573 const char *shortonto, int num, unsigned flags)
5575 int res;
5576 struct strbuf buf = STRBUF_INIT;
5578 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5579 if (flags & TODO_LIST_APPEND_TODO_HELP)
5580 append_todo_help(count_commands(todo_list),
5581 shortrevisions, shortonto, &buf);
5583 res = write_message(buf.buf, buf.len, file, 0);
5584 strbuf_release(&buf);
5586 return res;
5589 /* skip picking commits whose parents are unchanged */
5590 static int skip_unnecessary_picks(struct repository *r,
5591 struct todo_list *todo_list,
5592 struct object_id *base_oid)
5594 struct object_id *parent_oid;
5595 int i;
5597 for (i = 0; i < todo_list->nr; i++) {
5598 struct todo_item *item = todo_list->items + i;
5600 if (item->command >= TODO_NOOP)
5601 continue;
5602 if (item->command != TODO_PICK)
5603 break;
5604 if (parse_commit(item->commit)) {
5605 return error(_("could not parse commit '%s'"),
5606 oid_to_hex(&item->commit->object.oid));
5608 if (!item->commit->parents)
5609 break; /* root commit */
5610 if (item->commit->parents->next)
5611 break; /* merge commit */
5612 parent_oid = &item->commit->parents->item->object.oid;
5613 if (!oideq(parent_oid, base_oid))
5614 break;
5615 oidcpy(base_oid, &item->commit->object.oid);
5617 if (i > 0) {
5618 const char *done_path = rebase_path_done();
5620 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5621 error_errno(_("could not write to '%s'"), done_path);
5622 return -1;
5625 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5626 todo_list->nr -= i;
5627 todo_list->current = 0;
5628 todo_list->done_nr += i;
5630 if (is_fixup(peek_command(todo_list, 0)))
5631 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5634 return 0;
5637 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5638 const char *shortrevisions, const char *onto_name,
5639 struct commit *onto, const struct object_id *orig_head,
5640 struct string_list *commands, unsigned autosquash,
5641 struct todo_list *todo_list)
5643 char shortonto[GIT_MAX_HEXSZ + 1];
5644 const char *todo_file = rebase_path_todo();
5645 struct todo_list new_todo = TODO_LIST_INIT;
5646 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5647 struct object_id oid = onto->object.oid;
5648 int res;
5650 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5652 if (buf->len == 0) {
5653 struct todo_item *item = append_new_todo(todo_list);
5654 item->command = TODO_NOOP;
5655 item->commit = NULL;
5656 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5659 if (autosquash && todo_list_rearrange_squash(todo_list))
5660 return -1;
5662 if (commands->nr)
5663 todo_list_add_exec_commands(todo_list, commands);
5665 if (count_commands(todo_list) == 0) {
5666 apply_autostash(rebase_path_autostash());
5667 sequencer_remove_state(opts);
5669 return error(_("nothing to do"));
5672 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5673 shortonto, flags);
5674 if (res == -1)
5675 return -1;
5676 else if (res == -2) {
5677 apply_autostash(rebase_path_autostash());
5678 sequencer_remove_state(opts);
5680 return -1;
5681 } else if (res == -3) {
5682 apply_autostash(rebase_path_autostash());
5683 sequencer_remove_state(opts);
5684 todo_list_release(&new_todo);
5686 return error(_("nothing to do"));
5687 } else if (res == -4) {
5688 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5689 todo_list_release(&new_todo);
5691 return -1;
5694 /* Expand the commit IDs */
5695 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5696 strbuf_swap(&new_todo.buf, &buf2);
5697 strbuf_release(&buf2);
5698 new_todo.total_nr -= new_todo.nr;
5699 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5700 BUG("invalid todo list after expanding IDs:\n%s",
5701 new_todo.buf.buf);
5703 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5704 todo_list_release(&new_todo);
5705 return error(_("could not skip unnecessary pick commands"));
5708 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5709 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5710 todo_list_release(&new_todo);
5711 return error_errno(_("could not write '%s'"), todo_file);
5714 res = -1;
5716 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5717 goto cleanup;
5719 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5720 goto cleanup;
5722 todo_list_write_total_nr(&new_todo);
5723 res = pick_commits(r, &new_todo, opts);
5725 cleanup:
5726 todo_list_release(&new_todo);
5728 return res;
5731 struct subject2item_entry {
5732 struct hashmap_entry entry;
5733 int i;
5734 char subject[FLEX_ARRAY];
5737 static int subject2item_cmp(const void *fndata,
5738 const struct hashmap_entry *eptr,
5739 const struct hashmap_entry *entry_or_key,
5740 const void *key)
5742 const struct subject2item_entry *a, *b;
5744 a = container_of(eptr, const struct subject2item_entry, entry);
5745 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5747 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5750 define_commit_slab(commit_todo_item, struct todo_item *);
5752 static int skip_fixupish(const char *subject, const char **p) {
5753 return skip_prefix(subject, "fixup! ", p) ||
5754 skip_prefix(subject, "amend! ", p) ||
5755 skip_prefix(subject, "squash! ", p);
5759 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5760 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5761 * after the former, and change "pick" to "fixup"/"squash".
5763 * Note that if the config has specified a custom instruction format, each log
5764 * message will have to be retrieved from the commit (as the oneline in the
5765 * script cannot be trusted) in order to normalize the autosquash arrangement.
5767 int todo_list_rearrange_squash(struct todo_list *todo_list)
5769 struct hashmap subject2item;
5770 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5771 char **subjects;
5772 struct commit_todo_item commit_todo;
5773 struct todo_item *items = NULL;
5775 init_commit_todo_item(&commit_todo);
5777 * The hashmap maps onelines to the respective todo list index.
5779 * If any items need to be rearranged, the next[i] value will indicate
5780 * which item was moved directly after the i'th.
5782 * In that case, last[i] will indicate the index of the latest item to
5783 * be moved to appear after the i'th.
5785 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5786 ALLOC_ARRAY(next, todo_list->nr);
5787 ALLOC_ARRAY(tail, todo_list->nr);
5788 ALLOC_ARRAY(subjects, todo_list->nr);
5789 for (i = 0; i < todo_list->nr; i++) {
5790 struct strbuf buf = STRBUF_INIT;
5791 struct todo_item *item = todo_list->items + i;
5792 const char *commit_buffer, *subject, *p;
5793 size_t subject_len;
5794 int i2 = -1;
5795 struct subject2item_entry *entry;
5797 next[i] = tail[i] = -1;
5798 if (!item->commit || item->command == TODO_DROP) {
5799 subjects[i] = NULL;
5800 continue;
5803 if (is_fixup(item->command)) {
5804 clear_commit_todo_item(&commit_todo);
5805 return error(_("the script was already rearranged."));
5808 *commit_todo_item_at(&commit_todo, item->commit) = item;
5810 parse_commit(item->commit);
5811 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5812 find_commit_subject(commit_buffer, &subject);
5813 format_subject(&buf, subject, " ");
5814 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5815 unuse_commit_buffer(item->commit, commit_buffer);
5816 if (skip_fixupish(subject, &p)) {
5817 struct commit *commit2;
5819 for (;;) {
5820 while (isspace(*p))
5821 p++;
5822 if (!skip_fixupish(p, &p))
5823 break;
5826 entry = hashmap_get_entry_from_hash(&subject2item,
5827 strhash(p), p,
5828 struct subject2item_entry,
5829 entry);
5830 if (entry)
5831 /* found by title */
5832 i2 = entry->i;
5833 else if (!strchr(p, ' ') &&
5834 (commit2 =
5835 lookup_commit_reference_by_name(p)) &&
5836 *commit_todo_item_at(&commit_todo, commit2))
5837 /* found by commit name */
5838 i2 = *commit_todo_item_at(&commit_todo, commit2)
5839 - todo_list->items;
5840 else {
5841 /* copy can be a prefix of the commit subject */
5842 for (i2 = 0; i2 < i; i2++)
5843 if (subjects[i2] &&
5844 starts_with(subjects[i2], p))
5845 break;
5846 if (i2 == i)
5847 i2 = -1;
5850 if (i2 >= 0) {
5851 rearranged = 1;
5852 if (starts_with(subject, "fixup!")) {
5853 todo_list->items[i].command = TODO_FIXUP;
5854 } else if (starts_with(subject, "amend!")) {
5855 todo_list->items[i].command = TODO_FIXUP;
5856 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5857 } else {
5858 todo_list->items[i].command = TODO_SQUASH;
5860 if (tail[i2] < 0) {
5861 next[i] = next[i2];
5862 next[i2] = i;
5863 } else {
5864 next[i] = next[tail[i2]];
5865 next[tail[i2]] = i;
5867 tail[i2] = i;
5868 } else if (!hashmap_get_from_hash(&subject2item,
5869 strhash(subject), subject)) {
5870 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5871 entry->i = i;
5872 hashmap_entry_init(&entry->entry,
5873 strhash(entry->subject));
5874 hashmap_put(&subject2item, &entry->entry);
5878 if (rearranged) {
5879 for (i = 0; i < todo_list->nr; i++) {
5880 enum todo_command command = todo_list->items[i].command;
5881 int cur = i;
5884 * Initially, all commands are 'pick's. If it is a
5885 * fixup or a squash now, we have rearranged it.
5887 if (is_fixup(command))
5888 continue;
5890 while (cur >= 0) {
5891 ALLOC_GROW(items, nr + 1, alloc);
5892 items[nr++] = todo_list->items[cur];
5893 cur = next[cur];
5897 FREE_AND_NULL(todo_list->items);
5898 todo_list->items = items;
5899 todo_list->nr = nr;
5900 todo_list->alloc = alloc;
5903 free(next);
5904 free(tail);
5905 for (i = 0; i < todo_list->nr; i++)
5906 free(subjects[i]);
5907 free(subjects);
5908 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5910 clear_commit_todo_item(&commit_todo);
5912 return 0;
5915 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5917 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5918 struct object_id cherry_pick_head, rebase_head;
5920 if (file_exists(git_path_seq_dir()))
5921 *whence = FROM_CHERRY_PICK_MULTI;
5922 if (file_exists(rebase_path()) &&
5923 !get_oid("REBASE_HEAD", &rebase_head) &&
5924 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5925 oideq(&rebase_head, &cherry_pick_head))
5926 *whence = FROM_REBASE_PICK;
5927 else
5928 *whence = FROM_CHERRY_PICK_SINGLE;
5930 return 1;
5933 return 0;