revert: config documentation fixes
[git/debian.git] / sequencer.c
blob4b66a1f79c75f5314053aac18a5e6aa1895faad1
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 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
225 opts->commit_use_reference = git_config_bool(k, v);
227 status = git_gpg_config(k, v, NULL);
228 if (status)
229 return status;
231 return git_diff_basic_config(k, v, NULL);
234 void sequencer_init_config(struct replay_opts *opts)
236 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
237 git_config(git_sequencer_config, opts);
240 static inline int is_rebase_i(const struct replay_opts *opts)
242 return opts->action == REPLAY_INTERACTIVE_REBASE;
245 static const char *get_dir(const struct replay_opts *opts)
247 if (is_rebase_i(opts))
248 return rebase_path();
249 return git_path_seq_dir();
252 static const char *get_todo_path(const struct replay_opts *opts)
254 if (is_rebase_i(opts))
255 return rebase_path_todo();
256 return git_path_todo_file();
260 * Returns 0 for non-conforming footer
261 * Returns 1 for conforming footer
262 * Returns 2 when sob exists within conforming footer
263 * Returns 3 when sob exists within conforming footer as last entry
265 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
266 size_t ignore_footer)
268 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
269 struct trailer_info info;
270 size_t i;
271 int found_sob = 0, found_sob_last = 0;
272 char saved_char;
274 opts.no_divider = 1;
276 if (ignore_footer) {
277 saved_char = sb->buf[sb->len - ignore_footer];
278 sb->buf[sb->len - ignore_footer] = '\0';
281 trailer_info_get(&info, sb->buf, &opts);
283 if (ignore_footer)
284 sb->buf[sb->len - ignore_footer] = saved_char;
286 if (info.trailer_start == info.trailer_end)
287 return 0;
289 for (i = 0; i < info.trailer_nr; i++)
290 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
291 found_sob = 1;
292 if (i == info.trailer_nr - 1)
293 found_sob_last = 1;
296 trailer_info_release(&info);
298 if (found_sob_last)
299 return 3;
300 if (found_sob)
301 return 2;
302 return 1;
305 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
307 static struct strbuf buf = STRBUF_INIT;
309 strbuf_reset(&buf);
310 if (opts->gpg_sign)
311 sq_quotef(&buf, "-S%s", opts->gpg_sign);
312 return buf.buf;
315 int sequencer_remove_state(struct replay_opts *opts)
317 struct strbuf buf = STRBUF_INIT;
318 int i, ret = 0;
320 if (is_rebase_i(opts) &&
321 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
322 char *p = buf.buf;
323 while (*p) {
324 char *eol = strchr(p, '\n');
325 if (eol)
326 *eol = '\0';
327 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
328 warning(_("could not delete '%s'"), p);
329 ret = -1;
331 if (!eol)
332 break;
333 p = eol + 1;
337 free(opts->gpg_sign);
338 free(opts->default_strategy);
339 free(opts->strategy);
340 for (i = 0; i < opts->xopts_nr; i++)
341 free(opts->xopts[i]);
342 free(opts->xopts);
343 strbuf_release(&opts->current_fixups);
345 strbuf_reset(&buf);
346 strbuf_addstr(&buf, get_dir(opts));
347 if (remove_dir_recursively(&buf, 0))
348 ret = error(_("could not remove '%s'"), buf.buf);
349 strbuf_release(&buf);
351 return ret;
354 static const char *action_name(const struct replay_opts *opts)
356 switch (opts->action) {
357 case REPLAY_REVERT:
358 return N_("revert");
359 case REPLAY_PICK:
360 return N_("cherry-pick");
361 case REPLAY_INTERACTIVE_REBASE:
362 return N_("rebase");
364 die(_("unknown action: %d"), opts->action);
367 struct commit_message {
368 char *parent_label;
369 char *label;
370 char *subject;
371 const char *message;
374 static const char *short_commit_name(struct commit *commit)
376 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
379 static int get_message(struct commit *commit, struct commit_message *out)
381 const char *abbrev, *subject;
382 int subject_len;
384 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
385 abbrev = short_commit_name(commit);
387 subject_len = find_commit_subject(out->message, &subject);
389 out->subject = xmemdupz(subject, subject_len);
390 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
391 out->parent_label = xstrfmt("parent of %s", out->label);
393 return 0;
396 static void free_message(struct commit *commit, struct commit_message *msg)
398 free(msg->parent_label);
399 free(msg->label);
400 free(msg->subject);
401 unuse_commit_buffer(commit, msg->message);
404 static void print_advice(struct repository *r, int show_hint,
405 struct replay_opts *opts)
407 char *msg = getenv("GIT_CHERRY_PICK_HELP");
409 if (msg) {
410 advise("%s\n", msg);
412 * A conflict has occurred but the porcelain
413 * (typically rebase --interactive) wants to take care
414 * of the commit itself so remove CHERRY_PICK_HEAD
416 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
417 NULL, 0);
418 return;
421 if (show_hint) {
422 if (opts->no_commit)
423 advise(_("after resolving the conflicts, mark the corrected paths\n"
424 "with 'git add <paths>' or 'git rm <paths>'"));
425 else if (opts->action == REPLAY_PICK)
426 advise(_("After resolving the conflicts, mark them with\n"
427 "\"git add/rm <pathspec>\", then run\n"
428 "\"git cherry-pick --continue\".\n"
429 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
430 "To abort and get back to the state before \"git cherry-pick\",\n"
431 "run \"git cherry-pick --abort\"."));
432 else if (opts->action == REPLAY_REVERT)
433 advise(_("After resolving the conflicts, mark them with\n"
434 "\"git add/rm <pathspec>\", then run\n"
435 "\"git revert --continue\".\n"
436 "You can instead skip this commit with \"git revert --skip\".\n"
437 "To abort and get back to the state before \"git revert\",\n"
438 "run \"git revert --abort\"."));
439 else
440 BUG("unexpected pick action in print_advice()");
444 static int write_message(const void *buf, size_t len, const char *filename,
445 int append_eol)
447 struct lock_file msg_file = LOCK_INIT;
449 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
450 if (msg_fd < 0)
451 return error_errno(_("could not lock '%s'"), filename);
452 if (write_in_full(msg_fd, buf, len) < 0) {
453 error_errno(_("could not write to '%s'"), filename);
454 rollback_lock_file(&msg_file);
455 return -1;
457 if (append_eol && write(msg_fd, "\n", 1) < 0) {
458 error_errno(_("could not write eol to '%s'"), filename);
459 rollback_lock_file(&msg_file);
460 return -1;
462 if (commit_lock_file(&msg_file) < 0)
463 return error(_("failed to finalize '%s'"), filename);
465 return 0;
468 int read_oneliner(struct strbuf *buf,
469 const char *path, unsigned flags)
471 int orig_len = buf->len;
473 if (strbuf_read_file(buf, path, 0) < 0) {
474 if ((flags & READ_ONELINER_WARN_MISSING) ||
475 (errno != ENOENT && errno != ENOTDIR))
476 warning_errno(_("could not read '%s'"), path);
477 return 0;
480 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
481 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
482 --buf->len;
483 buf->buf[buf->len] = '\0';
486 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
487 return 0;
489 return 1;
492 static struct tree *empty_tree(struct repository *r)
494 return lookup_tree(r, the_hash_algo->empty_tree);
497 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
499 if (repo_read_index_unmerged(repo))
500 return error_resolve_conflict(_(action_name(opts)));
502 error(_("your local changes would be overwritten by %s."),
503 _(action_name(opts)));
505 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
506 advise(_("commit your changes or stash them to proceed."));
507 return -1;
510 static void update_abort_safety_file(void)
512 struct object_id head;
514 /* Do nothing on a single-pick */
515 if (!file_exists(git_path_seq_dir()))
516 return;
518 if (!get_oid("HEAD", &head))
519 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
520 else
521 write_file(git_path_abort_safety_file(), "%s", "");
524 static int fast_forward_to(struct repository *r,
525 const struct object_id *to,
526 const struct object_id *from,
527 int unborn,
528 struct replay_opts *opts)
530 struct ref_transaction *transaction;
531 struct strbuf sb = STRBUF_INIT;
532 struct strbuf err = STRBUF_INIT;
534 repo_read_index(r);
535 if (checkout_fast_forward(r, from, to, 1))
536 return -1; /* the callee should have complained already */
538 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
540 transaction = ref_transaction_begin(&err);
541 if (!transaction ||
542 ref_transaction_update(transaction, "HEAD",
543 to, unborn && !is_rebase_i(opts) ?
544 null_oid() : from,
545 0, sb.buf, &err) ||
546 ref_transaction_commit(transaction, &err)) {
547 ref_transaction_free(transaction);
548 error("%s", err.buf);
549 strbuf_release(&sb);
550 strbuf_release(&err);
551 return -1;
554 strbuf_release(&sb);
555 strbuf_release(&err);
556 ref_transaction_free(transaction);
557 update_abort_safety_file();
558 return 0;
561 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
562 int use_editor)
564 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
565 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
566 COMMIT_MSG_CLEANUP_SPACE;
567 else if (!strcmp(cleanup_arg, "verbatim"))
568 return COMMIT_MSG_CLEANUP_NONE;
569 else if (!strcmp(cleanup_arg, "whitespace"))
570 return COMMIT_MSG_CLEANUP_SPACE;
571 else if (!strcmp(cleanup_arg, "strip"))
572 return COMMIT_MSG_CLEANUP_ALL;
573 else if (!strcmp(cleanup_arg, "scissors"))
574 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
575 COMMIT_MSG_CLEANUP_SPACE;
576 else
577 die(_("Invalid cleanup mode %s"), cleanup_arg);
581 * NB using int rather than enum cleanup_mode to stop clang's
582 * -Wtautological-constant-out-of-range-compare complaining that the comparison
583 * is always true.
585 static const char *describe_cleanup_mode(int cleanup_mode)
587 static const char *modes[] = { "whitespace",
588 "verbatim",
589 "scissors",
590 "strip" };
592 if (cleanup_mode < ARRAY_SIZE(modes))
593 return modes[cleanup_mode];
595 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
598 void append_conflicts_hint(struct index_state *istate,
599 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
601 int i;
603 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
604 strbuf_addch(msgbuf, '\n');
605 wt_status_append_cut_line(msgbuf);
606 strbuf_addch(msgbuf, comment_line_char);
609 strbuf_addch(msgbuf, '\n');
610 strbuf_commented_addf(msgbuf, "Conflicts:\n");
611 for (i = 0; i < istate->cache_nr;) {
612 const struct cache_entry *ce = istate->cache[i++];
613 if (ce_stage(ce)) {
614 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
615 while (i < istate->cache_nr &&
616 !strcmp(ce->name, istate->cache[i]->name))
617 i++;
622 static int do_recursive_merge(struct repository *r,
623 struct commit *base, struct commit *next,
624 const char *base_label, const char *next_label,
625 struct object_id *head, struct strbuf *msgbuf,
626 struct replay_opts *opts)
628 struct merge_options o;
629 struct merge_result result;
630 struct tree *next_tree, *base_tree, *head_tree;
631 int clean, show_output;
632 int i;
633 struct lock_file index_lock = LOCK_INIT;
635 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
636 return -1;
638 repo_read_index(r);
640 init_merge_options(&o, r);
641 o.ancestor = base ? base_label : "(empty tree)";
642 o.branch1 = "HEAD";
643 o.branch2 = next ? next_label : "(empty tree)";
644 if (is_rebase_i(opts))
645 o.buffer_output = 2;
646 o.show_rename_progress = 1;
648 head_tree = parse_tree_indirect(head);
649 next_tree = next ? get_commit_tree(next) : empty_tree(r);
650 base_tree = base ? get_commit_tree(base) : empty_tree(r);
652 for (i = 0; i < opts->xopts_nr; i++)
653 parse_merge_opt(&o, opts->xopts[i]);
655 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
656 memset(&result, 0, sizeof(result));
657 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
658 &result);
659 show_output = !is_rebase_i(opts) || !result.clean;
661 * TODO: merge_switch_to_result will update index/working tree;
662 * we only really want to do that if !result.clean || this is
663 * the final patch to be picked. But determining this is the
664 * final patch would take some work, and "head_tree" would need
665 * to be replace with the tree the index matched before we
666 * started doing any picks.
668 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
669 clean = result.clean;
670 } else {
671 ensure_full_index(r->index);
672 clean = merge_trees(&o, head_tree, next_tree, base_tree);
673 if (is_rebase_i(opts) && clean <= 0)
674 fputs(o.obuf.buf, stdout);
675 strbuf_release(&o.obuf);
677 if (clean < 0) {
678 rollback_lock_file(&index_lock);
679 return clean;
682 if (write_locked_index(r->index, &index_lock,
683 COMMIT_LOCK | SKIP_IF_UNCHANGED))
685 * TRANSLATORS: %s will be "revert", "cherry-pick" or
686 * "rebase".
688 return error(_("%s: Unable to write new index file"),
689 _(action_name(opts)));
691 if (!clean)
692 append_conflicts_hint(r->index, msgbuf,
693 opts->default_msg_cleanup);
695 return !clean;
698 static struct object_id *get_cache_tree_oid(struct index_state *istate)
700 if (!cache_tree_fully_valid(istate->cache_tree))
701 if (cache_tree_update(istate, 0)) {
702 error(_("unable to update cache tree"));
703 return NULL;
706 return &istate->cache_tree->oid;
709 static int is_index_unchanged(struct repository *r)
711 struct object_id head_oid, *cache_tree_oid;
712 struct commit *head_commit;
713 struct index_state *istate = r->index;
715 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
716 return error(_("could not resolve HEAD commit"));
718 head_commit = lookup_commit(r, &head_oid);
721 * If head_commit is NULL, check_commit, called from
722 * lookup_commit, would have indicated that head_commit is not
723 * a commit object already. parse_commit() will return failure
724 * without further complaints in such a case. Otherwise, if
725 * the commit is invalid, parse_commit() will complain. So
726 * there is nothing for us to say here. Just return failure.
728 if (parse_commit(head_commit))
729 return -1;
731 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
732 return -1;
734 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
737 static int write_author_script(const char *message)
739 struct strbuf buf = STRBUF_INIT;
740 const char *eol;
741 int res;
743 for (;;)
744 if (!*message || starts_with(message, "\n")) {
745 missing_author:
746 /* Missing 'author' line? */
747 unlink(rebase_path_author_script());
748 return 0;
749 } else if (skip_prefix(message, "author ", &message))
750 break;
751 else if ((eol = strchr(message, '\n')))
752 message = eol + 1;
753 else
754 goto missing_author;
756 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
757 while (*message && *message != '\n' && *message != '\r')
758 if (skip_prefix(message, " <", &message))
759 break;
760 else if (*message != '\'')
761 strbuf_addch(&buf, *(message++));
762 else
763 strbuf_addf(&buf, "'\\%c'", *(message++));
764 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
765 while (*message && *message != '\n' && *message != '\r')
766 if (skip_prefix(message, "> ", &message))
767 break;
768 else if (*message != '\'')
769 strbuf_addch(&buf, *(message++));
770 else
771 strbuf_addf(&buf, "'\\%c'", *(message++));
772 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
773 while (*message && *message != '\n' && *message != '\r')
774 if (*message != '\'')
775 strbuf_addch(&buf, *(message++));
776 else
777 strbuf_addf(&buf, "'\\%c'", *(message++));
778 strbuf_addch(&buf, '\'');
779 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
780 strbuf_release(&buf);
781 return res;
785 * Take a series of KEY='VALUE' lines where VALUE part is
786 * sq-quoted, and append <KEY, VALUE> at the end of the string list
788 static int parse_key_value_squoted(char *buf, struct string_list *list)
790 while (*buf) {
791 struct string_list_item *item;
792 char *np;
793 char *cp = strchr(buf, '=');
794 if (!cp) {
795 np = strchrnul(buf, '\n');
796 return error(_("no key present in '%.*s'"),
797 (int) (np - buf), buf);
799 np = strchrnul(cp, '\n');
800 *cp++ = '\0';
801 item = string_list_append(list, buf);
803 buf = np + (*np == '\n');
804 *np = '\0';
805 cp = sq_dequote(cp);
806 if (!cp)
807 return error(_("unable to dequote value of '%s'"),
808 item->string);
809 item->util = xstrdup(cp);
811 return 0;
815 * Reads and parses the state directory's "author-script" file, and sets name,
816 * email and date accordingly.
817 * Returns 0 on success, -1 if the file could not be parsed.
819 * The author script is of the format:
821 * GIT_AUTHOR_NAME='$author_name'
822 * GIT_AUTHOR_EMAIL='$author_email'
823 * GIT_AUTHOR_DATE='$author_date'
825 * where $author_name, $author_email and $author_date are quoted. We are strict
826 * with our parsing, as the file was meant to be eval'd in the now-removed
827 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
828 * from what this function expects, it is better to bail out than to do
829 * something that the user does not expect.
831 int read_author_script(const char *path, char **name, char **email, char **date,
832 int allow_missing)
834 struct strbuf buf = STRBUF_INIT;
835 struct string_list kv = STRING_LIST_INIT_DUP;
836 int retval = -1; /* assume failure */
837 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
839 if (strbuf_read_file(&buf, path, 256) <= 0) {
840 strbuf_release(&buf);
841 if (errno == ENOENT && allow_missing)
842 return 0;
843 else
844 return error_errno(_("could not open '%s' for reading"),
845 path);
848 if (parse_key_value_squoted(buf.buf, &kv))
849 goto finish;
851 for (i = 0; i < kv.nr; i++) {
852 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
853 if (name_i != -2)
854 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
855 else
856 name_i = i;
857 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
858 if (email_i != -2)
859 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
860 else
861 email_i = i;
862 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
863 if (date_i != -2)
864 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
865 else
866 date_i = i;
867 } else {
868 err = error(_("unknown variable '%s'"),
869 kv.items[i].string);
872 if (name_i == -2)
873 error(_("missing 'GIT_AUTHOR_NAME'"));
874 if (email_i == -2)
875 error(_("missing 'GIT_AUTHOR_EMAIL'"));
876 if (date_i == -2)
877 error(_("missing 'GIT_AUTHOR_DATE'"));
878 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
879 goto finish;
880 *name = kv.items[name_i].util;
881 *email = kv.items[email_i].util;
882 *date = kv.items[date_i].util;
883 retval = 0;
884 finish:
885 string_list_clear(&kv, !!retval);
886 strbuf_release(&buf);
887 return retval;
891 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
892 * file with shell quoting into struct strvec. Returns -1 on
893 * error, 0 otherwise.
895 static int read_env_script(struct strvec *env)
897 char *name, *email, *date;
899 if (read_author_script(rebase_path_author_script(),
900 &name, &email, &date, 0))
901 return -1;
903 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
904 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
905 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
906 free(name);
907 free(email);
908 free(date);
910 return 0;
913 static char *get_author(const char *message)
915 size_t len;
916 const char *a;
918 a = find_commit_header(message, "author", &len);
919 if (a)
920 return xmemdupz(a, len);
922 return NULL;
925 static const char *author_date_from_env_array(const struct strvec *env)
927 int i;
928 const char *date;
930 for (i = 0; i < env->nr; i++)
931 if (skip_prefix(env->v[i],
932 "GIT_AUTHOR_DATE=", &date))
933 return date;
935 * If GIT_AUTHOR_DATE is missing we should have already errored out when
936 * reading the script
938 BUG("GIT_AUTHOR_DATE missing from author script");
941 static const char staged_changes_advice[] =
942 N_("you have staged changes in your working tree\n"
943 "If these changes are meant to be squashed into the previous commit, run:\n"
944 "\n"
945 " git commit --amend %s\n"
946 "\n"
947 "If they are meant to go into a new commit, run:\n"
948 "\n"
949 " git commit %s\n"
950 "\n"
951 "In both cases, once you're done, continue with:\n"
952 "\n"
953 " git rebase --continue\n");
955 #define ALLOW_EMPTY (1<<0)
956 #define EDIT_MSG (1<<1)
957 #define AMEND_MSG (1<<2)
958 #define CLEANUP_MSG (1<<3)
959 #define VERIFY_MSG (1<<4)
960 #define CREATE_ROOT_COMMIT (1<<5)
961 #define VERBATIM_MSG (1<<6)
963 static int run_command_silent_on_success(struct child_process *cmd)
965 struct strbuf buf = STRBUF_INIT;
966 int rc;
968 cmd->stdout_to_stderr = 1;
969 rc = pipe_command(cmd,
970 NULL, 0,
971 NULL, 0,
972 &buf, 0);
974 if (rc)
975 fputs(buf.buf, stderr);
976 strbuf_release(&buf);
977 return rc;
981 * If we are cherry-pick, and if the merge did not result in
982 * hand-editing, we will hit this commit and inherit the original
983 * author date and name.
985 * If we are revert, or if our cherry-pick results in a hand merge,
986 * we had better say that the current user is responsible for that.
988 * An exception is when run_git_commit() is called during an
989 * interactive rebase: in that case, we will want to retain the
990 * author metadata.
992 static int run_git_commit(const char *defmsg,
993 struct replay_opts *opts,
994 unsigned int flags)
996 struct child_process cmd = CHILD_PROCESS_INIT;
998 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
999 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1001 cmd.git_cmd = 1;
1003 if (is_rebase_i(opts) &&
1004 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1005 !(!defmsg && (flags & AMEND_MSG))) &&
1006 read_env_script(&cmd.env_array)) {
1007 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1009 return error(_(staged_changes_advice),
1010 gpg_opt, gpg_opt);
1013 if (opts->committer_date_is_author_date)
1014 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
1015 opts->ignore_date ?
1016 "" :
1017 author_date_from_env_array(&cmd.env_array));
1018 if (opts->ignore_date)
1019 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1021 strvec_push(&cmd.args, "commit");
1023 if (!(flags & VERIFY_MSG))
1024 strvec_push(&cmd.args, "-n");
1025 if ((flags & AMEND_MSG))
1026 strvec_push(&cmd.args, "--amend");
1027 if (opts->gpg_sign)
1028 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1029 else
1030 strvec_push(&cmd.args, "--no-gpg-sign");
1031 if (defmsg)
1032 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1033 else if (!(flags & EDIT_MSG))
1034 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1035 if ((flags & CLEANUP_MSG))
1036 strvec_push(&cmd.args, "--cleanup=strip");
1037 if ((flags & VERBATIM_MSG))
1038 strvec_push(&cmd.args, "--cleanup=verbatim");
1039 if ((flags & EDIT_MSG))
1040 strvec_push(&cmd.args, "-e");
1041 else if (!(flags & CLEANUP_MSG) &&
1042 !opts->signoff && !opts->record_origin &&
1043 !opts->explicit_cleanup)
1044 strvec_push(&cmd.args, "--cleanup=verbatim");
1046 if ((flags & ALLOW_EMPTY))
1047 strvec_push(&cmd.args, "--allow-empty");
1049 if (!(flags & EDIT_MSG))
1050 strvec_push(&cmd.args, "--allow-empty-message");
1052 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1053 return run_command_silent_on_success(&cmd);
1054 else
1055 return run_command(&cmd);
1058 static int rest_is_empty(const struct strbuf *sb, int start)
1060 int i, eol;
1061 const char *nl;
1063 /* Check if the rest is just whitespace and Signed-off-by's. */
1064 for (i = start; i < sb->len; i++) {
1065 nl = memchr(sb->buf + i, '\n', sb->len - i);
1066 if (nl)
1067 eol = nl - sb->buf;
1068 else
1069 eol = sb->len;
1071 if (strlen(sign_off_header) <= eol - i &&
1072 starts_with(sb->buf + i, sign_off_header)) {
1073 i = eol;
1074 continue;
1076 while (i < eol)
1077 if (!isspace(sb->buf[i++]))
1078 return 0;
1081 return 1;
1084 void cleanup_message(struct strbuf *msgbuf,
1085 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1087 if (verbose || /* Truncate the message just before the diff, if any. */
1088 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1089 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1090 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1091 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1095 * Find out if the message in the strbuf contains only whitespace and
1096 * Signed-off-by lines.
1098 int message_is_empty(const struct strbuf *sb,
1099 enum commit_msg_cleanup_mode cleanup_mode)
1101 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1102 return 0;
1103 return rest_is_empty(sb, 0);
1107 * See if the user edited the message in the editor or left what
1108 * was in the template intact
1110 int template_untouched(const struct strbuf *sb, const char *template_file,
1111 enum commit_msg_cleanup_mode cleanup_mode)
1113 struct strbuf tmpl = STRBUF_INIT;
1114 const char *start;
1116 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1117 return 0;
1119 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1120 return 0;
1122 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1123 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1124 start = sb->buf;
1125 strbuf_release(&tmpl);
1126 return rest_is_empty(sb, start - sb->buf);
1129 int update_head_with_reflog(const struct commit *old_head,
1130 const struct object_id *new_head,
1131 const char *action, const struct strbuf *msg,
1132 struct strbuf *err)
1134 struct ref_transaction *transaction;
1135 struct strbuf sb = STRBUF_INIT;
1136 const char *nl;
1137 int ret = 0;
1139 if (action) {
1140 strbuf_addstr(&sb, action);
1141 strbuf_addstr(&sb, ": ");
1144 nl = strchr(msg->buf, '\n');
1145 if (nl) {
1146 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1147 } else {
1148 strbuf_addbuf(&sb, msg);
1149 strbuf_addch(&sb, '\n');
1152 transaction = ref_transaction_begin(err);
1153 if (!transaction ||
1154 ref_transaction_update(transaction, "HEAD", new_head,
1155 old_head ? &old_head->object.oid : null_oid(),
1156 0, sb.buf, err) ||
1157 ref_transaction_commit(transaction, err)) {
1158 ret = -1;
1160 ref_transaction_free(transaction);
1161 strbuf_release(&sb);
1163 return ret;
1166 static int run_rewrite_hook(const struct object_id *oldoid,
1167 const struct object_id *newoid)
1169 struct child_process proc = CHILD_PROCESS_INIT;
1170 int code;
1171 struct strbuf sb = STRBUF_INIT;
1172 const char *hook_path = find_hook("post-rewrite");
1174 if (!hook_path)
1175 return 0;
1177 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1178 proc.in = -1;
1179 proc.stdout_to_stderr = 1;
1180 proc.trace2_hook_name = "post-rewrite";
1182 code = start_command(&proc);
1183 if (code)
1184 return code;
1185 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1186 sigchain_push(SIGPIPE, SIG_IGN);
1187 write_in_full(proc.in, sb.buf, sb.len);
1188 close(proc.in);
1189 strbuf_release(&sb);
1190 sigchain_pop(SIGPIPE);
1191 return finish_command(&proc);
1194 void commit_post_rewrite(struct repository *r,
1195 const struct commit *old_head,
1196 const struct object_id *new_head)
1198 struct notes_rewrite_cfg *cfg;
1200 cfg = init_copy_notes_for_rewrite("amend");
1201 if (cfg) {
1202 /* we are amending, so old_head is not NULL */
1203 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1204 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1206 run_rewrite_hook(&old_head->object.oid, new_head);
1209 static int run_prepare_commit_msg_hook(struct repository *r,
1210 struct strbuf *msg,
1211 const char *commit)
1213 int ret = 0;
1214 const char *name, *arg1 = NULL, *arg2 = NULL;
1216 name = git_path_commit_editmsg();
1217 if (write_message(msg->buf, msg->len, name, 0))
1218 return -1;
1220 if (commit) {
1221 arg1 = "commit";
1222 arg2 = commit;
1223 } else {
1224 arg1 = "message";
1226 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1227 arg1, arg2, NULL))
1228 ret = error(_("'prepare-commit-msg' hook failed"));
1230 return ret;
1233 static const char implicit_ident_advice_noconfig[] =
1234 N_("Your name and email address were configured automatically based\n"
1235 "on your username and hostname. Please check that they are accurate.\n"
1236 "You can suppress this message by setting them explicitly. Run the\n"
1237 "following command and follow the instructions in your editor to edit\n"
1238 "your configuration file:\n"
1239 "\n"
1240 " git config --global --edit\n"
1241 "\n"
1242 "After doing this, you may fix the identity used for this commit with:\n"
1243 "\n"
1244 " git commit --amend --reset-author\n");
1246 static const char implicit_ident_advice_config[] =
1247 N_("Your name and email address were configured automatically based\n"
1248 "on your username and hostname. Please check that they are accurate.\n"
1249 "You can suppress this message by setting them explicitly:\n"
1250 "\n"
1251 " git config --global user.name \"Your Name\"\n"
1252 " git config --global user.email you@example.com\n"
1253 "\n"
1254 "After doing this, you may fix the identity used for this commit with:\n"
1255 "\n"
1256 " git commit --amend --reset-author\n");
1258 static const char *implicit_ident_advice(void)
1260 char *user_config = interpolate_path("~/.gitconfig", 0);
1261 char *xdg_config = xdg_config_home("config");
1262 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1264 free(user_config);
1265 free(xdg_config);
1267 if (config_exists)
1268 return _(implicit_ident_advice_config);
1269 else
1270 return _(implicit_ident_advice_noconfig);
1274 void print_commit_summary(struct repository *r,
1275 const char *prefix,
1276 const struct object_id *oid,
1277 unsigned int flags)
1279 struct rev_info rev;
1280 struct commit *commit;
1281 struct strbuf format = STRBUF_INIT;
1282 const char *head;
1283 struct pretty_print_context pctx = {0};
1284 struct strbuf author_ident = STRBUF_INIT;
1285 struct strbuf committer_ident = STRBUF_INIT;
1286 struct ref_store *refs;
1288 commit = lookup_commit(r, oid);
1289 if (!commit)
1290 die(_("couldn't look up newly created commit"));
1291 if (parse_commit(commit))
1292 die(_("could not parse newly created commit"));
1294 strbuf_addstr(&format, "format:%h] %s");
1296 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1297 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1298 if (strbuf_cmp(&author_ident, &committer_ident)) {
1299 strbuf_addstr(&format, "\n Author: ");
1300 strbuf_addbuf_percentquote(&format, &author_ident);
1302 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1303 struct strbuf date = STRBUF_INIT;
1305 format_commit_message(commit, "%ad", &date, &pctx);
1306 strbuf_addstr(&format, "\n Date: ");
1307 strbuf_addbuf_percentquote(&format, &date);
1308 strbuf_release(&date);
1310 if (!committer_ident_sufficiently_given()) {
1311 strbuf_addstr(&format, "\n Committer: ");
1312 strbuf_addbuf_percentquote(&format, &committer_ident);
1313 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1314 strbuf_addch(&format, '\n');
1315 strbuf_addstr(&format, implicit_ident_advice());
1318 strbuf_release(&author_ident);
1319 strbuf_release(&committer_ident);
1321 repo_init_revisions(r, &rev, prefix);
1322 setup_revisions(0, NULL, &rev, NULL);
1324 rev.diff = 1;
1325 rev.diffopt.output_format =
1326 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1328 rev.verbose_header = 1;
1329 rev.show_root_diff = 1;
1330 get_commit_format(format.buf, &rev);
1331 rev.always_show_header = 0;
1332 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1333 rev.diffopt.break_opt = 0;
1334 diff_setup_done(&rev.diffopt);
1336 refs = get_main_ref_store(the_repository);
1337 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1338 if (!head)
1339 die(_("unable to resolve HEAD after creating commit"));
1340 if (!strcmp(head, "HEAD"))
1341 head = _("detached HEAD");
1342 else
1343 skip_prefix(head, "refs/heads/", &head);
1344 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1345 _(" (root-commit)") : "");
1347 if (!log_tree_commit(&rev, commit)) {
1348 rev.always_show_header = 1;
1349 rev.use_terminator = 1;
1350 log_tree_commit(&rev, commit);
1353 strbuf_release(&format);
1356 static int parse_head(struct repository *r, struct commit **head)
1358 struct commit *current_head;
1359 struct object_id oid;
1361 if (get_oid("HEAD", &oid)) {
1362 current_head = NULL;
1363 } else {
1364 current_head = lookup_commit_reference(r, &oid);
1365 if (!current_head)
1366 return error(_("could not parse HEAD"));
1367 if (!oideq(&oid, &current_head->object.oid)) {
1368 warning(_("HEAD %s is not a commit!"),
1369 oid_to_hex(&oid));
1371 if (parse_commit(current_head))
1372 return error(_("could not parse HEAD commit"));
1374 *head = current_head;
1376 return 0;
1380 * Try to commit without forking 'git commit'. In some cases we need
1381 * to run 'git commit' to display an error message
1383 * Returns:
1384 * -1 - error unable to commit
1385 * 0 - success
1386 * 1 - run 'git commit'
1388 static int try_to_commit(struct repository *r,
1389 struct strbuf *msg, const char *author,
1390 struct replay_opts *opts, unsigned int flags,
1391 struct object_id *oid)
1393 struct object_id tree;
1394 struct commit *current_head = NULL;
1395 struct commit_list *parents = NULL;
1396 struct commit_extra_header *extra = NULL;
1397 struct strbuf err = STRBUF_INIT;
1398 struct strbuf commit_msg = STRBUF_INIT;
1399 char *amend_author = NULL;
1400 const char *committer = NULL;
1401 const char *hook_commit = NULL;
1402 enum commit_msg_cleanup_mode cleanup;
1403 int res = 0;
1405 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1406 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1408 if (parse_head(r, &current_head))
1409 return -1;
1411 if (flags & AMEND_MSG) {
1412 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1413 const char *out_enc = get_commit_output_encoding();
1414 const char *message = logmsg_reencode(current_head, NULL,
1415 out_enc);
1417 if (!msg) {
1418 const char *orig_message = NULL;
1420 find_commit_subject(message, &orig_message);
1421 msg = &commit_msg;
1422 strbuf_addstr(msg, orig_message);
1423 hook_commit = "HEAD";
1425 author = amend_author = get_author(message);
1426 unuse_commit_buffer(current_head, message);
1427 if (!author) {
1428 res = error(_("unable to parse commit author"));
1429 goto out;
1431 parents = copy_commit_list(current_head->parents);
1432 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1433 } else if (current_head &&
1434 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1435 commit_list_insert(current_head, &parents);
1438 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1439 res = error(_("git write-tree failed to write a tree"));
1440 goto out;
1443 if (!(flags & ALLOW_EMPTY)) {
1444 struct commit *first_parent = current_head;
1446 if (flags & AMEND_MSG) {
1447 if (current_head->parents) {
1448 first_parent = current_head->parents->item;
1449 if (repo_parse_commit(r, first_parent)) {
1450 res = error(_("could not parse HEAD commit"));
1451 goto out;
1453 } else {
1454 first_parent = NULL;
1457 if (oideq(first_parent
1458 ? get_commit_tree_oid(first_parent)
1459 : the_hash_algo->empty_tree,
1460 &tree)) {
1461 res = 1; /* run 'git commit' to display error message */
1462 goto out;
1466 if (hook_exists("prepare-commit-msg")) {
1467 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1468 if (res)
1469 goto out;
1470 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1471 2048) < 0) {
1472 res = error_errno(_("unable to read commit message "
1473 "from '%s'"),
1474 git_path_commit_editmsg());
1475 goto out;
1477 msg = &commit_msg;
1480 if (flags & CLEANUP_MSG)
1481 cleanup = COMMIT_MSG_CLEANUP_ALL;
1482 else if (flags & VERBATIM_MSG)
1483 cleanup = COMMIT_MSG_CLEANUP_NONE;
1484 else if ((opts->signoff || opts->record_origin) &&
1485 !opts->explicit_cleanup)
1486 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1487 else
1488 cleanup = opts->default_msg_cleanup;
1490 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1491 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1492 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1493 res = 1; /* run 'git commit' to display error message */
1494 goto out;
1497 if (opts->committer_date_is_author_date) {
1498 struct ident_split id;
1499 struct strbuf date = STRBUF_INIT;
1501 if (!opts->ignore_date) {
1502 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1503 res = error(_("invalid author identity '%s'"),
1504 author);
1505 goto out;
1507 if (!id.date_begin) {
1508 res = error(_(
1509 "corrupt author: missing date information"));
1510 goto out;
1512 strbuf_addf(&date, "@%.*s %.*s",
1513 (int)(id.date_end - id.date_begin),
1514 id.date_begin,
1515 (int)(id.tz_end - id.tz_begin),
1516 id.tz_begin);
1517 } else {
1518 reset_ident_date();
1520 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1521 getenv("GIT_COMMITTER_EMAIL"),
1522 WANT_COMMITTER_IDENT,
1523 opts->ignore_date ? NULL : date.buf,
1524 IDENT_STRICT);
1525 strbuf_release(&date);
1526 } else {
1527 reset_ident_date();
1530 if (opts->ignore_date) {
1531 struct ident_split id;
1532 char *name, *email;
1534 if (split_ident_line(&id, author, strlen(author)) < 0) {
1535 error(_("invalid author identity '%s'"), author);
1536 goto out;
1538 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1539 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1540 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1541 IDENT_STRICT);
1542 free(name);
1543 free(email);
1546 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1547 author, committer, opts->gpg_sign, extra)) {
1548 res = error(_("failed to write commit object"));
1549 goto out;
1552 if (update_head_with_reflog(current_head, oid,
1553 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1554 res = error("%s", err.buf);
1555 goto out;
1558 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1559 if (flags & AMEND_MSG)
1560 commit_post_rewrite(r, current_head, oid);
1562 out:
1563 free_commit_extra_headers(extra);
1564 strbuf_release(&err);
1565 strbuf_release(&commit_msg);
1566 free(amend_author);
1568 return res;
1571 static int write_rebase_head(struct object_id *oid)
1573 if (update_ref("rebase", "REBASE_HEAD", oid,
1574 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1575 return error(_("could not update %s"), "REBASE_HEAD");
1577 return 0;
1580 static int do_commit(struct repository *r,
1581 const char *msg_file, const char *author,
1582 struct replay_opts *opts, unsigned int flags,
1583 struct object_id *oid)
1585 int res = 1;
1587 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1588 struct object_id oid;
1589 struct strbuf sb = STRBUF_INIT;
1591 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1592 return error_errno(_("unable to read commit message "
1593 "from '%s'"),
1594 msg_file);
1596 res = try_to_commit(r, msg_file ? &sb : NULL,
1597 author, opts, flags, &oid);
1598 strbuf_release(&sb);
1599 if (!res) {
1600 refs_delete_ref(get_main_ref_store(r), "",
1601 "CHERRY_PICK_HEAD", NULL, 0);
1602 unlink(git_path_merge_msg(r));
1603 if (!is_rebase_i(opts))
1604 print_commit_summary(r, NULL, &oid,
1605 SUMMARY_SHOW_AUTHOR_DATE);
1606 return res;
1609 if (res == 1) {
1610 if (is_rebase_i(opts) && oid)
1611 if (write_rebase_head(oid))
1612 return -1;
1613 return run_git_commit(msg_file, opts, flags);
1616 return res;
1619 static int is_original_commit_empty(struct commit *commit)
1621 const struct object_id *ptree_oid;
1623 if (parse_commit(commit))
1624 return error(_("could not parse commit %s"),
1625 oid_to_hex(&commit->object.oid));
1626 if (commit->parents) {
1627 struct commit *parent = commit->parents->item;
1628 if (parse_commit(parent))
1629 return error(_("could not parse parent commit %s"),
1630 oid_to_hex(&parent->object.oid));
1631 ptree_oid = get_commit_tree_oid(parent);
1632 } else {
1633 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1636 return oideq(ptree_oid, get_commit_tree_oid(commit));
1640 * Should empty commits be allowed? Return status:
1641 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1642 * 0: Halt on empty commit
1643 * 1: Allow empty commit
1644 * 2: Drop empty commit
1646 static int allow_empty(struct repository *r,
1647 struct replay_opts *opts,
1648 struct commit *commit)
1650 int index_unchanged, originally_empty;
1653 * Four cases:
1655 * (1) we do not allow empty at all and error out.
1657 * (2) we allow ones that were initially empty, and
1658 * just drop the ones that become empty
1660 * (3) we allow ones that were initially empty, but
1661 * halt for the ones that become empty;
1663 * (4) we allow both.
1665 if (!opts->allow_empty)
1666 return 0; /* let "git commit" barf as necessary */
1668 index_unchanged = is_index_unchanged(r);
1669 if (index_unchanged < 0)
1670 return index_unchanged;
1671 if (!index_unchanged)
1672 return 0; /* we do not have to say --allow-empty */
1674 if (opts->keep_redundant_commits)
1675 return 1;
1677 originally_empty = is_original_commit_empty(commit);
1678 if (originally_empty < 0)
1679 return originally_empty;
1680 if (originally_empty)
1681 return 1;
1682 else if (opts->drop_redundant_commits)
1683 return 2;
1684 else
1685 return 0;
1688 static struct {
1689 char c;
1690 const char *str;
1691 } todo_command_info[] = {
1692 { 'p', "pick" },
1693 { 0, "revert" },
1694 { 'e', "edit" },
1695 { 'r', "reword" },
1696 { 'f', "fixup" },
1697 { 's', "squash" },
1698 { 'x', "exec" },
1699 { 'b', "break" },
1700 { 'l', "label" },
1701 { 't', "reset" },
1702 { 'm', "merge" },
1703 { 0, "noop" },
1704 { 'd', "drop" },
1705 { 0, NULL }
1708 static const char *command_to_string(const enum todo_command command)
1710 if (command < TODO_COMMENT)
1711 return todo_command_info[command].str;
1712 die(_("unknown command: %d"), command);
1715 static char command_to_char(const enum todo_command command)
1717 if (command < TODO_COMMENT)
1718 return todo_command_info[command].c;
1719 return comment_line_char;
1722 static int is_noop(const enum todo_command command)
1724 return TODO_NOOP <= command;
1727 static int is_fixup(enum todo_command command)
1729 return command == TODO_FIXUP || command == TODO_SQUASH;
1732 /* Does this command create a (non-merge) commit? */
1733 static int is_pick_or_similar(enum todo_command command)
1735 switch (command) {
1736 case TODO_PICK:
1737 case TODO_REVERT:
1738 case TODO_EDIT:
1739 case TODO_REWORD:
1740 case TODO_FIXUP:
1741 case TODO_SQUASH:
1742 return 1;
1743 default:
1744 return 0;
1748 enum todo_item_flags {
1749 TODO_EDIT_MERGE_MSG = (1 << 0),
1750 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1751 TODO_EDIT_FIXUP_MSG = (1 << 2),
1754 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1755 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1756 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1757 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1758 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1760 static int is_fixup_flag(enum todo_command command, unsigned flag)
1762 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1763 (flag & TODO_EDIT_FIXUP_MSG));
1767 * Wrapper around strbuf_add_commented_lines() which avoids double
1768 * commenting commit subjects.
1770 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1772 const char *s = str;
1773 while (len > 0 && s[0] == comment_line_char) {
1774 size_t count;
1775 const char *n = memchr(s, '\n', len);
1776 if (!n)
1777 count = len;
1778 else
1779 count = n - s + 1;
1780 strbuf_add(buf, s, count);
1781 s += count;
1782 len -= count;
1784 strbuf_add_commented_lines(buf, s, len);
1787 /* Does the current fixup chain contain a squash command? */
1788 static int seen_squash(struct replay_opts *opts)
1790 return starts_with(opts->current_fixups.buf, "squash") ||
1791 strstr(opts->current_fixups.buf, "\nsquash");
1794 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1796 strbuf_setlen(buf1, 2);
1797 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1798 strbuf_addch(buf1, '\n');
1799 strbuf_setlen(buf2, 2);
1800 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1801 strbuf_addch(buf2, '\n');
1805 * Comment out any un-commented commit messages, updating the message comments
1806 * to say they will be skipped but do not comment out the empty lines that
1807 * surround commit messages and their comments.
1809 static void update_squash_message_for_fixup(struct strbuf *msg)
1811 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1812 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1813 const char *s, *start;
1814 char *orig_msg;
1815 size_t orig_msg_len;
1816 int i = 1;
1818 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1819 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1820 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1821 while (s) {
1822 const char *next;
1823 size_t off;
1824 if (skip_prefix(s, buf1.buf, &next)) {
1826 * Copy the last message, preserving the blank line
1827 * preceding the current line
1829 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1830 copy_lines(msg, start, s - start - off);
1831 if (off)
1832 strbuf_addch(msg, '\n');
1834 * The next message needs to be commented out but the
1835 * message header is already commented out so just copy
1836 * it and the blank line that follows it.
1838 strbuf_addbuf(msg, &buf2);
1839 if (*next == '\n')
1840 strbuf_addch(msg, *next++);
1841 start = s = next;
1842 copy_lines = add_commented_lines;
1843 update_comment_bufs(&buf1, &buf2, ++i);
1844 } else if (skip_prefix(s, buf2.buf, &next)) {
1845 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1846 copy_lines(msg, start, s - start - off);
1847 start = s - off;
1848 s = next;
1849 copy_lines = strbuf_add;
1850 update_comment_bufs(&buf1, &buf2, ++i);
1851 } else {
1852 s = strchr(s, '\n');
1853 if (s)
1854 s++;
1857 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1858 free(orig_msg);
1859 strbuf_release(&buf1);
1860 strbuf_release(&buf2);
1863 static int append_squash_message(struct strbuf *buf, const char *body,
1864 enum todo_command command, struct replay_opts *opts,
1865 unsigned flag)
1867 const char *fixup_msg;
1868 size_t commented_len = 0, fixup_off;
1870 * amend is non-interactive and not normally used with fixup!
1871 * or squash! commits, so only comment out those subjects when
1872 * squashing commit messages.
1874 if (starts_with(body, "amend!") ||
1875 ((command == TODO_SQUASH || seen_squash(opts)) &&
1876 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1877 commented_len = commit_subject_length(body);
1879 strbuf_addf(buf, "\n%c ", comment_line_char);
1880 strbuf_addf(buf, _(nth_commit_msg_fmt),
1881 ++opts->current_fixup_count + 1);
1882 strbuf_addstr(buf, "\n\n");
1883 strbuf_add_commented_lines(buf, body, commented_len);
1884 /* buf->buf may be reallocated so store an offset into the buffer */
1885 fixup_off = buf->len;
1886 strbuf_addstr(buf, body + commented_len);
1888 /* fixup -C after squash behaves like squash */
1889 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1891 * We're replacing the commit message so we need to
1892 * append the Signed-off-by: trailer if the user
1893 * requested '--signoff'.
1895 if (opts->signoff)
1896 append_signoff(buf, 0, 0);
1898 if ((command == TODO_FIXUP) &&
1899 (flag & TODO_REPLACE_FIXUP_MSG) &&
1900 (file_exists(rebase_path_fixup_msg()) ||
1901 !file_exists(rebase_path_squash_msg()))) {
1902 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1903 if (write_message(fixup_msg, strlen(fixup_msg),
1904 rebase_path_fixup_msg(), 0) < 0)
1905 return error(_("cannot write '%s'"),
1906 rebase_path_fixup_msg());
1907 } else {
1908 unlink(rebase_path_fixup_msg());
1910 } else {
1911 unlink(rebase_path_fixup_msg());
1914 return 0;
1917 static int update_squash_messages(struct repository *r,
1918 enum todo_command command,
1919 struct commit *commit,
1920 struct replay_opts *opts,
1921 unsigned flag)
1923 struct strbuf buf = STRBUF_INIT;
1924 int res = 0;
1925 const char *message, *body;
1926 const char *encoding = get_commit_output_encoding();
1928 if (opts->current_fixup_count > 0) {
1929 struct strbuf header = STRBUF_INIT;
1930 char *eol;
1932 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1933 return error(_("could not read '%s'"),
1934 rebase_path_squash_msg());
1936 eol = buf.buf[0] != comment_line_char ?
1937 buf.buf : strchrnul(buf.buf, '\n');
1939 strbuf_addf(&header, "%c ", comment_line_char);
1940 strbuf_addf(&header, _(combined_commit_msg_fmt),
1941 opts->current_fixup_count + 2);
1942 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1943 strbuf_release(&header);
1944 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1945 update_squash_message_for_fixup(&buf);
1946 } else {
1947 struct object_id head;
1948 struct commit *head_commit;
1949 const char *head_message, *body;
1951 if (get_oid("HEAD", &head))
1952 return error(_("need a HEAD to fixup"));
1953 if (!(head_commit = lookup_commit_reference(r, &head)))
1954 return error(_("could not read HEAD"));
1955 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1956 return error(_("could not read HEAD's commit message"));
1958 find_commit_subject(head_message, &body);
1959 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1960 rebase_path_fixup_msg(), 0) < 0) {
1961 unuse_commit_buffer(head_commit, head_message);
1962 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1964 strbuf_addf(&buf, "%c ", comment_line_char);
1965 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1966 strbuf_addf(&buf, "\n%c ", comment_line_char);
1967 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1968 _(skip_first_commit_msg_str) :
1969 _(first_commit_msg_str));
1970 strbuf_addstr(&buf, "\n\n");
1971 if (is_fixup_flag(command, flag))
1972 strbuf_add_commented_lines(&buf, body, strlen(body));
1973 else
1974 strbuf_addstr(&buf, body);
1976 unuse_commit_buffer(head_commit, head_message);
1979 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1980 return error(_("could not read commit message of %s"),
1981 oid_to_hex(&commit->object.oid));
1982 find_commit_subject(message, &body);
1984 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1985 res = append_squash_message(&buf, body, command, opts, flag);
1986 } else if (command == TODO_FIXUP) {
1987 strbuf_addf(&buf, "\n%c ", comment_line_char);
1988 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1989 ++opts->current_fixup_count + 1);
1990 strbuf_addstr(&buf, "\n\n");
1991 strbuf_add_commented_lines(&buf, body, strlen(body));
1992 } else
1993 return error(_("unknown command: %d"), command);
1994 unuse_commit_buffer(commit, message);
1996 if (!res)
1997 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1999 strbuf_release(&buf);
2001 if (!res) {
2002 strbuf_addf(&opts->current_fixups, "%s%s %s",
2003 opts->current_fixups.len ? "\n" : "",
2004 command_to_string(command),
2005 oid_to_hex(&commit->object.oid));
2006 res = write_message(opts->current_fixups.buf,
2007 opts->current_fixups.len,
2008 rebase_path_current_fixups(), 0);
2011 return res;
2014 static void flush_rewritten_pending(void)
2016 struct strbuf buf = STRBUF_INIT;
2017 struct object_id newoid;
2018 FILE *out;
2020 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2021 !get_oid("HEAD", &newoid) &&
2022 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2023 char *bol = buf.buf, *eol;
2025 while (*bol) {
2026 eol = strchrnul(bol, '\n');
2027 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2028 bol, oid_to_hex(&newoid));
2029 if (!*eol)
2030 break;
2031 bol = eol + 1;
2033 fclose(out);
2034 unlink(rebase_path_rewritten_pending());
2036 strbuf_release(&buf);
2039 static void record_in_rewritten(struct object_id *oid,
2040 enum todo_command next_command)
2042 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2044 if (!out)
2045 return;
2047 fprintf(out, "%s\n", oid_to_hex(oid));
2048 fclose(out);
2050 if (!is_fixup(next_command))
2051 flush_rewritten_pending();
2054 static int should_edit(struct replay_opts *opts) {
2055 if (opts->edit < 0)
2057 * Note that we only handle the case of non-conflicted
2058 * commits; continue_single_pick() handles the conflicted
2059 * commits itself instead of calling this function.
2061 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2062 return opts->edit;
2065 static void refer_to_commit(struct replay_opts *opts,
2066 struct strbuf *msgbuf, struct commit *commit)
2068 if (opts->commit_use_reference) {
2069 struct pretty_print_context ctx = {
2070 .abbrev = DEFAULT_ABBREV,
2071 .date_mode.type = DATE_SHORT,
2073 format_commit_message(commit, "%h (%s, %ad)", msgbuf, &ctx);
2074 } else {
2075 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2079 static int do_pick_commit(struct repository *r,
2080 struct todo_item *item,
2081 struct replay_opts *opts,
2082 int final_fixup, int *check_todo)
2084 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2085 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2086 struct object_id head;
2087 struct commit *base, *next, *parent;
2088 const char *base_label, *next_label;
2089 char *author = NULL;
2090 struct commit_message msg = { NULL, NULL, NULL, NULL };
2091 struct strbuf msgbuf = STRBUF_INIT;
2092 int res, unborn = 0, reword = 0, allow, drop_commit;
2093 enum todo_command command = item->command;
2094 struct commit *commit = item->commit;
2096 if (opts->no_commit) {
2098 * We do not intend to commit immediately. We just want to
2099 * merge the differences in, so let's compute the tree
2100 * that represents the "current" state for the merge machinery
2101 * to work on.
2103 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2104 return error(_("your index file is unmerged."));
2105 } else {
2106 unborn = get_oid("HEAD", &head);
2107 /* Do we want to generate a root commit? */
2108 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2109 oideq(&head, &opts->squash_onto)) {
2110 if (is_fixup(command))
2111 return error(_("cannot fixup root commit"));
2112 flags |= CREATE_ROOT_COMMIT;
2113 unborn = 1;
2114 } else if (unborn)
2115 oidcpy(&head, the_hash_algo->empty_tree);
2116 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2117 NULL, 0))
2118 return error_dirty_index(r, opts);
2120 discard_index(r->index);
2122 if (!commit->parents)
2123 parent = NULL;
2124 else if (commit->parents->next) {
2125 /* Reverting or cherry-picking a merge commit */
2126 int cnt;
2127 struct commit_list *p;
2129 if (!opts->mainline)
2130 return error(_("commit %s is a merge but no -m option was given."),
2131 oid_to_hex(&commit->object.oid));
2133 for (cnt = 1, p = commit->parents;
2134 cnt != opts->mainline && p;
2135 cnt++)
2136 p = p->next;
2137 if (cnt != opts->mainline || !p)
2138 return error(_("commit %s does not have parent %d"),
2139 oid_to_hex(&commit->object.oid), opts->mainline);
2140 parent = p->item;
2141 } else if (1 < opts->mainline)
2143 * Non-first parent explicitly specified as mainline for
2144 * non-merge commit
2146 return error(_("commit %s does not have parent %d"),
2147 oid_to_hex(&commit->object.oid), opts->mainline);
2148 else
2149 parent = commit->parents->item;
2151 if (get_message(commit, &msg) != 0)
2152 return error(_("cannot get commit message for %s"),
2153 oid_to_hex(&commit->object.oid));
2155 if (opts->allow_ff && !is_fixup(command) &&
2156 ((parent && oideq(&parent->object.oid, &head)) ||
2157 (!parent && unborn))) {
2158 if (is_rebase_i(opts))
2159 write_author_script(msg.message);
2160 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2161 opts);
2162 if (res || command != TODO_REWORD)
2163 goto leave;
2164 reword = 1;
2165 msg_file = NULL;
2166 goto fast_forward_edit;
2168 if (parent && parse_commit(parent) < 0)
2169 /* TRANSLATORS: The first %s will be a "todo" command like
2170 "revert" or "pick", the second %s a SHA1. */
2171 return error(_("%s: cannot parse parent commit %s"),
2172 command_to_string(command),
2173 oid_to_hex(&parent->object.oid));
2176 * "commit" is an existing commit. We would want to apply
2177 * the difference it introduces since its first parent "prev"
2178 * on top of the current HEAD if we are cherry-pick. Or the
2179 * reverse of it if we are revert.
2182 if (command == TODO_REVERT) {
2183 base = commit;
2184 base_label = msg.label;
2185 next = parent;
2186 next_label = msg.parent_label;
2187 if (opts->commit_use_reference) {
2188 strbuf_addstr(&msgbuf,
2189 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2190 } else {
2191 strbuf_addstr(&msgbuf, "Revert \"");
2192 strbuf_addstr(&msgbuf, msg.subject);
2193 strbuf_addstr(&msgbuf, "\"");
2195 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2196 refer_to_commit(opts, &msgbuf, commit);
2198 if (commit->parents && commit->parents->next) {
2199 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2200 refer_to_commit(opts, &msgbuf, parent);
2202 strbuf_addstr(&msgbuf, ".\n");
2203 } else {
2204 const char *p;
2206 base = parent;
2207 base_label = msg.parent_label;
2208 next = commit;
2209 next_label = msg.label;
2211 /* Append the commit log message to msgbuf. */
2212 if (find_commit_subject(msg.message, &p))
2213 strbuf_addstr(&msgbuf, p);
2215 if (opts->record_origin) {
2216 strbuf_complete_line(&msgbuf);
2217 if (!has_conforming_footer(&msgbuf, NULL, 0))
2218 strbuf_addch(&msgbuf, '\n');
2219 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2220 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2221 strbuf_addstr(&msgbuf, ")\n");
2223 if (!is_fixup(command))
2224 author = get_author(msg.message);
2227 if (command == TODO_REWORD)
2228 reword = 1;
2229 else if (is_fixup(command)) {
2230 if (update_squash_messages(r, command, commit,
2231 opts, item->flags))
2232 return -1;
2233 flags |= AMEND_MSG;
2234 if (!final_fixup)
2235 msg_file = rebase_path_squash_msg();
2236 else if (file_exists(rebase_path_fixup_msg())) {
2237 flags |= VERBATIM_MSG;
2238 msg_file = rebase_path_fixup_msg();
2239 } else {
2240 const char *dest = git_path_squash_msg(r);
2241 unlink(dest);
2242 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2243 return error(_("could not rename '%s' to '%s'"),
2244 rebase_path_squash_msg(), dest);
2245 unlink(git_path_merge_msg(r));
2246 msg_file = dest;
2247 flags |= EDIT_MSG;
2251 if (opts->signoff && !is_fixup(command))
2252 append_signoff(&msgbuf, 0, 0);
2254 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2255 res = -1;
2256 else if (!opts->strategy ||
2257 !strcmp(opts->strategy, "recursive") ||
2258 !strcmp(opts->strategy, "ort") ||
2259 command == TODO_REVERT) {
2260 res = do_recursive_merge(r, base, next, base_label, next_label,
2261 &head, &msgbuf, opts);
2262 if (res < 0)
2263 goto leave;
2265 res |= write_message(msgbuf.buf, msgbuf.len,
2266 git_path_merge_msg(r), 0);
2267 } else {
2268 struct commit_list *common = NULL;
2269 struct commit_list *remotes = NULL;
2271 res = write_message(msgbuf.buf, msgbuf.len,
2272 git_path_merge_msg(r), 0);
2274 commit_list_insert(base, &common);
2275 commit_list_insert(next, &remotes);
2276 res |= try_merge_command(r, opts->strategy,
2277 opts->xopts_nr, (const char **)opts->xopts,
2278 common, oid_to_hex(&head), remotes);
2279 free_commit_list(common);
2280 free_commit_list(remotes);
2282 strbuf_release(&msgbuf);
2285 * If the merge was clean or if it failed due to conflict, we write
2286 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2287 * However, if the merge did not even start, then we don't want to
2288 * write it at all.
2290 if ((command == TODO_PICK || command == TODO_REWORD ||
2291 command == TODO_EDIT) && !opts->no_commit &&
2292 (res == 0 || res == 1) &&
2293 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2294 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2295 res = -1;
2296 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2297 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2298 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2299 res = -1;
2301 if (res) {
2302 error(command == TODO_REVERT
2303 ? _("could not revert %s... %s")
2304 : _("could not apply %s... %s"),
2305 short_commit_name(commit), msg.subject);
2306 print_advice(r, res == 1, opts);
2307 repo_rerere(r, opts->allow_rerere_auto);
2308 goto leave;
2311 drop_commit = 0;
2312 allow = allow_empty(r, opts, commit);
2313 if (allow < 0) {
2314 res = allow;
2315 goto leave;
2316 } else if (allow == 1) {
2317 flags |= ALLOW_EMPTY;
2318 } else if (allow == 2) {
2319 drop_commit = 1;
2320 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2321 NULL, 0);
2322 unlink(git_path_merge_msg(r));
2323 unlink(git_path_auto_merge(r));
2324 fprintf(stderr,
2325 _("dropping %s %s -- patch contents already upstream\n"),
2326 oid_to_hex(&commit->object.oid), msg.subject);
2327 } /* else allow == 0 and there's nothing special to do */
2328 if (!opts->no_commit && !drop_commit) {
2329 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2330 res = do_commit(r, msg_file, author, opts, flags,
2331 commit? &commit->object.oid : NULL);
2332 else
2333 res = error(_("unable to parse commit author"));
2334 *check_todo = !!(flags & EDIT_MSG);
2335 if (!res && reword) {
2336 fast_forward_edit:
2337 res = run_git_commit(NULL, opts, EDIT_MSG |
2338 VERIFY_MSG | AMEND_MSG |
2339 (flags & ALLOW_EMPTY));
2340 *check_todo = 1;
2345 if (!res && final_fixup) {
2346 unlink(rebase_path_fixup_msg());
2347 unlink(rebase_path_squash_msg());
2348 unlink(rebase_path_current_fixups());
2349 strbuf_reset(&opts->current_fixups);
2350 opts->current_fixup_count = 0;
2353 leave:
2354 free_message(commit, &msg);
2355 free(author);
2356 update_abort_safety_file();
2358 return res;
2361 static int prepare_revs(struct replay_opts *opts)
2364 * picking (but not reverting) ranges (but not individual revisions)
2365 * should be done in reverse
2367 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2368 opts->revs->reverse ^= 1;
2370 if (prepare_revision_walk(opts->revs))
2371 return error(_("revision walk setup failed"));
2373 return 0;
2376 static int read_and_refresh_cache(struct repository *r,
2377 struct replay_opts *opts)
2379 struct lock_file index_lock = LOCK_INIT;
2380 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2381 if (repo_read_index(r) < 0) {
2382 rollback_lock_file(&index_lock);
2383 return error(_("git %s: failed to read the index"),
2384 _(action_name(opts)));
2386 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2388 if (index_fd >= 0) {
2389 if (write_locked_index(r->index, &index_lock,
2390 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2391 return error(_("git %s: failed to refresh the index"),
2392 _(action_name(opts)));
2397 * If we are resolving merges in any way other than "ort", then
2398 * expand the sparse index.
2400 if (opts->strategy && strcmp(opts->strategy, "ort"))
2401 ensure_full_index(r->index);
2402 return 0;
2405 void todo_list_release(struct todo_list *todo_list)
2407 strbuf_release(&todo_list->buf);
2408 FREE_AND_NULL(todo_list->items);
2409 todo_list->nr = todo_list->alloc = 0;
2412 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2414 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2415 todo_list->total_nr++;
2416 return todo_list->items + todo_list->nr++;
2419 const char *todo_item_get_arg(struct todo_list *todo_list,
2420 struct todo_item *item)
2422 return todo_list->buf.buf + item->arg_offset;
2425 static int is_command(enum todo_command command, const char **bol)
2427 const char *str = todo_command_info[command].str;
2428 const char nick = todo_command_info[command].c;
2429 const char *p = *bol + 1;
2431 return skip_prefix(*bol, str, bol) ||
2432 ((nick && **bol == nick) &&
2433 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2434 (*bol = p));
2437 static int parse_insn_line(struct repository *r, struct todo_item *item,
2438 const char *buf, const char *bol, char *eol)
2440 struct object_id commit_oid;
2441 char *end_of_object_name;
2442 int i, saved, status, padding;
2444 item->flags = 0;
2446 /* left-trim */
2447 bol += strspn(bol, " \t");
2449 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2450 item->command = TODO_COMMENT;
2451 item->commit = NULL;
2452 item->arg_offset = bol - buf;
2453 item->arg_len = eol - bol;
2454 return 0;
2457 for (i = 0; i < TODO_COMMENT; i++)
2458 if (is_command(i, &bol)) {
2459 item->command = i;
2460 break;
2462 if (i >= TODO_COMMENT)
2463 return -1;
2465 /* Eat up extra spaces/ tabs before object name */
2466 padding = strspn(bol, " \t");
2467 bol += padding;
2469 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2470 if (bol != eol)
2471 return error(_("%s does not accept arguments: '%s'"),
2472 command_to_string(item->command), bol);
2473 item->commit = NULL;
2474 item->arg_offset = bol - buf;
2475 item->arg_len = eol - bol;
2476 return 0;
2479 if (!padding)
2480 return error(_("missing arguments for %s"),
2481 command_to_string(item->command));
2483 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2484 item->command == TODO_RESET) {
2485 item->commit = NULL;
2486 item->arg_offset = bol - buf;
2487 item->arg_len = (int)(eol - bol);
2488 return 0;
2491 if (item->command == TODO_FIXUP) {
2492 if (skip_prefix(bol, "-C", &bol) &&
2493 (*bol == ' ' || *bol == '\t')) {
2494 bol += strspn(bol, " \t");
2495 item->flags |= TODO_REPLACE_FIXUP_MSG;
2496 } else if (skip_prefix(bol, "-c", &bol) &&
2497 (*bol == ' ' || *bol == '\t')) {
2498 bol += strspn(bol, " \t");
2499 item->flags |= TODO_EDIT_FIXUP_MSG;
2503 if (item->command == TODO_MERGE) {
2504 if (skip_prefix(bol, "-C", &bol))
2505 bol += strspn(bol, " \t");
2506 else if (skip_prefix(bol, "-c", &bol)) {
2507 bol += strspn(bol, " \t");
2508 item->flags |= TODO_EDIT_MERGE_MSG;
2509 } else {
2510 item->flags |= TODO_EDIT_MERGE_MSG;
2511 item->commit = NULL;
2512 item->arg_offset = bol - buf;
2513 item->arg_len = (int)(eol - bol);
2514 return 0;
2518 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2519 saved = *end_of_object_name;
2520 *end_of_object_name = '\0';
2521 status = get_oid(bol, &commit_oid);
2522 if (status < 0)
2523 error(_("could not parse '%s'"), bol); /* return later */
2524 *end_of_object_name = saved;
2526 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2527 item->arg_offset = bol - buf;
2528 item->arg_len = (int)(eol - bol);
2530 if (status < 0)
2531 return status;
2533 item->commit = lookup_commit_reference(r, &commit_oid);
2534 return item->commit ? 0 : -1;
2537 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2539 const char *todo_file, *bol;
2540 struct strbuf buf = STRBUF_INIT;
2541 int ret = 0;
2543 todo_file = git_path_todo_file();
2544 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2545 if (errno == ENOENT || errno == ENOTDIR)
2546 return -1;
2547 else
2548 return error_errno("unable to open '%s'", todo_file);
2550 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2551 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2552 *action = REPLAY_PICK;
2553 else if (is_command(TODO_REVERT, &bol) &&
2554 (*bol == ' ' || *bol == '\t'))
2555 *action = REPLAY_REVERT;
2556 else
2557 ret = -1;
2559 strbuf_release(&buf);
2561 return ret;
2564 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2565 struct todo_list *todo_list)
2567 struct todo_item *item;
2568 char *p = buf, *next_p;
2569 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2571 todo_list->current = todo_list->nr = 0;
2573 for (i = 1; *p; i++, p = next_p) {
2574 char *eol = strchrnul(p, '\n');
2576 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2578 if (p != eol && eol[-1] == '\r')
2579 eol--; /* strip Carriage Return */
2581 item = append_new_todo(todo_list);
2582 item->offset_in_buf = p - todo_list->buf.buf;
2583 if (parse_insn_line(r, item, buf, p, eol)) {
2584 res = error(_("invalid line %d: %.*s"),
2585 i, (int)(eol - p), p);
2586 item->command = TODO_COMMENT + 1;
2587 item->arg_offset = p - buf;
2588 item->arg_len = (int)(eol - p);
2589 item->commit = NULL;
2592 if (fixup_okay)
2593 ; /* do nothing */
2594 else if (is_fixup(item->command))
2595 return error(_("cannot '%s' without a previous commit"),
2596 command_to_string(item->command));
2597 else if (!is_noop(item->command))
2598 fixup_okay = 1;
2601 return res;
2604 static int count_commands(struct todo_list *todo_list)
2606 int count = 0, i;
2608 for (i = 0; i < todo_list->nr; i++)
2609 if (todo_list->items[i].command != TODO_COMMENT)
2610 count++;
2612 return count;
2615 static int get_item_line_offset(struct todo_list *todo_list, int index)
2617 return index < todo_list->nr ?
2618 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2621 static const char *get_item_line(struct todo_list *todo_list, int index)
2623 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2626 static int get_item_line_length(struct todo_list *todo_list, int index)
2628 return get_item_line_offset(todo_list, index + 1)
2629 - get_item_line_offset(todo_list, index);
2632 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2634 int fd;
2635 ssize_t len;
2637 fd = open(path, O_RDONLY);
2638 if (fd < 0)
2639 return error_errno(_("could not open '%s'"), path);
2640 len = strbuf_read(sb, fd, 0);
2641 close(fd);
2642 if (len < 0)
2643 return error(_("could not read '%s'."), path);
2644 return len;
2647 static int have_finished_the_last_pick(void)
2649 struct strbuf buf = STRBUF_INIT;
2650 const char *eol;
2651 const char *todo_path = git_path_todo_file();
2652 int ret = 0;
2654 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2655 if (errno == ENOENT) {
2656 return 0;
2657 } else {
2658 error_errno("unable to open '%s'", todo_path);
2659 return 0;
2662 /* If there is only one line then we are done */
2663 eol = strchr(buf.buf, '\n');
2664 if (!eol || !eol[1])
2665 ret = 1;
2667 strbuf_release(&buf);
2669 return ret;
2672 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2674 struct replay_opts opts = REPLAY_OPTS_INIT;
2675 int need_cleanup = 0;
2677 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2678 if (!refs_delete_ref(get_main_ref_store(r), "",
2679 "CHERRY_PICK_HEAD", NULL, 0) &&
2680 verbose)
2681 warning(_("cancelling a cherry picking in progress"));
2682 opts.action = REPLAY_PICK;
2683 need_cleanup = 1;
2686 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2687 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2688 NULL, 0) &&
2689 verbose)
2690 warning(_("cancelling a revert in progress"));
2691 opts.action = REPLAY_REVERT;
2692 need_cleanup = 1;
2695 unlink(git_path_auto_merge(r));
2697 if (!need_cleanup)
2698 return;
2700 if (!have_finished_the_last_pick())
2701 return;
2703 sequencer_remove_state(&opts);
2706 static void todo_list_write_total_nr(struct todo_list *todo_list)
2708 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2710 if (f) {
2711 fprintf(f, "%d\n", todo_list->total_nr);
2712 fclose(f);
2716 static int read_populate_todo(struct repository *r,
2717 struct todo_list *todo_list,
2718 struct replay_opts *opts)
2720 const char *todo_file = get_todo_path(opts);
2721 int res;
2723 strbuf_reset(&todo_list->buf);
2724 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2725 return -1;
2727 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2728 if (res) {
2729 if (is_rebase_i(opts))
2730 return error(_("please fix this using "
2731 "'git rebase --edit-todo'."));
2732 return error(_("unusable instruction sheet: '%s'"), todo_file);
2735 if (!todo_list->nr &&
2736 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2737 return error(_("no commits parsed."));
2739 if (!is_rebase_i(opts)) {
2740 enum todo_command valid =
2741 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2742 int i;
2744 for (i = 0; i < todo_list->nr; i++)
2745 if (valid == todo_list->items[i].command)
2746 continue;
2747 else if (valid == TODO_PICK)
2748 return error(_("cannot cherry-pick during a revert."));
2749 else
2750 return error(_("cannot revert during a cherry-pick."));
2753 if (is_rebase_i(opts)) {
2754 struct todo_list done = TODO_LIST_INIT;
2756 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2757 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2758 todo_list->done_nr = count_commands(&done);
2759 else
2760 todo_list->done_nr = 0;
2762 todo_list->total_nr = todo_list->done_nr
2763 + count_commands(todo_list);
2764 todo_list_release(&done);
2766 todo_list_write_total_nr(todo_list);
2769 return 0;
2772 static int git_config_string_dup(char **dest,
2773 const char *var, const char *value)
2775 if (!value)
2776 return config_error_nonbool(var);
2777 free(*dest);
2778 *dest = xstrdup(value);
2779 return 0;
2782 static int populate_opts_cb(const char *key, const char *value, void *data)
2784 struct replay_opts *opts = data;
2785 int error_flag = 1;
2787 if (!value)
2788 error_flag = 0;
2789 else if (!strcmp(key, "options.no-commit"))
2790 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2791 else if (!strcmp(key, "options.edit"))
2792 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2793 else if (!strcmp(key, "options.allow-empty"))
2794 opts->allow_empty =
2795 git_config_bool_or_int(key, value, &error_flag);
2796 else if (!strcmp(key, "options.allow-empty-message"))
2797 opts->allow_empty_message =
2798 git_config_bool_or_int(key, value, &error_flag);
2799 else if (!strcmp(key, "options.keep-redundant-commits"))
2800 opts->keep_redundant_commits =
2801 git_config_bool_or_int(key, value, &error_flag);
2802 else if (!strcmp(key, "options.signoff"))
2803 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2804 else if (!strcmp(key, "options.record-origin"))
2805 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2806 else if (!strcmp(key, "options.allow-ff"))
2807 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2808 else if (!strcmp(key, "options.mainline"))
2809 opts->mainline = git_config_int(key, value);
2810 else if (!strcmp(key, "options.strategy"))
2811 git_config_string_dup(&opts->strategy, key, value);
2812 else if (!strcmp(key, "options.gpg-sign"))
2813 git_config_string_dup(&opts->gpg_sign, key, value);
2814 else if (!strcmp(key, "options.strategy-option")) {
2815 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2816 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2817 } else if (!strcmp(key, "options.allow-rerere-auto"))
2818 opts->allow_rerere_auto =
2819 git_config_bool_or_int(key, value, &error_flag) ?
2820 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2821 else if (!strcmp(key, "options.default-msg-cleanup")) {
2822 opts->explicit_cleanup = 1;
2823 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2824 } else
2825 return error(_("invalid key: %s"), key);
2827 if (!error_flag)
2828 return error(_("invalid value for '%s': '%s'"), key, value);
2830 return 0;
2833 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2835 int i;
2836 char *strategy_opts_string = raw_opts;
2838 if (*strategy_opts_string == ' ')
2839 strategy_opts_string++;
2841 opts->xopts_nr = split_cmdline(strategy_opts_string,
2842 (const char ***)&opts->xopts);
2843 for (i = 0; i < opts->xopts_nr; i++) {
2844 const char *arg = opts->xopts[i];
2846 skip_prefix(arg, "--", &arg);
2847 opts->xopts[i] = xstrdup(arg);
2851 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2853 strbuf_reset(buf);
2854 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2855 return;
2856 opts->strategy = strbuf_detach(buf, NULL);
2857 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2858 return;
2860 parse_strategy_opts(opts, buf->buf);
2863 static int read_populate_opts(struct replay_opts *opts)
2865 if (is_rebase_i(opts)) {
2866 struct strbuf buf = STRBUF_INIT;
2867 int ret = 0;
2869 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2870 READ_ONELINER_SKIP_IF_EMPTY)) {
2871 if (!starts_with(buf.buf, "-S"))
2872 strbuf_reset(&buf);
2873 else {
2874 free(opts->gpg_sign);
2875 opts->gpg_sign = xstrdup(buf.buf + 2);
2877 strbuf_reset(&buf);
2880 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2881 READ_ONELINER_SKIP_IF_EMPTY)) {
2882 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2883 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2884 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2885 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2886 strbuf_reset(&buf);
2889 if (file_exists(rebase_path_verbose()))
2890 opts->verbose = 1;
2892 if (file_exists(rebase_path_quiet()))
2893 opts->quiet = 1;
2895 if (file_exists(rebase_path_signoff())) {
2896 opts->allow_ff = 0;
2897 opts->signoff = 1;
2900 if (file_exists(rebase_path_cdate_is_adate())) {
2901 opts->allow_ff = 0;
2902 opts->committer_date_is_author_date = 1;
2905 if (file_exists(rebase_path_ignore_date())) {
2906 opts->allow_ff = 0;
2907 opts->ignore_date = 1;
2910 if (file_exists(rebase_path_reschedule_failed_exec()))
2911 opts->reschedule_failed_exec = 1;
2912 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2913 opts->reschedule_failed_exec = 0;
2915 if (file_exists(rebase_path_drop_redundant_commits()))
2916 opts->drop_redundant_commits = 1;
2918 if (file_exists(rebase_path_keep_redundant_commits()))
2919 opts->keep_redundant_commits = 1;
2921 read_strategy_opts(opts, &buf);
2922 strbuf_reset(&buf);
2924 if (read_oneliner(&opts->current_fixups,
2925 rebase_path_current_fixups(),
2926 READ_ONELINER_SKIP_IF_EMPTY)) {
2927 const char *p = opts->current_fixups.buf;
2928 opts->current_fixup_count = 1;
2929 while ((p = strchr(p, '\n'))) {
2930 opts->current_fixup_count++;
2931 p++;
2935 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2936 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2937 ret = error(_("unusable squash-onto"));
2938 goto done_rebase_i;
2940 opts->have_squash_onto = 1;
2943 done_rebase_i:
2944 strbuf_release(&buf);
2945 return ret;
2948 if (!file_exists(git_path_opts_file()))
2949 return 0;
2951 * The function git_parse_source(), called from git_config_from_file(),
2952 * may die() in case of a syntactically incorrect file. We do not care
2953 * about this case, though, because we wrote that file ourselves, so we
2954 * are pretty certain that it is syntactically correct.
2956 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2957 return error(_("malformed options sheet: '%s'"),
2958 git_path_opts_file());
2959 return 0;
2962 static void write_strategy_opts(struct replay_opts *opts)
2964 int i;
2965 struct strbuf buf = STRBUF_INIT;
2967 for (i = 0; i < opts->xopts_nr; ++i)
2968 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2970 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2971 strbuf_release(&buf);
2974 int write_basic_state(struct replay_opts *opts, const char *head_name,
2975 struct commit *onto, const struct object_id *orig_head)
2977 if (head_name)
2978 write_file(rebase_path_head_name(), "%s\n", head_name);
2979 if (onto)
2980 write_file(rebase_path_onto(), "%s\n",
2981 oid_to_hex(&onto->object.oid));
2982 if (orig_head)
2983 write_file(rebase_path_orig_head(), "%s\n",
2984 oid_to_hex(orig_head));
2986 if (opts->quiet)
2987 write_file(rebase_path_quiet(), "%s", "");
2988 if (opts->verbose)
2989 write_file(rebase_path_verbose(), "%s", "");
2990 if (opts->strategy)
2991 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2992 if (opts->xopts_nr > 0)
2993 write_strategy_opts(opts);
2995 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2996 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2997 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2998 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3000 if (opts->gpg_sign)
3001 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3002 if (opts->signoff)
3003 write_file(rebase_path_signoff(), "--signoff\n");
3004 if (opts->drop_redundant_commits)
3005 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3006 if (opts->keep_redundant_commits)
3007 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3008 if (opts->committer_date_is_author_date)
3009 write_file(rebase_path_cdate_is_adate(), "%s", "");
3010 if (opts->ignore_date)
3011 write_file(rebase_path_ignore_date(), "%s", "");
3012 if (opts->reschedule_failed_exec)
3013 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3014 else
3015 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3017 return 0;
3020 static int walk_revs_populate_todo(struct todo_list *todo_list,
3021 struct replay_opts *opts)
3023 enum todo_command command = opts->action == REPLAY_PICK ?
3024 TODO_PICK : TODO_REVERT;
3025 const char *command_string = todo_command_info[command].str;
3026 const char *encoding;
3027 struct commit *commit;
3029 if (prepare_revs(opts))
3030 return -1;
3032 encoding = get_log_output_encoding();
3034 while ((commit = get_revision(opts->revs))) {
3035 struct todo_item *item = append_new_todo(todo_list);
3036 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3037 const char *subject;
3038 int subject_len;
3040 item->command = command;
3041 item->commit = commit;
3042 item->arg_offset = 0;
3043 item->arg_len = 0;
3044 item->offset_in_buf = todo_list->buf.len;
3045 subject_len = find_commit_subject(commit_buffer, &subject);
3046 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3047 short_commit_name(commit), subject_len, subject);
3048 unuse_commit_buffer(commit, commit_buffer);
3051 if (!todo_list->nr)
3052 return error(_("empty commit set passed"));
3054 return 0;
3057 static int create_seq_dir(struct repository *r)
3059 enum replay_action action;
3060 const char *in_progress_error = NULL;
3061 const char *in_progress_advice = NULL;
3062 unsigned int advise_skip =
3063 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3064 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3066 if (!sequencer_get_last_command(r, &action)) {
3067 switch (action) {
3068 case REPLAY_REVERT:
3069 in_progress_error = _("revert is already in progress");
3070 in_progress_advice =
3071 _("try \"git revert (--continue | %s--abort | --quit)\"");
3072 break;
3073 case REPLAY_PICK:
3074 in_progress_error = _("cherry-pick is already in progress");
3075 in_progress_advice =
3076 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3077 break;
3078 default:
3079 BUG("unexpected action in create_seq_dir");
3082 if (in_progress_error) {
3083 error("%s", in_progress_error);
3084 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3085 advise(in_progress_advice,
3086 advise_skip ? "--skip | " : "");
3087 return -1;
3089 if (mkdir(git_path_seq_dir(), 0777) < 0)
3090 return error_errno(_("could not create sequencer directory '%s'"),
3091 git_path_seq_dir());
3093 return 0;
3096 static int save_head(const char *head)
3098 struct lock_file head_lock = LOCK_INIT;
3099 struct strbuf buf = STRBUF_INIT;
3100 int fd;
3101 ssize_t written;
3103 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3104 if (fd < 0)
3105 return error_errno(_("could not lock HEAD"));
3106 strbuf_addf(&buf, "%s\n", head);
3107 written = write_in_full(fd, buf.buf, buf.len);
3108 strbuf_release(&buf);
3109 if (written < 0) {
3110 error_errno(_("could not write to '%s'"), git_path_head_file());
3111 rollback_lock_file(&head_lock);
3112 return -1;
3114 if (commit_lock_file(&head_lock) < 0)
3115 return error(_("failed to finalize '%s'"), git_path_head_file());
3116 return 0;
3119 static int rollback_is_safe(void)
3121 struct strbuf sb = STRBUF_INIT;
3122 struct object_id expected_head, actual_head;
3124 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3125 strbuf_trim(&sb);
3126 if (get_oid_hex(sb.buf, &expected_head)) {
3127 strbuf_release(&sb);
3128 die(_("could not parse %s"), git_path_abort_safety_file());
3130 strbuf_release(&sb);
3132 else if (errno == ENOENT)
3133 oidclr(&expected_head);
3134 else
3135 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3137 if (get_oid("HEAD", &actual_head))
3138 oidclr(&actual_head);
3140 return oideq(&actual_head, &expected_head);
3143 static int reset_merge(const struct object_id *oid)
3145 int ret;
3146 struct strvec argv = STRVEC_INIT;
3148 strvec_pushl(&argv, "reset", "--merge", NULL);
3150 if (!is_null_oid(oid))
3151 strvec_push(&argv, oid_to_hex(oid));
3153 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3154 strvec_clear(&argv);
3156 return ret;
3159 static int rollback_single_pick(struct repository *r)
3161 struct object_id head_oid;
3163 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3164 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3165 return error(_("no cherry-pick or revert in progress"));
3166 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3167 return error(_("cannot resolve HEAD"));
3168 if (is_null_oid(&head_oid))
3169 return error(_("cannot abort from a branch yet to be born"));
3170 return reset_merge(&head_oid);
3173 static int skip_single_pick(void)
3175 struct object_id head;
3177 if (read_ref_full("HEAD", 0, &head, NULL))
3178 return error(_("cannot resolve HEAD"));
3179 return reset_merge(&head);
3182 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3184 FILE *f;
3185 struct object_id oid;
3186 struct strbuf buf = STRBUF_INIT;
3187 const char *p;
3189 f = fopen(git_path_head_file(), "r");
3190 if (!f && errno == ENOENT) {
3192 * There is no multiple-cherry-pick in progress.
3193 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3194 * a single-cherry-pick in progress, abort that.
3196 return rollback_single_pick(r);
3198 if (!f)
3199 return error_errno(_("cannot open '%s'"), git_path_head_file());
3200 if (strbuf_getline_lf(&buf, f)) {
3201 error(_("cannot read '%s': %s"), git_path_head_file(),
3202 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3203 fclose(f);
3204 goto fail;
3206 fclose(f);
3207 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3208 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3209 git_path_head_file());
3210 goto fail;
3212 if (is_null_oid(&oid)) {
3213 error(_("cannot abort from a branch yet to be born"));
3214 goto fail;
3217 if (!rollback_is_safe()) {
3218 /* Do not error, just do not rollback */
3219 warning(_("You seem to have moved HEAD. "
3220 "Not rewinding, check your HEAD!"));
3221 } else
3222 if (reset_merge(&oid))
3223 goto fail;
3224 strbuf_release(&buf);
3225 return sequencer_remove_state(opts);
3226 fail:
3227 strbuf_release(&buf);
3228 return -1;
3231 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3233 enum replay_action action = -1;
3234 sequencer_get_last_command(r, &action);
3237 * Check whether the subcommand requested to skip the commit is actually
3238 * in progress and that it's safe to skip the commit.
3240 * opts->action tells us which subcommand requested to skip the commit.
3241 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3242 * action is in progress and we can skip the commit.
3244 * Otherwise we check that the last instruction was related to the
3245 * particular subcommand we're trying to execute and barf if that's not
3246 * the case.
3248 * Finally we check that the rollback is "safe", i.e., has the HEAD
3249 * moved? In this case, it doesn't make sense to "reset the merge" and
3250 * "skip the commit" as the user already handled this by committing. But
3251 * we'd not want to barf here, instead give advice on how to proceed. We
3252 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3253 * it gets removed when the user commits, so if it still exists we're
3254 * sure the user can't have committed before.
3256 switch (opts->action) {
3257 case REPLAY_REVERT:
3258 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3259 if (action != REPLAY_REVERT)
3260 return error(_("no revert in progress"));
3261 if (!rollback_is_safe())
3262 goto give_advice;
3264 break;
3265 case REPLAY_PICK:
3266 if (!refs_ref_exists(get_main_ref_store(r),
3267 "CHERRY_PICK_HEAD")) {
3268 if (action != REPLAY_PICK)
3269 return error(_("no cherry-pick in progress"));
3270 if (!rollback_is_safe())
3271 goto give_advice;
3273 break;
3274 default:
3275 BUG("unexpected action in sequencer_skip");
3278 if (skip_single_pick())
3279 return error(_("failed to skip the commit"));
3280 if (!is_directory(git_path_seq_dir()))
3281 return 0;
3283 return sequencer_continue(r, opts);
3285 give_advice:
3286 error(_("there is nothing to skip"));
3288 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3289 advise(_("have you committed already?\n"
3290 "try \"git %s --continue\""),
3291 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3293 return -1;
3296 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3298 struct lock_file todo_lock = LOCK_INIT;
3299 const char *todo_path = get_todo_path(opts);
3300 int next = todo_list->current, offset, fd;
3303 * rebase -i writes "git-rebase-todo" without the currently executing
3304 * command, appending it to "done" instead.
3306 if (is_rebase_i(opts))
3307 next++;
3309 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3310 if (fd < 0)
3311 return error_errno(_("could not lock '%s'"), todo_path);
3312 offset = get_item_line_offset(todo_list, next);
3313 if (write_in_full(fd, todo_list->buf.buf + offset,
3314 todo_list->buf.len - offset) < 0)
3315 return error_errno(_("could not write to '%s'"), todo_path);
3316 if (commit_lock_file(&todo_lock) < 0)
3317 return error(_("failed to finalize '%s'"), todo_path);
3319 if (is_rebase_i(opts) && next > 0) {
3320 const char *done = rebase_path_done();
3321 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3322 int ret = 0;
3324 if (fd < 0)
3325 return 0;
3326 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3327 get_item_line_length(todo_list, next - 1))
3328 < 0)
3329 ret = error_errno(_("could not write to '%s'"), done);
3330 if (close(fd) < 0)
3331 ret = error_errno(_("failed to finalize '%s'"), done);
3332 return ret;
3334 return 0;
3337 static int save_opts(struct replay_opts *opts)
3339 const char *opts_file = git_path_opts_file();
3340 int res = 0;
3342 if (opts->no_commit)
3343 res |= git_config_set_in_file_gently(opts_file,
3344 "options.no-commit", "true");
3345 if (opts->edit >= 0)
3346 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3347 opts->edit ? "true" : "false");
3348 if (opts->allow_empty)
3349 res |= git_config_set_in_file_gently(opts_file,
3350 "options.allow-empty", "true");
3351 if (opts->allow_empty_message)
3352 res |= git_config_set_in_file_gently(opts_file,
3353 "options.allow-empty-message", "true");
3354 if (opts->keep_redundant_commits)
3355 res |= git_config_set_in_file_gently(opts_file,
3356 "options.keep-redundant-commits", "true");
3357 if (opts->signoff)
3358 res |= git_config_set_in_file_gently(opts_file,
3359 "options.signoff", "true");
3360 if (opts->record_origin)
3361 res |= git_config_set_in_file_gently(opts_file,
3362 "options.record-origin", "true");
3363 if (opts->allow_ff)
3364 res |= git_config_set_in_file_gently(opts_file,
3365 "options.allow-ff", "true");
3366 if (opts->mainline) {
3367 struct strbuf buf = STRBUF_INIT;
3368 strbuf_addf(&buf, "%d", opts->mainline);
3369 res |= git_config_set_in_file_gently(opts_file,
3370 "options.mainline", buf.buf);
3371 strbuf_release(&buf);
3373 if (opts->strategy)
3374 res |= git_config_set_in_file_gently(opts_file,
3375 "options.strategy", opts->strategy);
3376 if (opts->gpg_sign)
3377 res |= git_config_set_in_file_gently(opts_file,
3378 "options.gpg-sign", opts->gpg_sign);
3379 if (opts->xopts) {
3380 int i;
3381 for (i = 0; i < opts->xopts_nr; i++)
3382 res |= git_config_set_multivar_in_file_gently(opts_file,
3383 "options.strategy-option",
3384 opts->xopts[i], "^$", 0);
3386 if (opts->allow_rerere_auto)
3387 res |= git_config_set_in_file_gently(opts_file,
3388 "options.allow-rerere-auto",
3389 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3390 "true" : "false");
3392 if (opts->explicit_cleanup)
3393 res |= git_config_set_in_file_gently(opts_file,
3394 "options.default-msg-cleanup",
3395 describe_cleanup_mode(opts->default_msg_cleanup));
3396 return res;
3399 static int make_patch(struct repository *r,
3400 struct commit *commit,
3401 struct replay_opts *opts)
3403 struct strbuf buf = STRBUF_INIT;
3404 struct rev_info log_tree_opt;
3405 const char *subject;
3406 char hex[GIT_MAX_HEXSZ + 1];
3407 int res = 0;
3409 oid_to_hex_r(hex, &commit->object.oid);
3410 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3411 return -1;
3412 res |= write_rebase_head(&commit->object.oid);
3414 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3415 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3416 repo_init_revisions(r, &log_tree_opt, NULL);
3417 log_tree_opt.abbrev = 0;
3418 log_tree_opt.diff = 1;
3419 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3420 log_tree_opt.disable_stdin = 1;
3421 log_tree_opt.no_commit_id = 1;
3422 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3423 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3424 if (!log_tree_opt.diffopt.file)
3425 res |= error_errno(_("could not open '%s'"), buf.buf);
3426 else {
3427 res |= log_tree_commit(&log_tree_opt, commit);
3428 fclose(log_tree_opt.diffopt.file);
3430 strbuf_reset(&buf);
3432 strbuf_addf(&buf, "%s/message", get_dir(opts));
3433 if (!file_exists(buf.buf)) {
3434 const char *encoding = get_commit_output_encoding();
3435 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3436 find_commit_subject(commit_buffer, &subject);
3437 res |= write_message(subject, strlen(subject), buf.buf, 1);
3438 unuse_commit_buffer(commit, commit_buffer);
3440 strbuf_release(&buf);
3442 return res;
3445 static int intend_to_amend(void)
3447 struct object_id head;
3448 char *p;
3450 if (get_oid("HEAD", &head))
3451 return error(_("cannot read HEAD"));
3453 p = oid_to_hex(&head);
3454 return write_message(p, strlen(p), rebase_path_amend(), 1);
3457 static int error_with_patch(struct repository *r,
3458 struct commit *commit,
3459 const char *subject, int subject_len,
3460 struct replay_opts *opts,
3461 int exit_code, int to_amend)
3463 if (commit) {
3464 if (make_patch(r, commit, opts))
3465 return -1;
3466 } else if (copy_file(rebase_path_message(),
3467 git_path_merge_msg(r), 0666))
3468 return error(_("unable to copy '%s' to '%s'"),
3469 git_path_merge_msg(r), rebase_path_message());
3471 if (to_amend) {
3472 if (intend_to_amend())
3473 return -1;
3475 fprintf(stderr,
3476 _("You can amend the commit now, with\n"
3477 "\n"
3478 " git commit --amend %s\n"
3479 "\n"
3480 "Once you are satisfied with your changes, run\n"
3481 "\n"
3482 " git rebase --continue\n"),
3483 gpg_sign_opt_quoted(opts));
3484 } else if (exit_code) {
3485 if (commit)
3486 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3487 short_commit_name(commit), subject_len, subject);
3488 else
3490 * We don't have the hash of the parent so
3491 * just print the line from the todo file.
3493 fprintf_ln(stderr, _("Could not merge %.*s"),
3494 subject_len, subject);
3497 return exit_code;
3500 static int error_failed_squash(struct repository *r,
3501 struct commit *commit,
3502 struct replay_opts *opts,
3503 int subject_len,
3504 const char *subject)
3506 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3507 return error(_("could not copy '%s' to '%s'"),
3508 rebase_path_squash_msg(), rebase_path_message());
3509 unlink(git_path_merge_msg(r));
3510 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3511 return error(_("could not copy '%s' to '%s'"),
3512 rebase_path_message(),
3513 git_path_merge_msg(r));
3514 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3517 static int do_exec(struct repository *r, const char *command_line)
3519 const char *child_argv[] = { NULL, NULL };
3520 int dirty, status;
3522 fprintf(stderr, _("Executing: %s\n"), command_line);
3523 child_argv[0] = command_line;
3524 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
3526 /* force re-reading of the cache */
3527 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3528 return error(_("could not read index"));
3530 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3532 if (status) {
3533 warning(_("execution failed: %s\n%s"
3534 "You can fix the problem, and then run\n"
3535 "\n"
3536 " git rebase --continue\n"
3537 "\n"),
3538 command_line,
3539 dirty ? N_("and made changes to the index and/or the "
3540 "working tree\n") : "");
3541 if (status == 127)
3542 /* command not found */
3543 status = 1;
3544 } else if (dirty) {
3545 warning(_("execution succeeded: %s\nbut "
3546 "left changes to the index and/or the working tree\n"
3547 "Commit or stash your changes, and then run\n"
3548 "\n"
3549 " git rebase --continue\n"
3550 "\n"), command_line);
3551 status = 1;
3554 return status;
3557 __attribute__((format (printf, 2, 3)))
3558 static int safe_append(const char *filename, const char *fmt, ...)
3560 va_list ap;
3561 struct lock_file lock = LOCK_INIT;
3562 int fd = hold_lock_file_for_update(&lock, filename,
3563 LOCK_REPORT_ON_ERROR);
3564 struct strbuf buf = STRBUF_INIT;
3566 if (fd < 0)
3567 return -1;
3569 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3570 error_errno(_("could not read '%s'"), filename);
3571 rollback_lock_file(&lock);
3572 return -1;
3574 strbuf_complete(&buf, '\n');
3575 va_start(ap, fmt);
3576 strbuf_vaddf(&buf, fmt, ap);
3577 va_end(ap);
3579 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3580 error_errno(_("could not write to '%s'"), filename);
3581 strbuf_release(&buf);
3582 rollback_lock_file(&lock);
3583 return -1;
3585 if (commit_lock_file(&lock) < 0) {
3586 strbuf_release(&buf);
3587 rollback_lock_file(&lock);
3588 return error(_("failed to finalize '%s'"), filename);
3591 strbuf_release(&buf);
3592 return 0;
3595 static int do_label(struct repository *r, const char *name, int len)
3597 struct ref_store *refs = get_main_ref_store(r);
3598 struct ref_transaction *transaction;
3599 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3600 struct strbuf msg = STRBUF_INIT;
3601 int ret = 0;
3602 struct object_id head_oid;
3604 if (len == 1 && *name == '#')
3605 return error(_("illegal label name: '%.*s'"), len, name);
3607 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3608 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3610 transaction = ref_store_transaction_begin(refs, &err);
3611 if (!transaction) {
3612 error("%s", err.buf);
3613 ret = -1;
3614 } else if (get_oid("HEAD", &head_oid)) {
3615 error(_("could not read HEAD"));
3616 ret = -1;
3617 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3618 NULL, 0, msg.buf, &err) < 0 ||
3619 ref_transaction_commit(transaction, &err)) {
3620 error("%s", err.buf);
3621 ret = -1;
3623 ref_transaction_free(transaction);
3624 strbuf_release(&err);
3625 strbuf_release(&msg);
3627 if (!ret)
3628 ret = safe_append(rebase_path_refs_to_delete(),
3629 "%s\n", ref_name.buf);
3630 strbuf_release(&ref_name);
3632 return ret;
3635 __attribute__((format (printf, 3, 4)))
3636 static const char *reflog_message(struct replay_opts *opts,
3637 const char *sub_action, const char *fmt, ...)
3639 va_list ap;
3640 static struct strbuf buf = STRBUF_INIT;
3641 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3643 va_start(ap, fmt);
3644 strbuf_reset(&buf);
3645 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3646 if (sub_action)
3647 strbuf_addf(&buf, " (%s)", sub_action);
3648 if (fmt) {
3649 strbuf_addstr(&buf, ": ");
3650 strbuf_vaddf(&buf, fmt, ap);
3652 va_end(ap);
3654 return buf.buf;
3657 static int do_reset(struct repository *r,
3658 const char *name, int len,
3659 struct replay_opts *opts)
3661 struct strbuf ref_name = STRBUF_INIT;
3662 struct object_id oid;
3663 struct lock_file lock = LOCK_INIT;
3664 struct tree_desc desc = { 0 };
3665 struct tree *tree;
3666 struct unpack_trees_options unpack_tree_opts = { 0 };
3667 int ret = 0;
3669 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3670 return -1;
3672 if (len == 10 && !strncmp("[new root]", name, len)) {
3673 if (!opts->have_squash_onto) {
3674 const char *hex;
3675 if (commit_tree("", 0, the_hash_algo->empty_tree,
3676 NULL, &opts->squash_onto,
3677 NULL, NULL))
3678 return error(_("writing fake root commit"));
3679 opts->have_squash_onto = 1;
3680 hex = oid_to_hex(&opts->squash_onto);
3681 if (write_message(hex, strlen(hex),
3682 rebase_path_squash_onto(), 0))
3683 return error(_("writing squash-onto"));
3685 oidcpy(&oid, &opts->squash_onto);
3686 } else {
3687 int i;
3689 /* Determine the length of the label */
3690 for (i = 0; i < len; i++)
3691 if (isspace(name[i]))
3692 break;
3693 len = i;
3695 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3696 if (get_oid(ref_name.buf, &oid) &&
3697 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3698 ret = error(_("could not read '%s'"), ref_name.buf);
3699 goto cleanup;
3703 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3704 unpack_tree_opts.head_idx = 1;
3705 unpack_tree_opts.src_index = r->index;
3706 unpack_tree_opts.dst_index = r->index;
3707 unpack_tree_opts.fn = oneway_merge;
3708 unpack_tree_opts.merge = 1;
3709 unpack_tree_opts.update = 1;
3710 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3711 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3713 if (repo_read_index_unmerged(r)) {
3714 ret = error_resolve_conflict(_(action_name(opts)));
3715 goto cleanup;
3718 if (!fill_tree_descriptor(r, &desc, &oid)) {
3719 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3720 goto cleanup;
3723 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3724 ret = -1;
3725 goto cleanup;
3728 tree = parse_tree_indirect(&oid);
3729 prime_cache_tree(r, r->index, tree);
3731 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3732 ret = error(_("could not write index"));
3734 if (!ret)
3735 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3736 len, name), "HEAD", &oid,
3737 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3738 cleanup:
3739 free((void *)desc.buffer);
3740 if (ret < 0)
3741 rollback_lock_file(&lock);
3742 strbuf_release(&ref_name);
3743 clear_unpack_trees_porcelain(&unpack_tree_opts);
3744 return ret;
3747 static struct commit *lookup_label(const char *label, int len,
3748 struct strbuf *buf)
3750 struct commit *commit;
3752 strbuf_reset(buf);
3753 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3754 commit = lookup_commit_reference_by_name(buf->buf);
3755 if (!commit) {
3756 /* fall back to non-rewritten ref or commit */
3757 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3758 commit = lookup_commit_reference_by_name(buf->buf);
3761 if (!commit)
3762 error(_("could not resolve '%s'"), buf->buf);
3764 return commit;
3767 static int do_merge(struct repository *r,
3768 struct commit *commit,
3769 const char *arg, int arg_len,
3770 int flags, int *check_todo, struct replay_opts *opts)
3772 int run_commit_flags = 0;
3773 struct strbuf ref_name = STRBUF_INIT;
3774 struct commit *head_commit, *merge_commit, *i;
3775 struct commit_list *bases, *j;
3776 struct commit_list *to_merge = NULL, **tail = &to_merge;
3777 const char *strategy = !opts->xopts_nr &&
3778 (!opts->strategy ||
3779 !strcmp(opts->strategy, "recursive") ||
3780 !strcmp(opts->strategy, "ort")) ?
3781 NULL : opts->strategy;
3782 struct merge_options o;
3783 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3784 static struct lock_file lock;
3785 const char *p;
3787 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3788 ret = -1;
3789 goto leave_merge;
3792 head_commit = lookup_commit_reference_by_name("HEAD");
3793 if (!head_commit) {
3794 ret = error(_("cannot merge without a current revision"));
3795 goto leave_merge;
3799 * For octopus merges, the arg starts with the list of revisions to be
3800 * merged. The list is optionally followed by '#' and the oneline.
3802 merge_arg_len = oneline_offset = arg_len;
3803 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3804 if (!*p)
3805 break;
3806 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3807 p += 1 + strspn(p + 1, " \t\n");
3808 oneline_offset = p - arg;
3809 break;
3811 k = strcspn(p, " \t\n");
3812 if (!k)
3813 continue;
3814 merge_commit = lookup_label(p, k, &ref_name);
3815 if (!merge_commit) {
3816 ret = error(_("unable to parse '%.*s'"), k, p);
3817 goto leave_merge;
3819 tail = &commit_list_insert(merge_commit, tail)->next;
3820 p += k;
3821 merge_arg_len = p - arg;
3824 if (!to_merge) {
3825 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3826 goto leave_merge;
3829 if (opts->have_squash_onto &&
3830 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3832 * When the user tells us to "merge" something into a
3833 * "[new root]", let's simply fast-forward to the merge head.
3835 rollback_lock_file(&lock);
3836 if (to_merge->next)
3837 ret = error(_("octopus merge cannot be executed on "
3838 "top of a [new root]"));
3839 else
3840 ret = fast_forward_to(r, &to_merge->item->object.oid,
3841 &head_commit->object.oid, 0,
3842 opts);
3843 goto leave_merge;
3847 * If HEAD is not identical to the first parent of the original merge
3848 * commit, we cannot fast-forward.
3850 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3851 oideq(&commit->parents->item->object.oid,
3852 &head_commit->object.oid);
3855 * If any merge head is different from the original one, we cannot
3856 * fast-forward.
3858 if (can_fast_forward) {
3859 struct commit_list *p = commit->parents->next;
3861 for (j = to_merge; j && p; j = j->next, p = p->next)
3862 if (!oideq(&j->item->object.oid,
3863 &p->item->object.oid)) {
3864 can_fast_forward = 0;
3865 break;
3868 * If the number of merge heads differs from the original merge
3869 * commit, we cannot fast-forward.
3871 if (j || p)
3872 can_fast_forward = 0;
3875 if (can_fast_forward) {
3876 rollback_lock_file(&lock);
3877 ret = fast_forward_to(r, &commit->object.oid,
3878 &head_commit->object.oid, 0, opts);
3879 if (flags & TODO_EDIT_MERGE_MSG)
3880 goto fast_forward_edit;
3882 goto leave_merge;
3885 if (commit) {
3886 const char *encoding = get_commit_output_encoding();
3887 const char *message = logmsg_reencode(commit, NULL, encoding);
3888 const char *body;
3889 int len;
3891 if (!message) {
3892 ret = error(_("could not get commit message of '%s'"),
3893 oid_to_hex(&commit->object.oid));
3894 goto leave_merge;
3896 write_author_script(message);
3897 find_commit_subject(message, &body);
3898 len = strlen(body);
3899 ret = write_message(body, len, git_path_merge_msg(r), 0);
3900 unuse_commit_buffer(commit, message);
3901 if (ret) {
3902 error_errno(_("could not write '%s'"),
3903 git_path_merge_msg(r));
3904 goto leave_merge;
3906 } else {
3907 struct strbuf buf = STRBUF_INIT;
3908 int len;
3910 strbuf_addf(&buf, "author %s", git_author_info(0));
3911 write_author_script(buf.buf);
3912 strbuf_reset(&buf);
3914 if (oneline_offset < arg_len) {
3915 p = arg + oneline_offset;
3916 len = arg_len - oneline_offset;
3917 } else {
3918 strbuf_addf(&buf, "Merge %s '%.*s'",
3919 to_merge->next ? "branches" : "branch",
3920 merge_arg_len, arg);
3921 p = buf.buf;
3922 len = buf.len;
3925 ret = write_message(p, len, git_path_merge_msg(r), 0);
3926 strbuf_release(&buf);
3927 if (ret) {
3928 error_errno(_("could not write '%s'"),
3929 git_path_merge_msg(r));
3930 goto leave_merge;
3934 if (strategy || to_merge->next) {
3935 /* Octopus merge */
3936 struct child_process cmd = CHILD_PROCESS_INIT;
3938 if (read_env_script(&cmd.env_array)) {
3939 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3941 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3942 goto leave_merge;
3945 if (opts->committer_date_is_author_date)
3946 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3947 opts->ignore_date ?
3948 "" :
3949 author_date_from_env_array(&cmd.env_array));
3950 if (opts->ignore_date)
3951 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3953 cmd.git_cmd = 1;
3954 strvec_push(&cmd.args, "merge");
3955 strvec_push(&cmd.args, "-s");
3956 if (!strategy)
3957 strvec_push(&cmd.args, "octopus");
3958 else {
3959 strvec_push(&cmd.args, strategy);
3960 for (k = 0; k < opts->xopts_nr; k++)
3961 strvec_pushf(&cmd.args,
3962 "-X%s", opts->xopts[k]);
3964 if (!(flags & TODO_EDIT_MERGE_MSG))
3965 strvec_push(&cmd.args, "--no-edit");
3966 else
3967 strvec_push(&cmd.args, "--edit");
3968 strvec_push(&cmd.args, "--no-ff");
3969 strvec_push(&cmd.args, "--no-log");
3970 strvec_push(&cmd.args, "--no-stat");
3971 strvec_push(&cmd.args, "-F");
3972 strvec_push(&cmd.args, git_path_merge_msg(r));
3973 if (opts->gpg_sign)
3974 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3975 else
3976 strvec_push(&cmd.args, "--no-gpg-sign");
3978 /* Add the tips to be merged */
3979 for (j = to_merge; j; j = j->next)
3980 strvec_push(&cmd.args,
3981 oid_to_hex(&j->item->object.oid));
3983 strbuf_release(&ref_name);
3984 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3985 NULL, 0);
3986 rollback_lock_file(&lock);
3988 ret = run_command(&cmd);
3990 /* force re-reading of the cache */
3991 if (!ret && (discard_index(r->index) < 0 ||
3992 repo_read_index(r) < 0))
3993 ret = error(_("could not read index"));
3994 goto leave_merge;
3997 merge_commit = to_merge->item;
3998 bases = get_merge_bases(head_commit, merge_commit);
3999 if (bases && oideq(&merge_commit->object.oid,
4000 &bases->item->object.oid)) {
4001 ret = 0;
4002 /* skip merging an ancestor of HEAD */
4003 goto leave_merge;
4006 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4007 git_path_merge_head(r), 0);
4008 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4010 bases = reverse_commit_list(bases);
4012 repo_read_index(r);
4013 init_merge_options(&o, r);
4014 o.branch1 = "HEAD";
4015 o.branch2 = ref_name.buf;
4016 o.buffer_output = 2;
4018 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4020 * TODO: Should use merge_incore_recursive() and
4021 * merge_switch_to_result(), skipping the call to
4022 * merge_switch_to_result() when we don't actually need to
4023 * update the index and working copy immediately.
4025 ret = merge_ort_recursive(&o,
4026 head_commit, merge_commit, bases,
4027 &i);
4028 } else {
4029 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4030 &i);
4032 if (ret <= 0)
4033 fputs(o.obuf.buf, stdout);
4034 strbuf_release(&o.obuf);
4035 if (ret < 0) {
4036 error(_("could not even attempt to merge '%.*s'"),
4037 merge_arg_len, arg);
4038 goto leave_merge;
4041 * The return value of merge_recursive() is 1 on clean, and 0 on
4042 * unclean merge.
4044 * Let's reverse that, so that do_merge() returns 0 upon success and
4045 * 1 upon failed merge (keeping the return value -1 for the cases where
4046 * we will want to reschedule the `merge` command).
4048 ret = !ret;
4050 if (r->index->cache_changed &&
4051 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4052 ret = error(_("merge: Unable to write new index file"));
4053 goto leave_merge;
4056 rollback_lock_file(&lock);
4057 if (ret)
4058 repo_rerere(r, opts->allow_rerere_auto);
4059 else
4061 * In case of problems, we now want to return a positive
4062 * value (a negative one would indicate that the `merge`
4063 * command needs to be rescheduled).
4065 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4066 run_commit_flags);
4068 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4069 fast_forward_edit:
4070 *check_todo = 1;
4071 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4072 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4076 leave_merge:
4077 strbuf_release(&ref_name);
4078 rollback_lock_file(&lock);
4079 free_commit_list(to_merge);
4080 return ret;
4083 static int is_final_fixup(struct todo_list *todo_list)
4085 int i = todo_list->current;
4087 if (!is_fixup(todo_list->items[i].command))
4088 return 0;
4090 while (++i < todo_list->nr)
4091 if (is_fixup(todo_list->items[i].command))
4092 return 0;
4093 else if (!is_noop(todo_list->items[i].command))
4094 break;
4095 return 1;
4098 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4100 int i;
4102 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4103 if (!is_noop(todo_list->items[i].command))
4104 return todo_list->items[i].command;
4106 return -1;
4109 void create_autostash(struct repository *r, const char *path)
4111 struct strbuf buf = STRBUF_INIT;
4112 struct lock_file lock_file = LOCK_INIT;
4113 int fd;
4115 fd = repo_hold_locked_index(r, &lock_file, 0);
4116 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4117 if (0 <= fd)
4118 repo_update_index_if_able(r, &lock_file);
4119 rollback_lock_file(&lock_file);
4121 if (has_unstaged_changes(r, 1) ||
4122 has_uncommitted_changes(r, 1)) {
4123 struct child_process stash = CHILD_PROCESS_INIT;
4124 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4125 struct object_id oid;
4127 strvec_pushl(&stash.args,
4128 "stash", "create", "autostash", NULL);
4129 stash.git_cmd = 1;
4130 stash.no_stdin = 1;
4131 strbuf_reset(&buf);
4132 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4133 die(_("Cannot autostash"));
4134 strbuf_trim_trailing_newline(&buf);
4135 if (get_oid(buf.buf, &oid))
4136 die(_("Unexpected stash response: '%s'"),
4137 buf.buf);
4138 strbuf_reset(&buf);
4139 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4141 if (safe_create_leading_directories_const(path))
4142 die(_("Could not create directory for '%s'"),
4143 path);
4144 write_file(path, "%s", oid_to_hex(&oid));
4145 printf(_("Created autostash: %s\n"), buf.buf);
4146 if (reset_head(r, &ropts) < 0)
4147 die(_("could not reset --hard"));
4148 if (discard_index(r->index) < 0 ||
4149 repo_read_index(r) < 0)
4150 die(_("could not read index"));
4152 strbuf_release(&buf);
4155 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4157 struct child_process child = CHILD_PROCESS_INIT;
4158 int ret = 0;
4160 if (attempt_apply) {
4161 child.git_cmd = 1;
4162 child.no_stdout = 1;
4163 child.no_stderr = 1;
4164 strvec_push(&child.args, "stash");
4165 strvec_push(&child.args, "apply");
4166 strvec_push(&child.args, stash_oid);
4167 ret = run_command(&child);
4170 if (attempt_apply && !ret)
4171 fprintf(stderr, _("Applied autostash.\n"));
4172 else {
4173 struct child_process store = CHILD_PROCESS_INIT;
4175 store.git_cmd = 1;
4176 strvec_push(&store.args, "stash");
4177 strvec_push(&store.args, "store");
4178 strvec_push(&store.args, "-m");
4179 strvec_push(&store.args, "autostash");
4180 strvec_push(&store.args, "-q");
4181 strvec_push(&store.args, stash_oid);
4182 if (run_command(&store))
4183 ret = error(_("cannot store %s"), stash_oid);
4184 else
4185 fprintf(stderr,
4186 _("%s\n"
4187 "Your changes are safe in the stash.\n"
4188 "You can run \"git stash pop\" or"
4189 " \"git stash drop\" at any time.\n"),
4190 attempt_apply ?
4191 _("Applying autostash resulted in conflicts.") :
4192 _("Autostash exists; creating a new stash entry."));
4195 return ret;
4198 static int apply_save_autostash(const char *path, int attempt_apply)
4200 struct strbuf stash_oid = STRBUF_INIT;
4201 int ret = 0;
4203 if (!read_oneliner(&stash_oid, path,
4204 READ_ONELINER_SKIP_IF_EMPTY)) {
4205 strbuf_release(&stash_oid);
4206 return 0;
4208 strbuf_trim(&stash_oid);
4210 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4212 unlink(path);
4213 strbuf_release(&stash_oid);
4214 return ret;
4217 int save_autostash(const char *path)
4219 return apply_save_autostash(path, 0);
4222 int apply_autostash(const char *path)
4224 return apply_save_autostash(path, 1);
4227 int apply_autostash_oid(const char *stash_oid)
4229 return apply_save_autostash_oid(stash_oid, 1);
4232 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4233 const char *onto_name, const struct object_id *onto,
4234 const struct object_id *orig_head)
4236 struct reset_head_opts ropts = {
4237 .oid = onto,
4238 .orig_head = orig_head,
4239 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4240 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4241 .head_msg = reflog_message(opts, "start", "checkout %s",
4242 onto_name),
4243 .default_reflog_action = "rebase"
4245 if (reset_head(r, &ropts)) {
4246 apply_autostash(rebase_path_autostash());
4247 sequencer_remove_state(opts);
4248 return error(_("could not detach HEAD"));
4251 return 0;
4254 static int stopped_at_head(struct repository *r)
4256 struct object_id head;
4257 struct commit *commit;
4258 struct commit_message message;
4260 if (get_oid("HEAD", &head) ||
4261 !(commit = lookup_commit(r, &head)) ||
4262 parse_commit(commit) || get_message(commit, &message))
4263 fprintf(stderr, _("Stopped at HEAD\n"));
4264 else {
4265 fprintf(stderr, _("Stopped at %s\n"), message.label);
4266 free_message(commit, &message);
4268 return 0;
4272 static int reread_todo_if_changed(struct repository *r,
4273 struct todo_list *todo_list,
4274 struct replay_opts *opts)
4276 int offset;
4277 struct strbuf buf = STRBUF_INIT;
4279 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4280 return -1;
4281 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4282 if (buf.len != todo_list->buf.len - offset ||
4283 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4284 /* Reread the todo file if it has changed. */
4285 todo_list_release(todo_list);
4286 if (read_populate_todo(r, todo_list, opts))
4287 return -1; /* message was printed */
4288 /* `current` will be incremented on return */
4289 todo_list->current = -1;
4291 strbuf_release(&buf);
4293 return 0;
4296 static const char rescheduled_advice[] =
4297 N_("Could not execute the todo command\n"
4298 "\n"
4299 " %.*s"
4300 "\n"
4301 "It has been rescheduled; To edit the command before continuing, please\n"
4302 "edit the todo list first:\n"
4303 "\n"
4304 " git rebase --edit-todo\n"
4305 " git rebase --continue\n");
4307 static int pick_commits(struct repository *r,
4308 struct todo_list *todo_list,
4309 struct replay_opts *opts)
4311 int res = 0, reschedule = 0;
4312 char *prev_reflog_action;
4314 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4315 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4316 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4317 if (opts->allow_ff)
4318 assert(!(opts->signoff || opts->no_commit ||
4319 opts->record_origin || should_edit(opts) ||
4320 opts->committer_date_is_author_date ||
4321 opts->ignore_date));
4322 if (read_and_refresh_cache(r, opts))
4323 return -1;
4325 while (todo_list->current < todo_list->nr) {
4326 struct todo_item *item = todo_list->items + todo_list->current;
4327 const char *arg = todo_item_get_arg(todo_list, item);
4328 int check_todo = 0;
4330 if (save_todo(todo_list, opts))
4331 return -1;
4332 if (is_rebase_i(opts)) {
4333 if (item->command != TODO_COMMENT) {
4334 FILE *f = fopen(rebase_path_msgnum(), "w");
4336 todo_list->done_nr++;
4338 if (f) {
4339 fprintf(f, "%d\n", todo_list->done_nr);
4340 fclose(f);
4342 if (!opts->quiet)
4343 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4344 todo_list->done_nr,
4345 todo_list->total_nr,
4346 opts->verbose ? "\n" : "\r");
4348 unlink(rebase_path_message());
4349 unlink(rebase_path_author_script());
4350 unlink(rebase_path_stopped_sha());
4351 unlink(rebase_path_amend());
4352 unlink(git_path_merge_head(r));
4353 unlink(git_path_auto_merge(r));
4354 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4356 if (item->command == TODO_BREAK) {
4357 if (!opts->verbose)
4358 term_clear_line();
4359 return stopped_at_head(r);
4362 if (item->command <= TODO_SQUASH) {
4363 if (is_rebase_i(opts))
4364 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4365 command_to_string(item->command), NULL),
4367 res = do_pick_commit(r, item, opts,
4368 is_final_fixup(todo_list),
4369 &check_todo);
4370 if (is_rebase_i(opts))
4371 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4372 if (is_rebase_i(opts) && res < 0) {
4373 /* Reschedule */
4374 advise(_(rescheduled_advice),
4375 get_item_line_length(todo_list,
4376 todo_list->current),
4377 get_item_line(todo_list,
4378 todo_list->current));
4379 todo_list->current--;
4380 if (save_todo(todo_list, opts))
4381 return -1;
4383 if (item->command == TODO_EDIT) {
4384 struct commit *commit = item->commit;
4385 if (!res) {
4386 if (!opts->verbose)
4387 term_clear_line();
4388 fprintf(stderr,
4389 _("Stopped at %s... %.*s\n"),
4390 short_commit_name(commit),
4391 item->arg_len, arg);
4393 return error_with_patch(r, commit,
4394 arg, item->arg_len, opts, res, !res);
4396 if (is_rebase_i(opts) && !res)
4397 record_in_rewritten(&item->commit->object.oid,
4398 peek_command(todo_list, 1));
4399 if (res && is_fixup(item->command)) {
4400 if (res == 1)
4401 intend_to_amend();
4402 return error_failed_squash(r, item->commit, opts,
4403 item->arg_len, arg);
4404 } else if (res && is_rebase_i(opts) && item->commit) {
4405 int to_amend = 0;
4406 struct object_id oid;
4409 * If we are rewording and have either
4410 * fast-forwarded already, or are about to
4411 * create a new root commit, we want to amend,
4412 * otherwise we do not.
4414 if (item->command == TODO_REWORD &&
4415 !get_oid("HEAD", &oid) &&
4416 (oideq(&item->commit->object.oid, &oid) ||
4417 (opts->have_squash_onto &&
4418 oideq(&opts->squash_onto, &oid))))
4419 to_amend = 1;
4421 return res | error_with_patch(r, item->commit,
4422 arg, item->arg_len, opts,
4423 res, to_amend);
4425 } else if (item->command == TODO_EXEC) {
4426 char *end_of_arg = (char *)(arg + item->arg_len);
4427 int saved = *end_of_arg;
4429 if (!opts->verbose)
4430 term_clear_line();
4431 *end_of_arg = '\0';
4432 res = do_exec(r, arg);
4433 *end_of_arg = saved;
4435 if (res) {
4436 if (opts->reschedule_failed_exec)
4437 reschedule = 1;
4439 check_todo = 1;
4440 } else if (item->command == TODO_LABEL) {
4441 if ((res = do_label(r, arg, item->arg_len)))
4442 reschedule = 1;
4443 } else if (item->command == TODO_RESET) {
4444 if ((res = do_reset(r, arg, item->arg_len, opts)))
4445 reschedule = 1;
4446 } else if (item->command == TODO_MERGE) {
4447 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4448 item->flags, &check_todo, opts)) < 0)
4449 reschedule = 1;
4450 else if (item->commit)
4451 record_in_rewritten(&item->commit->object.oid,
4452 peek_command(todo_list, 1));
4453 if (res > 0)
4454 /* failed with merge conflicts */
4455 return error_with_patch(r, item->commit,
4456 arg, item->arg_len,
4457 opts, res, 0);
4458 } else if (!is_noop(item->command))
4459 return error(_("unknown command %d"), item->command);
4461 if (reschedule) {
4462 advise(_(rescheduled_advice),
4463 get_item_line_length(todo_list,
4464 todo_list->current),
4465 get_item_line(todo_list, todo_list->current));
4466 todo_list->current--;
4467 if (save_todo(todo_list, opts))
4468 return -1;
4469 if (item->commit)
4470 return error_with_patch(r,
4471 item->commit,
4472 arg, item->arg_len,
4473 opts, res, 0);
4474 } else if (is_rebase_i(opts) && check_todo && !res &&
4475 reread_todo_if_changed(r, todo_list, opts)) {
4476 return -1;
4479 todo_list->current++;
4480 if (res)
4481 return res;
4484 if (is_rebase_i(opts)) {
4485 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4486 struct stat st;
4488 /* Stopped in the middle, as planned? */
4489 if (todo_list->current < todo_list->nr)
4490 return 0;
4492 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4493 starts_with(head_ref.buf, "refs/")) {
4494 const char *msg;
4495 struct object_id head, orig;
4496 int res;
4498 if (get_oid("HEAD", &head)) {
4499 res = error(_("cannot read HEAD"));
4500 cleanup_head_ref:
4501 strbuf_release(&head_ref);
4502 strbuf_release(&buf);
4503 return res;
4505 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4506 get_oid_hex(buf.buf, &orig)) {
4507 res = error(_("could not read orig-head"));
4508 goto cleanup_head_ref;
4510 strbuf_reset(&buf);
4511 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4512 res = error(_("could not read 'onto'"));
4513 goto cleanup_head_ref;
4515 msg = reflog_message(opts, "finish", "%s onto %s",
4516 head_ref.buf, buf.buf);
4517 if (update_ref(msg, head_ref.buf, &head, &orig,
4518 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4519 res = error(_("could not update %s"),
4520 head_ref.buf);
4521 goto cleanup_head_ref;
4523 msg = reflog_message(opts, "finish", "returning to %s",
4524 head_ref.buf);
4525 if (create_symref("HEAD", head_ref.buf, msg)) {
4526 res = error(_("could not update HEAD to %s"),
4527 head_ref.buf);
4528 goto cleanup_head_ref;
4530 strbuf_reset(&buf);
4533 if (opts->verbose) {
4534 struct rev_info log_tree_opt;
4535 struct object_id orig, head;
4537 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4538 repo_init_revisions(r, &log_tree_opt, NULL);
4539 log_tree_opt.diff = 1;
4540 log_tree_opt.diffopt.output_format =
4541 DIFF_FORMAT_DIFFSTAT;
4542 log_tree_opt.disable_stdin = 1;
4544 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4545 !get_oid(buf.buf, &orig) &&
4546 !get_oid("HEAD", &head)) {
4547 diff_tree_oid(&orig, &head, "",
4548 &log_tree_opt.diffopt);
4549 log_tree_diff_flush(&log_tree_opt);
4552 flush_rewritten_pending();
4553 if (!stat(rebase_path_rewritten_list(), &st) &&
4554 st.st_size > 0) {
4555 struct child_process child = CHILD_PROCESS_INIT;
4556 const char *post_rewrite_hook =
4557 find_hook("post-rewrite");
4559 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4560 child.git_cmd = 1;
4561 strvec_push(&child.args, "notes");
4562 strvec_push(&child.args, "copy");
4563 strvec_push(&child.args, "--for-rewrite=rebase");
4564 /* we don't care if this copying failed */
4565 run_command(&child);
4567 if (post_rewrite_hook) {
4568 struct child_process hook = CHILD_PROCESS_INIT;
4570 hook.in = open(rebase_path_rewritten_list(),
4571 O_RDONLY);
4572 hook.stdout_to_stderr = 1;
4573 hook.trace2_hook_name = "post-rewrite";
4574 strvec_push(&hook.args, post_rewrite_hook);
4575 strvec_push(&hook.args, "rebase");
4576 /* we don't care if this hook failed */
4577 run_command(&hook);
4580 apply_autostash(rebase_path_autostash());
4582 if (!opts->quiet) {
4583 if (!opts->verbose)
4584 term_clear_line();
4585 fprintf(stderr,
4586 _("Successfully rebased and updated %s.\n"),
4587 head_ref.buf);
4590 strbuf_release(&buf);
4591 strbuf_release(&head_ref);
4595 * Sequence of picks finished successfully; cleanup by
4596 * removing the .git/sequencer directory
4598 return sequencer_remove_state(opts);
4601 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4603 struct strvec argv = STRVEC_INIT;
4604 int ret;
4606 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4607 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4608 return error(_("no cherry-pick or revert in progress"));
4610 strvec_push(&argv, "commit");
4613 * continue_single_pick() handles the case of recovering from a
4614 * conflict. should_edit() doesn't handle that case; for a conflict,
4615 * we want to edit if the user asked for it, or if they didn't specify
4616 * and stdin is a tty.
4618 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4620 * Include --cleanup=strip as well because we don't want the
4621 * "# Conflicts:" messages.
4623 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4625 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4626 strvec_clear(&argv);
4627 return ret;
4630 static int commit_staged_changes(struct repository *r,
4631 struct replay_opts *opts,
4632 struct todo_list *todo_list)
4634 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4635 unsigned int final_fixup = 0, is_clean;
4637 if (has_unstaged_changes(r, 1))
4638 return error(_("cannot rebase: You have unstaged changes."));
4640 is_clean = !has_uncommitted_changes(r, 0);
4642 if (file_exists(rebase_path_amend())) {
4643 struct strbuf rev = STRBUF_INIT;
4644 struct object_id head, to_amend;
4646 if (get_oid("HEAD", &head))
4647 return error(_("cannot amend non-existing commit"));
4648 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4649 return error(_("invalid file: '%s'"), rebase_path_amend());
4650 if (get_oid_hex(rev.buf, &to_amend))
4651 return error(_("invalid contents: '%s'"),
4652 rebase_path_amend());
4653 if (!is_clean && !oideq(&head, &to_amend))
4654 return error(_("\nYou have uncommitted changes in your "
4655 "working tree. Please, commit them\n"
4656 "first and then run 'git rebase "
4657 "--continue' again."));
4659 * When skipping a failed fixup/squash, we need to edit the
4660 * commit message, the current fixup list and count, and if it
4661 * was the last fixup/squash in the chain, we need to clean up
4662 * the commit message and if there was a squash, let the user
4663 * edit it.
4665 if (!is_clean || !opts->current_fixup_count)
4666 ; /* this is not the final fixup */
4667 else if (!oideq(&head, &to_amend) ||
4668 !file_exists(rebase_path_stopped_sha())) {
4669 /* was a final fixup or squash done manually? */
4670 if (!is_fixup(peek_command(todo_list, 0))) {
4671 unlink(rebase_path_fixup_msg());
4672 unlink(rebase_path_squash_msg());
4673 unlink(rebase_path_current_fixups());
4674 strbuf_reset(&opts->current_fixups);
4675 opts->current_fixup_count = 0;
4677 } else {
4678 /* we are in a fixup/squash chain */
4679 const char *p = opts->current_fixups.buf;
4680 int len = opts->current_fixups.len;
4682 opts->current_fixup_count--;
4683 if (!len)
4684 BUG("Incorrect current_fixups:\n%s", p);
4685 while (len && p[len - 1] != '\n')
4686 len--;
4687 strbuf_setlen(&opts->current_fixups, len);
4688 if (write_message(p, len, rebase_path_current_fixups(),
4689 0) < 0)
4690 return error(_("could not write file: '%s'"),
4691 rebase_path_current_fixups());
4694 * If a fixup/squash in a fixup/squash chain failed, the
4695 * commit message is already correct, no need to commit
4696 * it again.
4698 * Only if it is the final command in the fixup/squash
4699 * chain, and only if the chain is longer than a single
4700 * fixup/squash command (which was just skipped), do we
4701 * actually need to re-commit with a cleaned up commit
4702 * message.
4704 if (opts->current_fixup_count > 0 &&
4705 !is_fixup(peek_command(todo_list, 0))) {
4706 final_fixup = 1;
4708 * If there was not a single "squash" in the
4709 * chain, we only need to clean up the commit
4710 * message, no need to bother the user with
4711 * opening the commit message in the editor.
4713 if (!starts_with(p, "squash ") &&
4714 !strstr(p, "\nsquash "))
4715 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4716 } else if (is_fixup(peek_command(todo_list, 0))) {
4718 * We need to update the squash message to skip
4719 * the latest commit message.
4721 struct commit *commit;
4722 const char *path = rebase_path_squash_msg();
4723 const char *encoding = get_commit_output_encoding();
4725 if (parse_head(r, &commit) ||
4726 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4727 write_message(p, strlen(p), path, 0)) {
4728 unuse_commit_buffer(commit, p);
4729 return error(_("could not write file: "
4730 "'%s'"), path);
4732 unuse_commit_buffer(commit, p);
4736 strbuf_release(&rev);
4737 flags |= AMEND_MSG;
4740 if (is_clean) {
4741 if (refs_ref_exists(get_main_ref_store(r),
4742 "CHERRY_PICK_HEAD") &&
4743 refs_delete_ref(get_main_ref_store(r), "",
4744 "CHERRY_PICK_HEAD", NULL, 0))
4745 return error(_("could not remove CHERRY_PICK_HEAD"));
4746 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4747 return error_errno(_("could not remove '%s'"),
4748 git_path_merge_msg(r));
4749 if (!final_fixup)
4750 return 0;
4753 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4754 opts, flags))
4755 return error(_("could not commit staged changes."));
4756 unlink(rebase_path_amend());
4757 unlink(git_path_merge_head(r));
4758 unlink(git_path_auto_merge(r));
4759 if (final_fixup) {
4760 unlink(rebase_path_fixup_msg());
4761 unlink(rebase_path_squash_msg());
4763 if (opts->current_fixup_count > 0) {
4765 * Whether final fixup or not, we just cleaned up the commit
4766 * message...
4768 unlink(rebase_path_current_fixups());
4769 strbuf_reset(&opts->current_fixups);
4770 opts->current_fixup_count = 0;
4772 return 0;
4775 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4777 struct todo_list todo_list = TODO_LIST_INIT;
4778 int res;
4780 if (read_and_refresh_cache(r, opts))
4781 return -1;
4783 if (read_populate_opts(opts))
4784 return -1;
4785 if (is_rebase_i(opts)) {
4786 if ((res = read_populate_todo(r, &todo_list, opts)))
4787 goto release_todo_list;
4789 if (file_exists(rebase_path_dropped())) {
4790 if ((res = todo_list_check_against_backup(r, &todo_list)))
4791 goto release_todo_list;
4793 unlink(rebase_path_dropped());
4796 if (commit_staged_changes(r, opts, &todo_list)) {
4797 res = -1;
4798 goto release_todo_list;
4800 } else if (!file_exists(get_todo_path(opts)))
4801 return continue_single_pick(r, opts);
4802 else if ((res = read_populate_todo(r, &todo_list, opts)))
4803 goto release_todo_list;
4805 if (!is_rebase_i(opts)) {
4806 /* Verify that the conflict has been resolved */
4807 if (refs_ref_exists(get_main_ref_store(r),
4808 "CHERRY_PICK_HEAD") ||
4809 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4810 res = continue_single_pick(r, opts);
4811 if (res)
4812 goto release_todo_list;
4814 if (index_differs_from(r, "HEAD", NULL, 0)) {
4815 res = error_dirty_index(r, opts);
4816 goto release_todo_list;
4818 todo_list.current++;
4819 } else if (file_exists(rebase_path_stopped_sha())) {
4820 struct strbuf buf = STRBUF_INIT;
4821 struct object_id oid;
4823 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4824 READ_ONELINER_SKIP_IF_EMPTY) &&
4825 !get_oid_hex(buf.buf, &oid))
4826 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4827 strbuf_release(&buf);
4830 res = pick_commits(r, &todo_list, opts);
4831 release_todo_list:
4832 todo_list_release(&todo_list);
4833 return res;
4836 static int single_pick(struct repository *r,
4837 struct commit *cmit,
4838 struct replay_opts *opts)
4840 int check_todo;
4841 struct todo_item item;
4843 item.command = opts->action == REPLAY_PICK ?
4844 TODO_PICK : TODO_REVERT;
4845 item.commit = cmit;
4847 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4848 return do_pick_commit(r, &item, opts, 0, &check_todo);
4851 int sequencer_pick_revisions(struct repository *r,
4852 struct replay_opts *opts)
4854 struct todo_list todo_list = TODO_LIST_INIT;
4855 struct object_id oid;
4856 int i, res;
4858 assert(opts->revs);
4859 if (read_and_refresh_cache(r, opts))
4860 return -1;
4862 for (i = 0; i < opts->revs->pending.nr; i++) {
4863 struct object_id oid;
4864 const char *name = opts->revs->pending.objects[i].name;
4866 /* This happens when using --stdin. */
4867 if (!strlen(name))
4868 continue;
4870 if (!get_oid(name, &oid)) {
4871 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4872 enum object_type type = oid_object_info(r,
4873 &oid,
4874 NULL);
4875 return error(_("%s: can't cherry-pick a %s"),
4876 name, type_name(type));
4878 } else
4879 return error(_("%s: bad revision"), name);
4883 * If we were called as "git cherry-pick <commit>", just
4884 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4885 * REVERT_HEAD, and don't touch the sequencer state.
4886 * This means it is possible to cherry-pick in the middle
4887 * of a cherry-pick sequence.
4889 if (opts->revs->cmdline.nr == 1 &&
4890 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4891 opts->revs->no_walk &&
4892 !opts->revs->cmdline.rev->flags) {
4893 struct commit *cmit;
4894 if (prepare_revision_walk(opts->revs))
4895 return error(_("revision walk setup failed"));
4896 cmit = get_revision(opts->revs);
4897 if (!cmit)
4898 return error(_("empty commit set passed"));
4899 if (get_revision(opts->revs))
4900 BUG("unexpected extra commit from walk");
4901 return single_pick(r, cmit, opts);
4905 * Start a new cherry-pick/ revert sequence; but
4906 * first, make sure that an existing one isn't in
4907 * progress
4910 if (walk_revs_populate_todo(&todo_list, opts) ||
4911 create_seq_dir(r) < 0)
4912 return -1;
4913 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4914 return error(_("can't revert as initial commit"));
4915 if (save_head(oid_to_hex(&oid)))
4916 return -1;
4917 if (save_opts(opts))
4918 return -1;
4919 update_abort_safety_file();
4920 res = pick_commits(r, &todo_list, opts);
4921 todo_list_release(&todo_list);
4922 return res;
4925 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4927 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4928 struct strbuf sob = STRBUF_INIT;
4929 int has_footer;
4931 strbuf_addstr(&sob, sign_off_header);
4932 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4933 strbuf_addch(&sob, '\n');
4935 if (!ignore_footer)
4936 strbuf_complete_line(msgbuf);
4939 * If the whole message buffer is equal to the sob, pretend that we
4940 * found a conforming footer with a matching sob
4942 if (msgbuf->len - ignore_footer == sob.len &&
4943 !strncmp(msgbuf->buf, sob.buf, sob.len))
4944 has_footer = 3;
4945 else
4946 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4948 if (!has_footer) {
4949 const char *append_newlines = NULL;
4950 size_t len = msgbuf->len - ignore_footer;
4952 if (!len) {
4954 * The buffer is completely empty. Leave foom for
4955 * the title and body to be filled in by the user.
4957 append_newlines = "\n\n";
4958 } else if (len == 1) {
4960 * Buffer contains a single newline. Add another
4961 * so that we leave room for the title and body.
4963 append_newlines = "\n";
4964 } else if (msgbuf->buf[len - 2] != '\n') {
4966 * Buffer ends with a single newline. Add another
4967 * so that there is an empty line between the message
4968 * body and the sob.
4970 append_newlines = "\n";
4971 } /* else, the buffer already ends with two newlines. */
4973 if (append_newlines)
4974 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4975 append_newlines, strlen(append_newlines));
4978 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4979 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4980 sob.buf, sob.len);
4982 strbuf_release(&sob);
4985 struct labels_entry {
4986 struct hashmap_entry entry;
4987 char label[FLEX_ARRAY];
4990 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4991 const struct hashmap_entry *entry_or_key, const void *key)
4993 const struct labels_entry *a, *b;
4995 a = container_of(eptr, const struct labels_entry, entry);
4996 b = container_of(entry_or_key, const struct labels_entry, entry);
4998 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5001 struct string_entry {
5002 struct oidmap_entry entry;
5003 char string[FLEX_ARRAY];
5006 struct label_state {
5007 struct oidmap commit2label;
5008 struct hashmap labels;
5009 struct strbuf buf;
5012 static const char *label_oid(struct object_id *oid, const char *label,
5013 struct label_state *state)
5015 struct labels_entry *labels_entry;
5016 struct string_entry *string_entry;
5017 struct object_id dummy;
5018 int i;
5020 string_entry = oidmap_get(&state->commit2label, oid);
5021 if (string_entry)
5022 return string_entry->string;
5025 * For "uninteresting" commits, i.e. commits that are not to be
5026 * rebased, and which can therefore not be labeled, we use a unique
5027 * abbreviation of the commit name. This is slightly more complicated
5028 * than calling find_unique_abbrev() because we also need to make
5029 * sure that the abbreviation does not conflict with any other
5030 * label.
5032 * We disallow "interesting" commits to be labeled by a string that
5033 * is a valid full-length hash, to ensure that we always can find an
5034 * abbreviation for any uninteresting commit's names that does not
5035 * clash with any other label.
5037 strbuf_reset(&state->buf);
5038 if (!label) {
5039 char *p;
5041 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5042 label = p = state->buf.buf;
5044 find_unique_abbrev_r(p, oid, default_abbrev);
5047 * We may need to extend the abbreviated hash so that there is
5048 * no conflicting label.
5050 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5051 size_t i = strlen(p) + 1;
5053 oid_to_hex_r(p, oid);
5054 for (; i < the_hash_algo->hexsz; i++) {
5055 char save = p[i];
5056 p[i] = '\0';
5057 if (!hashmap_get_from_hash(&state->labels,
5058 strihash(p), p))
5059 break;
5060 p[i] = save;
5063 } else {
5064 struct strbuf *buf = &state->buf;
5067 * Sanitize labels by replacing non-alpha-numeric characters
5068 * (including white-space ones) by dashes, as they might be
5069 * illegal in file names (and hence in ref names).
5071 * Note that we retain non-ASCII UTF-8 characters (identified
5072 * via the most significant bit). They should be all acceptable
5073 * in file names. We do not validate the UTF-8 here, that's not
5074 * the job of this function.
5076 for (; *label; label++)
5077 if ((*label & 0x80) || isalnum(*label))
5078 strbuf_addch(buf, *label);
5079 /* avoid leading dash and double-dashes */
5080 else if (buf->len && buf->buf[buf->len - 1] != '-')
5081 strbuf_addch(buf, '-');
5082 if (!buf->len) {
5083 strbuf_addstr(buf, "rev-");
5084 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5086 label = buf->buf;
5088 if ((buf->len == the_hash_algo->hexsz &&
5089 !get_oid_hex(label, &dummy)) ||
5090 (buf->len == 1 && *label == '#') ||
5091 hashmap_get_from_hash(&state->labels,
5092 strihash(label), label)) {
5094 * If the label already exists, or if the label is a
5095 * valid full OID, or the label is a '#' (which we use
5096 * as a separator between merge heads and oneline), we
5097 * append a dash and a number to make it unique.
5099 size_t len = buf->len;
5101 for (i = 2; ; i++) {
5102 strbuf_setlen(buf, len);
5103 strbuf_addf(buf, "-%d", i);
5104 if (!hashmap_get_from_hash(&state->labels,
5105 strihash(buf->buf),
5106 buf->buf))
5107 break;
5110 label = buf->buf;
5114 FLEX_ALLOC_STR(labels_entry, label, label);
5115 hashmap_entry_init(&labels_entry->entry, strihash(label));
5116 hashmap_add(&state->labels, &labels_entry->entry);
5118 FLEX_ALLOC_STR(string_entry, string, label);
5119 oidcpy(&string_entry->entry.oid, oid);
5120 oidmap_put(&state->commit2label, string_entry);
5122 return string_entry->string;
5125 static int make_script_with_merges(struct pretty_print_context *pp,
5126 struct rev_info *revs, struct strbuf *out,
5127 unsigned flags)
5129 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5130 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5131 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5132 int skipped_commit = 0;
5133 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5134 struct strbuf label = STRBUF_INIT;
5135 struct commit_list *commits = NULL, **tail = &commits, *iter;
5136 struct commit_list *tips = NULL, **tips_tail = &tips;
5137 struct commit *commit;
5138 struct oidmap commit2todo = OIDMAP_INIT;
5139 struct string_entry *entry;
5140 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5141 shown = OIDSET_INIT;
5142 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5144 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5145 const char *cmd_pick = abbr ? "p" : "pick",
5146 *cmd_label = abbr ? "l" : "label",
5147 *cmd_reset = abbr ? "t" : "reset",
5148 *cmd_merge = abbr ? "m" : "merge";
5150 oidmap_init(&commit2todo, 0);
5151 oidmap_init(&state.commit2label, 0);
5152 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5153 strbuf_init(&state.buf, 32);
5155 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5156 struct labels_entry *onto_label_entry;
5157 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5158 FLEX_ALLOC_STR(entry, string, "onto");
5159 oidcpy(&entry->entry.oid, oid);
5160 oidmap_put(&state.commit2label, entry);
5162 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5163 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5164 hashmap_add(&state.labels, &onto_label_entry->entry);
5168 * First phase:
5169 * - get onelines for all commits
5170 * - gather all branch tips (i.e. 2nd or later parents of merges)
5171 * - label all branch tips
5173 while ((commit = get_revision(revs))) {
5174 struct commit_list *to_merge;
5175 const char *p1, *p2;
5176 struct object_id *oid;
5177 int is_empty;
5179 tail = &commit_list_insert(commit, tail)->next;
5180 oidset_insert(&interesting, &commit->object.oid);
5182 is_empty = is_original_commit_empty(commit);
5183 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5184 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5185 warning(_("skipped previously applied commit %s"),
5186 short_commit_name(commit));
5187 skipped_commit = 1;
5188 continue;
5190 if (is_empty && !keep_empty)
5191 continue;
5193 strbuf_reset(&oneline);
5194 pretty_print_commit(pp, commit, &oneline);
5196 to_merge = commit->parents ? commit->parents->next : NULL;
5197 if (!to_merge) {
5198 /* non-merge commit: easy case */
5199 strbuf_reset(&buf);
5200 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5201 oid_to_hex(&commit->object.oid),
5202 oneline.buf);
5203 if (is_empty)
5204 strbuf_addf(&buf, " %c empty",
5205 comment_line_char);
5207 FLEX_ALLOC_STR(entry, string, buf.buf);
5208 oidcpy(&entry->entry.oid, &commit->object.oid);
5209 oidmap_put(&commit2todo, entry);
5211 continue;
5214 /* Create a label */
5215 strbuf_reset(&label);
5216 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5217 (p1 = strchr(p1, '\'')) &&
5218 (p2 = strchr(++p1, '\'')))
5219 strbuf_add(&label, p1, p2 - p1);
5220 else if (skip_prefix(oneline.buf, "Merge pull request ",
5221 &p1) &&
5222 (p1 = strstr(p1, " from ")))
5223 strbuf_addstr(&label, p1 + strlen(" from "));
5224 else
5225 strbuf_addbuf(&label, &oneline);
5227 strbuf_reset(&buf);
5228 strbuf_addf(&buf, "%s -C %s",
5229 cmd_merge, oid_to_hex(&commit->object.oid));
5231 /* label the tips of merged branches */
5232 for (; to_merge; to_merge = to_merge->next) {
5233 oid = &to_merge->item->object.oid;
5234 strbuf_addch(&buf, ' ');
5236 if (!oidset_contains(&interesting, oid)) {
5237 strbuf_addstr(&buf, label_oid(oid, NULL,
5238 &state));
5239 continue;
5242 tips_tail = &commit_list_insert(to_merge->item,
5243 tips_tail)->next;
5245 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5247 strbuf_addf(&buf, " # %s", oneline.buf);
5249 FLEX_ALLOC_STR(entry, string, buf.buf);
5250 oidcpy(&entry->entry.oid, &commit->object.oid);
5251 oidmap_put(&commit2todo, entry);
5253 if (skipped_commit)
5254 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5255 _("use --reapply-cherry-picks to include skipped commits"));
5258 * Second phase:
5259 * - label branch points
5260 * - add HEAD to the branch tips
5262 for (iter = commits; iter; iter = iter->next) {
5263 struct commit_list *parent = iter->item->parents;
5264 for (; parent; parent = parent->next) {
5265 struct object_id *oid = &parent->item->object.oid;
5266 if (!oidset_contains(&interesting, oid))
5267 continue;
5268 if (oidset_insert(&child_seen, oid))
5269 label_oid(oid, "branch-point", &state);
5272 /* Add HEAD as implicit "tip of branch" */
5273 if (!iter->next)
5274 tips_tail = &commit_list_insert(iter->item,
5275 tips_tail)->next;
5279 * Third phase: output the todo list. This is a bit tricky, as we
5280 * want to avoid jumping back and forth between revisions. To
5281 * accomplish that goal, we walk backwards from the branch tips,
5282 * gathering commits not yet shown, reversing the list on the fly,
5283 * then outputting that list (labeling revisions as needed).
5285 strbuf_addf(out, "%s onto\n", cmd_label);
5286 for (iter = tips; iter; iter = iter->next) {
5287 struct commit_list *list = NULL, *iter2;
5289 commit = iter->item;
5290 if (oidset_contains(&shown, &commit->object.oid))
5291 continue;
5292 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5294 if (entry)
5295 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5296 else
5297 strbuf_addch(out, '\n');
5299 while (oidset_contains(&interesting, &commit->object.oid) &&
5300 !oidset_contains(&shown, &commit->object.oid)) {
5301 commit_list_insert(commit, &list);
5302 if (!commit->parents) {
5303 commit = NULL;
5304 break;
5306 commit = commit->parents->item;
5309 if (!commit)
5310 strbuf_addf(out, "%s %s\n", cmd_reset,
5311 rebase_cousins || root_with_onto ?
5312 "onto" : "[new root]");
5313 else {
5314 const char *to = NULL;
5316 entry = oidmap_get(&state.commit2label,
5317 &commit->object.oid);
5318 if (entry)
5319 to = entry->string;
5320 else if (!rebase_cousins)
5321 to = label_oid(&commit->object.oid, NULL,
5322 &state);
5324 if (!to || !strcmp(to, "onto"))
5325 strbuf_addf(out, "%s onto\n", cmd_reset);
5326 else {
5327 strbuf_reset(&oneline);
5328 pretty_print_commit(pp, commit, &oneline);
5329 strbuf_addf(out, "%s %s # %s\n",
5330 cmd_reset, to, oneline.buf);
5334 for (iter2 = list; iter2; iter2 = iter2->next) {
5335 struct object_id *oid = &iter2->item->object.oid;
5336 entry = oidmap_get(&commit2todo, oid);
5337 /* only show if not already upstream */
5338 if (entry)
5339 strbuf_addf(out, "%s\n", entry->string);
5340 entry = oidmap_get(&state.commit2label, oid);
5341 if (entry)
5342 strbuf_addf(out, "%s %s\n",
5343 cmd_label, entry->string);
5344 oidset_insert(&shown, oid);
5347 free_commit_list(list);
5350 free_commit_list(commits);
5351 free_commit_list(tips);
5353 strbuf_release(&label);
5354 strbuf_release(&oneline);
5355 strbuf_release(&buf);
5357 oidmap_free(&commit2todo, 1);
5358 oidmap_free(&state.commit2label, 1);
5359 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5360 strbuf_release(&state.buf);
5362 return 0;
5365 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5366 const char **argv, unsigned flags)
5368 char *format = NULL;
5369 struct pretty_print_context pp = {0};
5370 struct rev_info revs;
5371 struct commit *commit;
5372 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5373 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5374 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5375 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5376 int skipped_commit = 0;
5378 repo_init_revisions(r, &revs, NULL);
5379 revs.verbose_header = 1;
5380 if (!rebase_merges)
5381 revs.max_parents = 1;
5382 revs.cherry_mark = !reapply_cherry_picks;
5383 revs.limited = 1;
5384 revs.reverse = 1;
5385 revs.right_only = 1;
5386 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5387 revs.topo_order = 1;
5389 revs.pretty_given = 1;
5390 git_config_get_string("rebase.instructionFormat", &format);
5391 if (!format || !*format) {
5392 free(format);
5393 format = xstrdup("%s");
5395 get_commit_format(format, &revs);
5396 free(format);
5397 pp.fmt = revs.commit_format;
5398 pp.output_encoding = get_log_output_encoding();
5400 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5401 return error(_("make_script: unhandled options"));
5403 if (prepare_revision_walk(&revs) < 0)
5404 return error(_("make_script: error preparing revisions"));
5406 if (rebase_merges)
5407 return make_script_with_merges(&pp, &revs, out, flags);
5409 while ((commit = get_revision(&revs))) {
5410 int is_empty = is_original_commit_empty(commit);
5412 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5413 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5414 warning(_("skipped previously applied commit %s"),
5415 short_commit_name(commit));
5416 skipped_commit = 1;
5417 continue;
5419 if (is_empty && !keep_empty)
5420 continue;
5421 strbuf_addf(out, "%s %s ", insn,
5422 oid_to_hex(&commit->object.oid));
5423 pretty_print_commit(&pp, commit, out);
5424 if (is_empty)
5425 strbuf_addf(out, " %c empty", comment_line_char);
5426 strbuf_addch(out, '\n');
5428 if (skipped_commit)
5429 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5430 _("use --reapply-cherry-picks to include skipped commits"));
5431 return 0;
5435 * Add commands after pick and (series of) squash/fixup commands
5436 * in the todo list.
5438 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5439 struct string_list *commands)
5441 struct strbuf *buf = &todo_list->buf;
5442 size_t base_offset = buf->len;
5443 int i, insert, nr = 0, alloc = 0;
5444 struct todo_item *items = NULL, *base_items = NULL;
5446 CALLOC_ARRAY(base_items, commands->nr);
5447 for (i = 0; i < commands->nr; i++) {
5448 size_t command_len = strlen(commands->items[i].string);
5450 strbuf_addstr(buf, commands->items[i].string);
5451 strbuf_addch(buf, '\n');
5453 base_items[i].command = TODO_EXEC;
5454 base_items[i].offset_in_buf = base_offset;
5455 base_items[i].arg_offset = base_offset + strlen("exec ");
5456 base_items[i].arg_len = command_len - strlen("exec ");
5458 base_offset += command_len + 1;
5462 * Insert <commands> after every pick. Here, fixup/squash chains
5463 * are considered part of the pick, so we insert the commands *after*
5464 * those chains if there are any.
5466 * As we insert the exec commands immediately after rearranging
5467 * any fixups and before the user edits the list, a fixup chain
5468 * can never contain comments (any comments are empty picks that
5469 * have been commented out because the user did not specify
5470 * --keep-empty). So, it is safe to insert an exec command
5471 * without looking at the command following a comment.
5473 insert = 0;
5474 for (i = 0; i < todo_list->nr; i++) {
5475 enum todo_command command = todo_list->items[i].command;
5476 if (insert && !is_fixup(command)) {
5477 ALLOC_GROW(items, nr + commands->nr, alloc);
5478 COPY_ARRAY(items + nr, base_items, commands->nr);
5479 nr += commands->nr;
5481 insert = 0;
5484 ALLOC_GROW(items, nr + 1, alloc);
5485 items[nr++] = todo_list->items[i];
5487 if (command == TODO_PICK || command == TODO_MERGE)
5488 insert = 1;
5491 /* insert or append final <commands> */
5492 if (insert) {
5493 ALLOC_GROW(items, nr + commands->nr, alloc);
5494 COPY_ARRAY(items + nr, base_items, commands->nr);
5495 nr += commands->nr;
5498 free(base_items);
5499 FREE_AND_NULL(todo_list->items);
5500 todo_list->items = items;
5501 todo_list->nr = nr;
5502 todo_list->alloc = alloc;
5505 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5506 struct strbuf *buf, int num, unsigned flags)
5508 struct todo_item *item;
5509 int i, max = todo_list->nr;
5511 if (num > 0 && num < max)
5512 max = num;
5514 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5515 char cmd;
5517 /* if the item is not a command write it and continue */
5518 if (item->command >= TODO_COMMENT) {
5519 strbuf_addf(buf, "%.*s\n", item->arg_len,
5520 todo_item_get_arg(todo_list, item));
5521 continue;
5524 /* add command to the buffer */
5525 cmd = command_to_char(item->command);
5526 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5527 strbuf_addch(buf, cmd);
5528 else
5529 strbuf_addstr(buf, command_to_string(item->command));
5531 /* add commit id */
5532 if (item->commit) {
5533 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5534 short_commit_name(item->commit) :
5535 oid_to_hex(&item->commit->object.oid);
5537 if (item->command == TODO_FIXUP) {
5538 if (item->flags & TODO_EDIT_FIXUP_MSG)
5539 strbuf_addstr(buf, " -c");
5540 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5541 strbuf_addstr(buf, " -C");
5545 if (item->command == TODO_MERGE) {
5546 if (item->flags & TODO_EDIT_MERGE_MSG)
5547 strbuf_addstr(buf, " -c");
5548 else
5549 strbuf_addstr(buf, " -C");
5552 strbuf_addf(buf, " %s", oid);
5555 /* add all the rest */
5556 if (!item->arg_len)
5557 strbuf_addch(buf, '\n');
5558 else
5559 strbuf_addf(buf, " %.*s\n", item->arg_len,
5560 todo_item_get_arg(todo_list, item));
5564 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5565 const char *file, const char *shortrevisions,
5566 const char *shortonto, int num, unsigned flags)
5568 int res;
5569 struct strbuf buf = STRBUF_INIT;
5571 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5572 if (flags & TODO_LIST_APPEND_TODO_HELP)
5573 append_todo_help(count_commands(todo_list),
5574 shortrevisions, shortonto, &buf);
5576 res = write_message(buf.buf, buf.len, file, 0);
5577 strbuf_release(&buf);
5579 return res;
5582 /* skip picking commits whose parents are unchanged */
5583 static int skip_unnecessary_picks(struct repository *r,
5584 struct todo_list *todo_list,
5585 struct object_id *base_oid)
5587 struct object_id *parent_oid;
5588 int i;
5590 for (i = 0; i < todo_list->nr; i++) {
5591 struct todo_item *item = todo_list->items + i;
5593 if (item->command >= TODO_NOOP)
5594 continue;
5595 if (item->command != TODO_PICK)
5596 break;
5597 if (parse_commit(item->commit)) {
5598 return error(_("could not parse commit '%s'"),
5599 oid_to_hex(&item->commit->object.oid));
5601 if (!item->commit->parents)
5602 break; /* root commit */
5603 if (item->commit->parents->next)
5604 break; /* merge commit */
5605 parent_oid = &item->commit->parents->item->object.oid;
5606 if (!oideq(parent_oid, base_oid))
5607 break;
5608 oidcpy(base_oid, &item->commit->object.oid);
5610 if (i > 0) {
5611 const char *done_path = rebase_path_done();
5613 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5614 error_errno(_("could not write to '%s'"), done_path);
5615 return -1;
5618 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5619 todo_list->nr -= i;
5620 todo_list->current = 0;
5621 todo_list->done_nr += i;
5623 if (is_fixup(peek_command(todo_list, 0)))
5624 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5627 return 0;
5630 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5631 const char *shortrevisions, const char *onto_name,
5632 struct commit *onto, const struct object_id *orig_head,
5633 struct string_list *commands, unsigned autosquash,
5634 struct todo_list *todo_list)
5636 char shortonto[GIT_MAX_HEXSZ + 1];
5637 const char *todo_file = rebase_path_todo();
5638 struct todo_list new_todo = TODO_LIST_INIT;
5639 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5640 struct object_id oid = onto->object.oid;
5641 int res;
5643 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5645 if (buf->len == 0) {
5646 struct todo_item *item = append_new_todo(todo_list);
5647 item->command = TODO_NOOP;
5648 item->commit = NULL;
5649 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5652 if (autosquash && todo_list_rearrange_squash(todo_list))
5653 return -1;
5655 if (commands->nr)
5656 todo_list_add_exec_commands(todo_list, commands);
5658 if (count_commands(todo_list) == 0) {
5659 apply_autostash(rebase_path_autostash());
5660 sequencer_remove_state(opts);
5662 return error(_("nothing to do"));
5665 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5666 shortonto, flags);
5667 if (res == -1)
5668 return -1;
5669 else if (res == -2) {
5670 apply_autostash(rebase_path_autostash());
5671 sequencer_remove_state(opts);
5673 return -1;
5674 } else if (res == -3) {
5675 apply_autostash(rebase_path_autostash());
5676 sequencer_remove_state(opts);
5677 todo_list_release(&new_todo);
5679 return error(_("nothing to do"));
5680 } else if (res == -4) {
5681 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5682 todo_list_release(&new_todo);
5684 return -1;
5687 /* Expand the commit IDs */
5688 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5689 strbuf_swap(&new_todo.buf, &buf2);
5690 strbuf_release(&buf2);
5691 new_todo.total_nr -= new_todo.nr;
5692 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5693 BUG("invalid todo list after expanding IDs:\n%s",
5694 new_todo.buf.buf);
5696 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5697 todo_list_release(&new_todo);
5698 return error(_("could not skip unnecessary pick commands"));
5701 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5702 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5703 todo_list_release(&new_todo);
5704 return error_errno(_("could not write '%s'"), todo_file);
5707 res = -1;
5709 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5710 goto cleanup;
5712 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5713 goto cleanup;
5715 todo_list_write_total_nr(&new_todo);
5716 res = pick_commits(r, &new_todo, opts);
5718 cleanup:
5719 todo_list_release(&new_todo);
5721 return res;
5724 struct subject2item_entry {
5725 struct hashmap_entry entry;
5726 int i;
5727 char subject[FLEX_ARRAY];
5730 static int subject2item_cmp(const void *fndata,
5731 const struct hashmap_entry *eptr,
5732 const struct hashmap_entry *entry_or_key,
5733 const void *key)
5735 const struct subject2item_entry *a, *b;
5737 a = container_of(eptr, const struct subject2item_entry, entry);
5738 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5740 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5743 define_commit_slab(commit_todo_item, struct todo_item *);
5745 static int skip_fixupish(const char *subject, const char **p) {
5746 return skip_prefix(subject, "fixup! ", p) ||
5747 skip_prefix(subject, "amend! ", p) ||
5748 skip_prefix(subject, "squash! ", p);
5752 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5753 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5754 * after the former, and change "pick" to "fixup"/"squash".
5756 * Note that if the config has specified a custom instruction format, each log
5757 * message will have to be retrieved from the commit (as the oneline in the
5758 * script cannot be trusted) in order to normalize the autosquash arrangement.
5760 int todo_list_rearrange_squash(struct todo_list *todo_list)
5762 struct hashmap subject2item;
5763 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5764 char **subjects;
5765 struct commit_todo_item commit_todo;
5766 struct todo_item *items = NULL;
5768 init_commit_todo_item(&commit_todo);
5770 * The hashmap maps onelines to the respective todo list index.
5772 * If any items need to be rearranged, the next[i] value will indicate
5773 * which item was moved directly after the i'th.
5775 * In that case, last[i] will indicate the index of the latest item to
5776 * be moved to appear after the i'th.
5778 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5779 ALLOC_ARRAY(next, todo_list->nr);
5780 ALLOC_ARRAY(tail, todo_list->nr);
5781 ALLOC_ARRAY(subjects, todo_list->nr);
5782 for (i = 0; i < todo_list->nr; i++) {
5783 struct strbuf buf = STRBUF_INIT;
5784 struct todo_item *item = todo_list->items + i;
5785 const char *commit_buffer, *subject, *p;
5786 size_t subject_len;
5787 int i2 = -1;
5788 struct subject2item_entry *entry;
5790 next[i] = tail[i] = -1;
5791 if (!item->commit || item->command == TODO_DROP) {
5792 subjects[i] = NULL;
5793 continue;
5796 if (is_fixup(item->command)) {
5797 clear_commit_todo_item(&commit_todo);
5798 return error(_("the script was already rearranged."));
5801 *commit_todo_item_at(&commit_todo, item->commit) = item;
5803 parse_commit(item->commit);
5804 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5805 find_commit_subject(commit_buffer, &subject);
5806 format_subject(&buf, subject, " ");
5807 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5808 unuse_commit_buffer(item->commit, commit_buffer);
5809 if (skip_fixupish(subject, &p)) {
5810 struct commit *commit2;
5812 for (;;) {
5813 while (isspace(*p))
5814 p++;
5815 if (!skip_fixupish(p, &p))
5816 break;
5819 entry = hashmap_get_entry_from_hash(&subject2item,
5820 strhash(p), p,
5821 struct subject2item_entry,
5822 entry);
5823 if (entry)
5824 /* found by title */
5825 i2 = entry->i;
5826 else if (!strchr(p, ' ') &&
5827 (commit2 =
5828 lookup_commit_reference_by_name(p)) &&
5829 *commit_todo_item_at(&commit_todo, commit2))
5830 /* found by commit name */
5831 i2 = *commit_todo_item_at(&commit_todo, commit2)
5832 - todo_list->items;
5833 else {
5834 /* copy can be a prefix of the commit subject */
5835 for (i2 = 0; i2 < i; i2++)
5836 if (subjects[i2] &&
5837 starts_with(subjects[i2], p))
5838 break;
5839 if (i2 == i)
5840 i2 = -1;
5843 if (i2 >= 0) {
5844 rearranged = 1;
5845 if (starts_with(subject, "fixup!")) {
5846 todo_list->items[i].command = TODO_FIXUP;
5847 } else if (starts_with(subject, "amend!")) {
5848 todo_list->items[i].command = TODO_FIXUP;
5849 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5850 } else {
5851 todo_list->items[i].command = TODO_SQUASH;
5853 if (tail[i2] < 0) {
5854 next[i] = next[i2];
5855 next[i2] = i;
5856 } else {
5857 next[i] = next[tail[i2]];
5858 next[tail[i2]] = i;
5860 tail[i2] = i;
5861 } else if (!hashmap_get_from_hash(&subject2item,
5862 strhash(subject), subject)) {
5863 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5864 entry->i = i;
5865 hashmap_entry_init(&entry->entry,
5866 strhash(entry->subject));
5867 hashmap_put(&subject2item, &entry->entry);
5871 if (rearranged) {
5872 for (i = 0; i < todo_list->nr; i++) {
5873 enum todo_command command = todo_list->items[i].command;
5874 int cur = i;
5877 * Initially, all commands are 'pick's. If it is a
5878 * fixup or a squash now, we have rearranged it.
5880 if (is_fixup(command))
5881 continue;
5883 while (cur >= 0) {
5884 ALLOC_GROW(items, nr + 1, alloc);
5885 items[nr++] = todo_list->items[cur];
5886 cur = next[cur];
5890 FREE_AND_NULL(todo_list->items);
5891 todo_list->items = items;
5892 todo_list->nr = nr;
5893 todo_list->alloc = alloc;
5896 free(next);
5897 free(tail);
5898 for (i = 0; i < todo_list->nr; i++)
5899 free(subjects[i]);
5900 free(subjects);
5901 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5903 clear_commit_todo_item(&commit_todo);
5905 return 0;
5908 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5910 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5911 struct object_id cherry_pick_head, rebase_head;
5913 if (file_exists(git_path_seq_dir()))
5914 *whence = FROM_CHERRY_PICK_MULTI;
5915 if (file_exists(rebase_path()) &&
5916 !get_oid("REBASE_HEAD", &rebase_head) &&
5917 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5918 oideq(&rebase_head, &cherry_pick_head))
5919 *whence = FROM_REBASE_PICK;
5920 else
5921 *whence = FROM_CHERRY_PICK_SINGLE;
5923 return 1;
5926 return 0;