merge-ort/merge-recursive: do report errors in `merge_submodule()`
[git.git] / sequencer.c
blobd3ca95f4fe0b2b0527c77a7525af71c272c87427
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
14 #include "object.h"
15 #include "pager.h"
16 #include "commit.h"
17 #include "sequencer.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "utf8.h"
21 #include "cache-tree.h"
22 #include "diff.h"
23 #include "path.h"
24 #include "revision.h"
25 #include "rerere.h"
26 #include "merge.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
29 #include "refs.h"
30 #include "sparse-index.h"
31 #include "strvec.h"
32 #include "quote.h"
33 #include "trailer.h"
34 #include "log-tree.h"
35 #include "wt-status.h"
36 #include "hashmap.h"
37 #include "notes-utils.h"
38 #include "sigchain.h"
39 #include "unpack-trees.h"
40 #include "oidmap.h"
41 #include "oidset.h"
42 #include "commit-slab.h"
43 #include "alias.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
46 #include "reset.h"
47 #include "branch.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
55 * are too long.
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
87 * actions.
89 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
92 * for the prompt).
94 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
130 * being rebased.
132 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189 * The following files are written by git-rebase just after parsing the
190 * command-line.
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
211 * A 'struct update_refs_record' represents a value in the update-refs
212 * list. We use a string_list to map refs to these (before, after) pairs.
214 struct update_ref_record {
215 struct object_id before;
216 struct object_id after;
219 static struct update_ref_record *init_update_ref_record(const char *ref)
221 struct update_ref_record *rec;
223 CALLOC_ARRAY(rec, 1);
225 oidcpy(&rec->before, null_oid());
226 oidcpy(&rec->after, null_oid());
228 /* This may fail, but that's fine, we will keep the null OID. */
229 read_ref(ref, &rec->before);
231 return rec;
234 static int git_sequencer_config(const char *k, const char *v,
235 const struct config_context *ctx, void *cb)
237 struct replay_opts *opts = cb;
239 if (!strcmp(k, "commit.cleanup")) {
240 if (!v)
241 return config_error_nonbool(k);
243 if (!strcmp(v, "verbatim")) {
244 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
245 opts->explicit_cleanup = 1;
246 } else if (!strcmp(v, "whitespace")) {
247 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
248 opts->explicit_cleanup = 1;
249 } else if (!strcmp(v, "strip")) {
250 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
251 opts->explicit_cleanup = 1;
252 } else if (!strcmp(v, "scissors")) {
253 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
254 opts->explicit_cleanup = 1;
255 } else {
256 warning(_("invalid commit message cleanup mode '%s'"),
260 return 0;
263 if (!strcmp(k, "commit.gpgsign")) {
264 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
265 return 0;
268 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
269 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
270 if (ret == 0) {
272 * pull.twohead is allowed to be multi-valued; we only
273 * care about the first value.
275 char *tmp = strchr(opts->default_strategy, ' ');
276 if (tmp)
277 *tmp = '\0';
279 return ret;
282 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
283 opts->commit_use_reference = git_config_bool(k, v);
285 return git_diff_basic_config(k, v, ctx, NULL);
288 void sequencer_init_config(struct replay_opts *opts)
290 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
291 git_config(git_sequencer_config, opts);
294 static inline int is_rebase_i(const struct replay_opts *opts)
296 return opts->action == REPLAY_INTERACTIVE_REBASE;
299 static const char *get_dir(const struct replay_opts *opts)
301 if (is_rebase_i(opts))
302 return rebase_path();
303 return git_path_seq_dir();
306 static const char *get_todo_path(const struct replay_opts *opts)
308 if (is_rebase_i(opts))
309 return rebase_path_todo();
310 return git_path_todo_file();
314 * Returns 0 for non-conforming footer
315 * Returns 1 for conforming footer
316 * Returns 2 when sob exists within conforming footer
317 * Returns 3 when sob exists within conforming footer as last entry
319 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
320 size_t ignore_footer)
322 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
323 struct trailer_info info;
324 size_t i;
325 int found_sob = 0, found_sob_last = 0;
326 char saved_char;
328 opts.no_divider = 1;
330 if (ignore_footer) {
331 saved_char = sb->buf[sb->len - ignore_footer];
332 sb->buf[sb->len - ignore_footer] = '\0';
335 trailer_info_get(&info, sb->buf, &opts);
337 if (ignore_footer)
338 sb->buf[sb->len - ignore_footer] = saved_char;
340 if (info.trailer_block_start == info.trailer_block_end)
341 return 0;
343 for (i = 0; i < info.trailer_nr; i++)
344 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
345 found_sob = 1;
346 if (i == info.trailer_nr - 1)
347 found_sob_last = 1;
350 trailer_info_release(&info);
352 if (found_sob_last)
353 return 3;
354 if (found_sob)
355 return 2;
356 return 1;
359 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
361 static struct strbuf buf = STRBUF_INIT;
363 strbuf_reset(&buf);
364 if (opts->gpg_sign)
365 sq_quotef(&buf, "-S%s", opts->gpg_sign);
366 return buf.buf;
369 void replay_opts_release(struct replay_opts *opts)
371 free(opts->gpg_sign);
372 free(opts->reflog_action);
373 free(opts->default_strategy);
374 free(opts->strategy);
375 strvec_clear (&opts->xopts);
376 strbuf_release(&opts->current_fixups);
377 if (opts->revs)
378 release_revisions(opts->revs);
379 free(opts->revs);
382 int sequencer_remove_state(struct replay_opts *opts)
384 struct strbuf buf = STRBUF_INIT;
385 int ret = 0;
387 if (is_rebase_i(opts) &&
388 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
389 char *p = buf.buf;
390 while (*p) {
391 char *eol = strchr(p, '\n');
392 if (eol)
393 *eol = '\0';
394 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
395 warning(_("could not delete '%s'"), p);
396 ret = -1;
398 if (!eol)
399 break;
400 p = eol + 1;
404 strbuf_reset(&buf);
405 strbuf_addstr(&buf, get_dir(opts));
406 if (remove_dir_recursively(&buf, 0))
407 ret = error(_("could not remove '%s'"), buf.buf);
408 strbuf_release(&buf);
410 return ret;
413 static const char *action_name(const struct replay_opts *opts)
415 switch (opts->action) {
416 case REPLAY_REVERT:
417 return N_("revert");
418 case REPLAY_PICK:
419 return N_("cherry-pick");
420 case REPLAY_INTERACTIVE_REBASE:
421 return N_("rebase");
423 die(_("unknown action: %d"), opts->action);
426 struct commit_message {
427 char *parent_label;
428 char *label;
429 char *subject;
430 const char *message;
433 static const char *short_commit_name(struct repository *r, struct commit *commit)
435 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
438 static int get_message(struct commit *commit, struct commit_message *out)
440 const char *abbrev, *subject;
441 int subject_len;
443 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
444 get_commit_output_encoding());
445 abbrev = short_commit_name(the_repository, commit);
447 subject_len = find_commit_subject(out->message, &subject);
449 out->subject = xmemdupz(subject, subject_len);
450 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
451 out->parent_label = xstrfmt("parent of %s", out->label);
453 return 0;
456 static void free_message(struct commit *commit, struct commit_message *msg)
458 free(msg->parent_label);
459 free(msg->label);
460 free(msg->subject);
461 repo_unuse_commit_buffer(the_repository, commit, msg->message);
464 static void print_advice(struct repository *r, int show_hint,
465 struct replay_opts *opts)
467 char *msg = getenv("GIT_CHERRY_PICK_HELP");
469 if (msg) {
470 advise("%s\n", msg);
472 * A conflict has occurred but the porcelain
473 * (typically rebase --interactive) wants to take care
474 * of the commit itself so remove CHERRY_PICK_HEAD
476 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
477 NULL, REF_NO_DEREF);
478 return;
481 if (show_hint) {
482 if (opts->no_commit)
483 advise(_("after resolving the conflicts, mark the corrected paths\n"
484 "with 'git add <paths>' or 'git rm <paths>'"));
485 else if (opts->action == REPLAY_PICK)
486 advise(_("After resolving the conflicts, mark them with\n"
487 "\"git add/rm <pathspec>\", then run\n"
488 "\"git cherry-pick --continue\".\n"
489 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
490 "To abort and get back to the state before \"git cherry-pick\",\n"
491 "run \"git cherry-pick --abort\"."));
492 else if (opts->action == REPLAY_REVERT)
493 advise(_("After resolving the conflicts, mark them with\n"
494 "\"git add/rm <pathspec>\", then run\n"
495 "\"git revert --continue\".\n"
496 "You can instead skip this commit with \"git revert --skip\".\n"
497 "To abort and get back to the state before \"git revert\",\n"
498 "run \"git revert --abort\"."));
499 else
500 BUG("unexpected pick action in print_advice()");
504 static int write_message(const void *buf, size_t len, const char *filename,
505 int append_eol)
507 struct lock_file msg_file = LOCK_INIT;
509 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
510 if (msg_fd < 0)
511 return error_errno(_("could not lock '%s'"), filename);
512 if (write_in_full(msg_fd, buf, len) < 0) {
513 error_errno(_("could not write to '%s'"), filename);
514 rollback_lock_file(&msg_file);
515 return -1;
517 if (append_eol && write(msg_fd, "\n", 1) < 0) {
518 error_errno(_("could not write eol to '%s'"), filename);
519 rollback_lock_file(&msg_file);
520 return -1;
522 if (commit_lock_file(&msg_file) < 0)
523 return error(_("failed to finalize '%s'"), filename);
525 return 0;
528 int read_oneliner(struct strbuf *buf,
529 const char *path, unsigned flags)
531 int orig_len = buf->len;
533 if (strbuf_read_file(buf, path, 0) < 0) {
534 if ((flags & READ_ONELINER_WARN_MISSING) ||
535 (errno != ENOENT && errno != ENOTDIR))
536 warning_errno(_("could not read '%s'"), path);
537 return 0;
540 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
541 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
542 --buf->len;
543 buf->buf[buf->len] = '\0';
546 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
547 return 0;
549 return 1;
552 static struct tree *empty_tree(struct repository *r)
554 return lookup_tree(r, the_hash_algo->empty_tree);
557 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
559 if (repo_read_index_unmerged(repo))
560 return error_resolve_conflict(action_name(opts));
562 error(_("your local changes would be overwritten by %s."),
563 _(action_name(opts)));
565 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
566 advise(_("commit your changes or stash them to proceed."));
567 return -1;
570 static void update_abort_safety_file(void)
572 struct object_id head;
574 /* Do nothing on a single-pick */
575 if (!file_exists(git_path_seq_dir()))
576 return;
578 if (!repo_get_oid(the_repository, "HEAD", &head))
579 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
580 else
581 write_file(git_path_abort_safety_file(), "%s", "");
584 static int fast_forward_to(struct repository *r,
585 const struct object_id *to,
586 const struct object_id *from,
587 int unborn,
588 struct replay_opts *opts)
590 struct ref_transaction *transaction;
591 struct strbuf sb = STRBUF_INIT;
592 struct strbuf err = STRBUF_INIT;
594 repo_read_index(r);
595 if (checkout_fast_forward(r, from, to, 1))
596 return -1; /* the callee should have complained already */
598 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
600 transaction = ref_transaction_begin(&err);
601 if (!transaction ||
602 ref_transaction_update(transaction, "HEAD",
603 to, unborn && !is_rebase_i(opts) ?
604 null_oid() : from,
605 0, sb.buf, &err) ||
606 ref_transaction_commit(transaction, &err)) {
607 ref_transaction_free(transaction);
608 error("%s", err.buf);
609 strbuf_release(&sb);
610 strbuf_release(&err);
611 return -1;
614 strbuf_release(&sb);
615 strbuf_release(&err);
616 ref_transaction_free(transaction);
617 update_abort_safety_file();
618 return 0;
621 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
622 int use_editor)
624 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
625 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
626 COMMIT_MSG_CLEANUP_SPACE;
627 else if (!strcmp(cleanup_arg, "verbatim"))
628 return COMMIT_MSG_CLEANUP_NONE;
629 else if (!strcmp(cleanup_arg, "whitespace"))
630 return COMMIT_MSG_CLEANUP_SPACE;
631 else if (!strcmp(cleanup_arg, "strip"))
632 return COMMIT_MSG_CLEANUP_ALL;
633 else if (!strcmp(cleanup_arg, "scissors"))
634 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
635 COMMIT_MSG_CLEANUP_SPACE;
636 else
637 die(_("Invalid cleanup mode %s"), cleanup_arg);
641 * NB using int rather than enum cleanup_mode to stop clang's
642 * -Wtautological-constant-out-of-range-compare complaining that the comparison
643 * is always true.
645 static const char *describe_cleanup_mode(int cleanup_mode)
647 static const char *modes[] = { "whitespace",
648 "verbatim",
649 "scissors",
650 "strip" };
652 if (cleanup_mode < ARRAY_SIZE(modes))
653 return modes[cleanup_mode];
655 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
658 void append_conflicts_hint(struct index_state *istate,
659 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
661 int i;
663 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
664 strbuf_addch(msgbuf, '\n');
665 wt_status_append_cut_line(msgbuf);
666 strbuf_addch(msgbuf, comment_line_char);
669 strbuf_addch(msgbuf, '\n');
670 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
671 for (i = 0; i < istate->cache_nr;) {
672 const struct cache_entry *ce = istate->cache[i++];
673 if (ce_stage(ce)) {
674 strbuf_commented_addf(msgbuf, comment_line_char,
675 "\t%s\n", ce->name);
676 while (i < istate->cache_nr &&
677 !strcmp(ce->name, istate->cache[i]->name))
678 i++;
683 static int do_recursive_merge(struct repository *r,
684 struct commit *base, struct commit *next,
685 const char *base_label, const char *next_label,
686 struct object_id *head, struct strbuf *msgbuf,
687 struct replay_opts *opts)
689 struct merge_options o;
690 struct merge_result result;
691 struct tree *next_tree, *base_tree, *head_tree;
692 int clean, show_output;
693 int i;
694 struct lock_file index_lock = LOCK_INIT;
696 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
697 return -1;
699 repo_read_index(r);
701 init_merge_options(&o, r);
702 o.ancestor = base ? base_label : "(empty tree)";
703 o.branch1 = "HEAD";
704 o.branch2 = next ? next_label : "(empty tree)";
705 if (is_rebase_i(opts))
706 o.buffer_output = 2;
707 o.show_rename_progress = 1;
709 head_tree = parse_tree_indirect(head);
710 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
711 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
713 for (i = 0; i < opts->xopts.nr; i++)
714 parse_merge_opt(&o, opts->xopts.v[i]);
716 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
717 memset(&result, 0, sizeof(result));
718 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
719 &result);
720 show_output = !is_rebase_i(opts) || !result.clean;
722 * TODO: merge_switch_to_result will update index/working tree;
723 * we only really want to do that if !result.clean || this is
724 * the final patch to be picked. But determining this is the
725 * final patch would take some work, and "head_tree" would need
726 * to be replace with the tree the index matched before we
727 * started doing any picks.
729 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
730 clean = result.clean;
731 } else {
732 ensure_full_index(r->index);
733 clean = merge_trees(&o, head_tree, next_tree, base_tree);
734 if (is_rebase_i(opts) && clean <= 0)
735 fputs(o.obuf.buf, stdout);
736 strbuf_release(&o.obuf);
738 if (clean < 0) {
739 rollback_lock_file(&index_lock);
740 return clean;
743 if (write_locked_index(r->index, &index_lock,
744 COMMIT_LOCK | SKIP_IF_UNCHANGED))
746 * TRANSLATORS: %s will be "revert", "cherry-pick" or
747 * "rebase".
749 return error(_("%s: Unable to write new index file"),
750 _(action_name(opts)));
752 if (!clean)
753 append_conflicts_hint(r->index, msgbuf,
754 opts->default_msg_cleanup);
756 return !clean;
759 static struct object_id *get_cache_tree_oid(struct index_state *istate)
761 if (!cache_tree_fully_valid(istate->cache_tree))
762 if (cache_tree_update(istate, 0)) {
763 error(_("unable to update cache tree"));
764 return NULL;
767 return &istate->cache_tree->oid;
770 static int is_index_unchanged(struct repository *r)
772 struct object_id head_oid, *cache_tree_oid;
773 struct commit *head_commit;
774 struct index_state *istate = r->index;
776 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
777 return error(_("could not resolve HEAD commit"));
779 head_commit = lookup_commit(r, &head_oid);
782 * If head_commit is NULL, check_commit, called from
783 * lookup_commit, would have indicated that head_commit is not
784 * a commit object already. repo_parse_commit() will return failure
785 * without further complaints in such a case. Otherwise, if
786 * the commit is invalid, repo_parse_commit() will complain. So
787 * there is nothing for us to say here. Just return failure.
789 if (repo_parse_commit(r, head_commit))
790 return -1;
792 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
793 return -1;
795 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
798 static int write_author_script(const char *message)
800 struct strbuf buf = STRBUF_INIT;
801 const char *eol;
802 int res;
804 for (;;)
805 if (!*message || starts_with(message, "\n")) {
806 missing_author:
807 /* Missing 'author' line? */
808 unlink(rebase_path_author_script());
809 return 0;
810 } else if (skip_prefix(message, "author ", &message))
811 break;
812 else if ((eol = strchr(message, '\n')))
813 message = eol + 1;
814 else
815 goto missing_author;
817 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
818 while (*message && *message != '\n' && *message != '\r')
819 if (skip_prefix(message, " <", &message))
820 break;
821 else if (*message != '\'')
822 strbuf_addch(&buf, *(message++));
823 else
824 strbuf_addf(&buf, "'\\%c'", *(message++));
825 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
826 while (*message && *message != '\n' && *message != '\r')
827 if (skip_prefix(message, "> ", &message))
828 break;
829 else if (*message != '\'')
830 strbuf_addch(&buf, *(message++));
831 else
832 strbuf_addf(&buf, "'\\%c'", *(message++));
833 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
834 while (*message && *message != '\n' && *message != '\r')
835 if (*message != '\'')
836 strbuf_addch(&buf, *(message++));
837 else
838 strbuf_addf(&buf, "'\\%c'", *(message++));
839 strbuf_addch(&buf, '\'');
840 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
841 strbuf_release(&buf);
842 return res;
846 * Take a series of KEY='VALUE' lines where VALUE part is
847 * sq-quoted, and append <KEY, VALUE> at the end of the string list
849 static int parse_key_value_squoted(char *buf, struct string_list *list)
851 while (*buf) {
852 struct string_list_item *item;
853 char *np;
854 char *cp = strchr(buf, '=');
855 if (!cp) {
856 np = strchrnul(buf, '\n');
857 return error(_("no key present in '%.*s'"),
858 (int) (np - buf), buf);
860 np = strchrnul(cp, '\n');
861 *cp++ = '\0';
862 item = string_list_append(list, buf);
864 buf = np + (*np == '\n');
865 *np = '\0';
866 cp = sq_dequote(cp);
867 if (!cp)
868 return error(_("unable to dequote value of '%s'"),
869 item->string);
870 item->util = xstrdup(cp);
872 return 0;
876 * Reads and parses the state directory's "author-script" file, and sets name,
877 * email and date accordingly.
878 * Returns 0 on success, -1 if the file could not be parsed.
880 * The author script is of the format:
882 * GIT_AUTHOR_NAME='$author_name'
883 * GIT_AUTHOR_EMAIL='$author_email'
884 * GIT_AUTHOR_DATE='$author_date'
886 * where $author_name, $author_email and $author_date are quoted. We are strict
887 * with our parsing, as the file was meant to be eval'd in the now-removed
888 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
889 * from what this function expects, it is better to bail out than to do
890 * something that the user does not expect.
892 int read_author_script(const char *path, char **name, char **email, char **date,
893 int allow_missing)
895 struct strbuf buf = STRBUF_INIT;
896 struct string_list kv = STRING_LIST_INIT_DUP;
897 int retval = -1; /* assume failure */
898 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
900 if (strbuf_read_file(&buf, path, 256) <= 0) {
901 strbuf_release(&buf);
902 if (errno == ENOENT && allow_missing)
903 return 0;
904 else
905 return error_errno(_("could not open '%s' for reading"),
906 path);
909 if (parse_key_value_squoted(buf.buf, &kv))
910 goto finish;
912 for (i = 0; i < kv.nr; i++) {
913 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
914 if (name_i != -2)
915 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
916 else
917 name_i = i;
918 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
919 if (email_i != -2)
920 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
921 else
922 email_i = i;
923 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
924 if (date_i != -2)
925 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
926 else
927 date_i = i;
928 } else {
929 err = error(_("unknown variable '%s'"),
930 kv.items[i].string);
933 if (name_i == -2)
934 error(_("missing 'GIT_AUTHOR_NAME'"));
935 if (email_i == -2)
936 error(_("missing 'GIT_AUTHOR_EMAIL'"));
937 if (date_i == -2)
938 error(_("missing 'GIT_AUTHOR_DATE'"));
939 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
940 goto finish;
941 *name = kv.items[name_i].util;
942 *email = kv.items[email_i].util;
943 *date = kv.items[date_i].util;
944 retval = 0;
945 finish:
946 string_list_clear(&kv, !!retval);
947 strbuf_release(&buf);
948 return retval;
952 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
953 * file with shell quoting into struct strvec. Returns -1 on
954 * error, 0 otherwise.
956 static int read_env_script(struct strvec *env)
958 char *name, *email, *date;
960 if (read_author_script(rebase_path_author_script(),
961 &name, &email, &date, 0))
962 return -1;
964 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
965 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
966 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
967 free(name);
968 free(email);
969 free(date);
971 return 0;
974 static char *get_author(const char *message)
976 size_t len;
977 const char *a;
979 a = find_commit_header(message, "author", &len);
980 if (a)
981 return xmemdupz(a, len);
983 return NULL;
986 static const char *author_date_from_env(const struct strvec *env)
988 int i;
989 const char *date;
991 for (i = 0; i < env->nr; i++)
992 if (skip_prefix(env->v[i],
993 "GIT_AUTHOR_DATE=", &date))
994 return date;
996 * If GIT_AUTHOR_DATE is missing we should have already errored out when
997 * reading the script
999 BUG("GIT_AUTHOR_DATE missing from author script");
1002 static const char staged_changes_advice[] =
1003 N_("you have staged changes in your working tree\n"
1004 "If these changes are meant to be squashed into the previous commit, run:\n"
1005 "\n"
1006 " git commit --amend %s\n"
1007 "\n"
1008 "If they are meant to go into a new commit, run:\n"
1009 "\n"
1010 " git commit %s\n"
1011 "\n"
1012 "In both cases, once you're done, continue with:\n"
1013 "\n"
1014 " git rebase --continue\n");
1016 #define ALLOW_EMPTY (1<<0)
1017 #define EDIT_MSG (1<<1)
1018 #define AMEND_MSG (1<<2)
1019 #define CLEANUP_MSG (1<<3)
1020 #define VERIFY_MSG (1<<4)
1021 #define CREATE_ROOT_COMMIT (1<<5)
1022 #define VERBATIM_MSG (1<<6)
1024 static int run_command_silent_on_success(struct child_process *cmd)
1026 struct strbuf buf = STRBUF_INIT;
1027 int rc;
1029 cmd->stdout_to_stderr = 1;
1030 rc = pipe_command(cmd,
1031 NULL, 0,
1032 NULL, 0,
1033 &buf, 0);
1035 if (rc)
1036 fputs(buf.buf, stderr);
1037 strbuf_release(&buf);
1038 return rc;
1042 * If we are cherry-pick, and if the merge did not result in
1043 * hand-editing, we will hit this commit and inherit the original
1044 * author date and name.
1046 * If we are revert, or if our cherry-pick results in a hand merge,
1047 * we had better say that the current user is responsible for that.
1049 * An exception is when run_git_commit() is called during an
1050 * interactive rebase: in that case, we will want to retain the
1051 * author metadata.
1053 static int run_git_commit(const char *defmsg,
1054 struct replay_opts *opts,
1055 unsigned int flags)
1057 struct child_process cmd = CHILD_PROCESS_INIT;
1059 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1060 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1062 cmd.git_cmd = 1;
1064 if (is_rebase_i(opts) &&
1065 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1066 !(!defmsg && (flags & AMEND_MSG))) &&
1067 read_env_script(&cmd.env)) {
1068 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1070 return error(_(staged_changes_advice),
1071 gpg_opt, gpg_opt);
1074 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1076 if (opts->committer_date_is_author_date)
1077 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1078 opts->ignore_date ?
1079 "" :
1080 author_date_from_env(&cmd.env));
1081 if (opts->ignore_date)
1082 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1084 strvec_push(&cmd.args, "commit");
1086 if (!(flags & VERIFY_MSG))
1087 strvec_push(&cmd.args, "-n");
1088 if ((flags & AMEND_MSG))
1089 strvec_push(&cmd.args, "--amend");
1090 if (opts->gpg_sign)
1091 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1092 else
1093 strvec_push(&cmd.args, "--no-gpg-sign");
1094 if (defmsg)
1095 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1096 else if (!(flags & EDIT_MSG))
1097 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1098 if ((flags & CLEANUP_MSG))
1099 strvec_push(&cmd.args, "--cleanup=strip");
1100 if ((flags & VERBATIM_MSG))
1101 strvec_push(&cmd.args, "--cleanup=verbatim");
1102 if ((flags & EDIT_MSG))
1103 strvec_push(&cmd.args, "-e");
1104 else if (!(flags & CLEANUP_MSG) &&
1105 !opts->signoff && !opts->record_origin &&
1106 !opts->explicit_cleanup)
1107 strvec_push(&cmd.args, "--cleanup=verbatim");
1109 if ((flags & ALLOW_EMPTY))
1110 strvec_push(&cmd.args, "--allow-empty");
1112 if (!(flags & EDIT_MSG))
1113 strvec_push(&cmd.args, "--allow-empty-message");
1115 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1116 return run_command_silent_on_success(&cmd);
1117 else
1118 return run_command(&cmd);
1121 static int rest_is_empty(const struct strbuf *sb, int start)
1123 int i, eol;
1124 const char *nl;
1126 /* Check if the rest is just whitespace and Signed-off-by's. */
1127 for (i = start; i < sb->len; i++) {
1128 nl = memchr(sb->buf + i, '\n', sb->len - i);
1129 if (nl)
1130 eol = nl - sb->buf;
1131 else
1132 eol = sb->len;
1134 if (strlen(sign_off_header) <= eol - i &&
1135 starts_with(sb->buf + i, sign_off_header)) {
1136 i = eol;
1137 continue;
1139 while (i < eol)
1140 if (!isspace(sb->buf[i++]))
1141 return 0;
1144 return 1;
1147 void cleanup_message(struct strbuf *msgbuf,
1148 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1150 if (verbose || /* Truncate the message just before the diff, if any. */
1151 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1152 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1153 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1154 strbuf_stripspace(msgbuf,
1155 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1159 * Find out if the message in the strbuf contains only whitespace and
1160 * Signed-off-by lines.
1162 int message_is_empty(const struct strbuf *sb,
1163 enum commit_msg_cleanup_mode cleanup_mode)
1165 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1166 return 0;
1167 return rest_is_empty(sb, 0);
1171 * See if the user edited the message in the editor or left what
1172 * was in the template intact
1174 int template_untouched(const struct strbuf *sb, const char *template_file,
1175 enum commit_msg_cleanup_mode cleanup_mode)
1177 struct strbuf tmpl = STRBUF_INIT;
1178 const char *start;
1180 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1181 return 0;
1183 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1184 return 0;
1186 strbuf_stripspace(&tmpl,
1187 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1188 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1189 start = sb->buf;
1190 strbuf_release(&tmpl);
1191 return rest_is_empty(sb, start - sb->buf);
1194 int update_head_with_reflog(const struct commit *old_head,
1195 const struct object_id *new_head,
1196 const char *action, const struct strbuf *msg,
1197 struct strbuf *err)
1199 struct ref_transaction *transaction;
1200 struct strbuf sb = STRBUF_INIT;
1201 const char *nl;
1202 int ret = 0;
1204 if (action) {
1205 strbuf_addstr(&sb, action);
1206 strbuf_addstr(&sb, ": ");
1209 nl = strchr(msg->buf, '\n');
1210 if (nl) {
1211 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1212 } else {
1213 strbuf_addbuf(&sb, msg);
1214 strbuf_addch(&sb, '\n');
1217 transaction = ref_transaction_begin(err);
1218 if (!transaction ||
1219 ref_transaction_update(transaction, "HEAD", new_head,
1220 old_head ? &old_head->object.oid : null_oid(),
1221 0, sb.buf, err) ||
1222 ref_transaction_commit(transaction, err)) {
1223 ret = -1;
1225 ref_transaction_free(transaction);
1226 strbuf_release(&sb);
1228 return ret;
1231 static int run_rewrite_hook(const struct object_id *oldoid,
1232 const struct object_id *newoid)
1234 struct child_process proc = CHILD_PROCESS_INIT;
1235 int code;
1236 struct strbuf sb = STRBUF_INIT;
1237 const char *hook_path = find_hook("post-rewrite");
1239 if (!hook_path)
1240 return 0;
1242 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1243 proc.in = -1;
1244 proc.stdout_to_stderr = 1;
1245 proc.trace2_hook_name = "post-rewrite";
1247 code = start_command(&proc);
1248 if (code)
1249 return code;
1250 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1251 sigchain_push(SIGPIPE, SIG_IGN);
1252 write_in_full(proc.in, sb.buf, sb.len);
1253 close(proc.in);
1254 strbuf_release(&sb);
1255 sigchain_pop(SIGPIPE);
1256 return finish_command(&proc);
1259 void commit_post_rewrite(struct repository *r,
1260 const struct commit *old_head,
1261 const struct object_id *new_head)
1263 struct notes_rewrite_cfg *cfg;
1265 cfg = init_copy_notes_for_rewrite("amend");
1266 if (cfg) {
1267 /* we are amending, so old_head is not NULL */
1268 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1269 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1271 run_rewrite_hook(&old_head->object.oid, new_head);
1274 static int run_prepare_commit_msg_hook(struct repository *r,
1275 struct strbuf *msg,
1276 const char *commit)
1278 int ret = 0;
1279 const char *name, *arg1 = NULL, *arg2 = NULL;
1281 name = git_path_commit_editmsg();
1282 if (write_message(msg->buf, msg->len, name, 0))
1283 return -1;
1285 if (commit) {
1286 arg1 = "commit";
1287 arg2 = commit;
1288 } else {
1289 arg1 = "message";
1291 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1292 arg1, arg2, NULL))
1293 ret = error(_("'prepare-commit-msg' hook failed"));
1295 return ret;
1298 static const char implicit_ident_advice_noconfig[] =
1299 N_("Your name and email address were configured automatically based\n"
1300 "on your username and hostname. Please check that they are accurate.\n"
1301 "You can suppress this message by setting them explicitly. Run the\n"
1302 "following command and follow the instructions in your editor to edit\n"
1303 "your configuration file:\n"
1304 "\n"
1305 " git config --global --edit\n"
1306 "\n"
1307 "After doing this, you may fix the identity used for this commit with:\n"
1308 "\n"
1309 " git commit --amend --reset-author\n");
1311 static const char implicit_ident_advice_config[] =
1312 N_("Your name and email address were configured automatically based\n"
1313 "on your username and hostname. Please check that they are accurate.\n"
1314 "You can suppress this message by setting them explicitly:\n"
1315 "\n"
1316 " git config --global user.name \"Your Name\"\n"
1317 " git config --global user.email you@example.com\n"
1318 "\n"
1319 "After doing this, you may fix the identity used for this commit with:\n"
1320 "\n"
1321 " git commit --amend --reset-author\n");
1323 static const char *implicit_ident_advice(void)
1325 char *user_config = interpolate_path("~/.gitconfig", 0);
1326 char *xdg_config = xdg_config_home("config");
1327 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1329 free(user_config);
1330 free(xdg_config);
1332 if (config_exists)
1333 return _(implicit_ident_advice_config);
1334 else
1335 return _(implicit_ident_advice_noconfig);
1339 void print_commit_summary(struct repository *r,
1340 const char *prefix,
1341 const struct object_id *oid,
1342 unsigned int flags)
1344 struct rev_info rev;
1345 struct commit *commit;
1346 struct strbuf format = STRBUF_INIT;
1347 const char *head;
1348 struct pretty_print_context pctx = {0};
1349 struct strbuf author_ident = STRBUF_INIT;
1350 struct strbuf committer_ident = STRBUF_INIT;
1351 struct ref_store *refs;
1353 commit = lookup_commit(r, oid);
1354 if (!commit)
1355 die(_("couldn't look up newly created commit"));
1356 if (repo_parse_commit(r, commit))
1357 die(_("could not parse newly created commit"));
1359 strbuf_addstr(&format, "format:%h] %s");
1361 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1362 &pctx);
1363 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1364 &pctx);
1365 if (strbuf_cmp(&author_ident, &committer_ident)) {
1366 strbuf_addstr(&format, "\n Author: ");
1367 strbuf_addbuf_percentquote(&format, &author_ident);
1369 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1370 struct strbuf date = STRBUF_INIT;
1372 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1373 strbuf_addstr(&format, "\n Date: ");
1374 strbuf_addbuf_percentquote(&format, &date);
1375 strbuf_release(&date);
1377 if (!committer_ident_sufficiently_given()) {
1378 strbuf_addstr(&format, "\n Committer: ");
1379 strbuf_addbuf_percentquote(&format, &committer_ident);
1380 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1381 strbuf_addch(&format, '\n');
1382 strbuf_addstr(&format, implicit_ident_advice());
1385 strbuf_release(&author_ident);
1386 strbuf_release(&committer_ident);
1388 repo_init_revisions(r, &rev, prefix);
1389 setup_revisions(0, NULL, &rev, NULL);
1391 rev.diff = 1;
1392 rev.diffopt.output_format =
1393 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1395 rev.verbose_header = 1;
1396 rev.show_root_diff = 1;
1397 get_commit_format(format.buf, &rev);
1398 rev.always_show_header = 0;
1399 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1400 diff_setup_done(&rev.diffopt);
1402 refs = get_main_ref_store(r);
1403 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1404 if (!head)
1405 die(_("unable to resolve HEAD after creating commit"));
1406 if (!strcmp(head, "HEAD"))
1407 head = _("detached HEAD");
1408 else
1409 skip_prefix(head, "refs/heads/", &head);
1410 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1411 _(" (root-commit)") : "");
1413 if (!log_tree_commit(&rev, commit)) {
1414 rev.always_show_header = 1;
1415 rev.use_terminator = 1;
1416 log_tree_commit(&rev, commit);
1419 release_revisions(&rev);
1420 strbuf_release(&format);
1423 static int parse_head(struct repository *r, struct commit **head)
1425 struct commit *current_head;
1426 struct object_id oid;
1428 if (repo_get_oid(r, "HEAD", &oid)) {
1429 current_head = NULL;
1430 } else {
1431 current_head = lookup_commit_reference(r, &oid);
1432 if (!current_head)
1433 return error(_("could not parse HEAD"));
1434 if (!oideq(&oid, &current_head->object.oid)) {
1435 warning(_("HEAD %s is not a commit!"),
1436 oid_to_hex(&oid));
1438 if (repo_parse_commit(r, current_head))
1439 return error(_("could not parse HEAD commit"));
1441 *head = current_head;
1443 return 0;
1447 * Try to commit without forking 'git commit'. In some cases we need
1448 * to run 'git commit' to display an error message
1450 * Returns:
1451 * -1 - error unable to commit
1452 * 0 - success
1453 * 1 - run 'git commit'
1455 static int try_to_commit(struct repository *r,
1456 struct strbuf *msg, const char *author,
1457 struct replay_opts *opts, unsigned int flags,
1458 struct object_id *oid)
1460 struct object_id tree;
1461 struct commit *current_head = NULL;
1462 struct commit_list *parents = NULL;
1463 struct commit_extra_header *extra = NULL;
1464 struct strbuf err = STRBUF_INIT;
1465 struct strbuf commit_msg = STRBUF_INIT;
1466 char *amend_author = NULL;
1467 const char *committer = NULL;
1468 const char *hook_commit = NULL;
1469 enum commit_msg_cleanup_mode cleanup;
1470 int res = 0;
1472 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1473 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1475 if (parse_head(r, &current_head))
1476 return -1;
1478 if (flags & AMEND_MSG) {
1479 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1480 const char *out_enc = get_commit_output_encoding();
1481 const char *message = repo_logmsg_reencode(r, current_head,
1482 NULL, out_enc);
1484 if (!msg) {
1485 const char *orig_message = NULL;
1487 find_commit_subject(message, &orig_message);
1488 msg = &commit_msg;
1489 strbuf_addstr(msg, orig_message);
1490 hook_commit = "HEAD";
1492 author = amend_author = get_author(message);
1493 repo_unuse_commit_buffer(r, current_head,
1494 message);
1495 if (!author) {
1496 res = error(_("unable to parse commit author"));
1497 goto out;
1499 parents = copy_commit_list(current_head->parents);
1500 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1501 } else if (current_head &&
1502 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1503 commit_list_insert(current_head, &parents);
1506 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1507 res = error(_("git write-tree failed to write a tree"));
1508 goto out;
1511 if (!(flags & ALLOW_EMPTY)) {
1512 struct commit *first_parent = current_head;
1514 if (flags & AMEND_MSG) {
1515 if (current_head->parents) {
1516 first_parent = current_head->parents->item;
1517 if (repo_parse_commit(r, first_parent)) {
1518 res = error(_("could not parse HEAD commit"));
1519 goto out;
1521 } else {
1522 first_parent = NULL;
1525 if (oideq(first_parent
1526 ? get_commit_tree_oid(first_parent)
1527 : the_hash_algo->empty_tree,
1528 &tree)) {
1529 res = 1; /* run 'git commit' to display error message */
1530 goto out;
1534 if (hook_exists("prepare-commit-msg")) {
1535 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1536 if (res)
1537 goto out;
1538 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1539 2048) < 0) {
1540 res = error_errno(_("unable to read commit message "
1541 "from '%s'"),
1542 git_path_commit_editmsg());
1543 goto out;
1545 msg = &commit_msg;
1548 if (flags & CLEANUP_MSG)
1549 cleanup = COMMIT_MSG_CLEANUP_ALL;
1550 else if (flags & VERBATIM_MSG)
1551 cleanup = COMMIT_MSG_CLEANUP_NONE;
1552 else if ((opts->signoff || opts->record_origin) &&
1553 !opts->explicit_cleanup)
1554 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1555 else
1556 cleanup = opts->default_msg_cleanup;
1558 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1559 strbuf_stripspace(msg,
1560 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1561 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1562 res = 1; /* run 'git commit' to display error message */
1563 goto out;
1566 if (opts->committer_date_is_author_date) {
1567 struct ident_split id;
1568 struct strbuf date = STRBUF_INIT;
1570 if (!opts->ignore_date) {
1571 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1572 res = error(_("invalid author identity '%s'"),
1573 author);
1574 goto out;
1576 if (!id.date_begin) {
1577 res = error(_(
1578 "corrupt author: missing date information"));
1579 goto out;
1581 strbuf_addf(&date, "@%.*s %.*s",
1582 (int)(id.date_end - id.date_begin),
1583 id.date_begin,
1584 (int)(id.tz_end - id.tz_begin),
1585 id.tz_begin);
1586 } else {
1587 reset_ident_date();
1589 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1590 getenv("GIT_COMMITTER_EMAIL"),
1591 WANT_COMMITTER_IDENT,
1592 opts->ignore_date ? NULL : date.buf,
1593 IDENT_STRICT);
1594 strbuf_release(&date);
1595 } else {
1596 reset_ident_date();
1599 if (opts->ignore_date) {
1600 struct ident_split id;
1601 char *name, *email;
1603 if (split_ident_line(&id, author, strlen(author)) < 0) {
1604 error(_("invalid author identity '%s'"), author);
1605 goto out;
1607 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1608 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1609 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1610 IDENT_STRICT);
1611 free(name);
1612 free(email);
1615 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1616 author, committer, opts->gpg_sign, extra)) {
1617 res = error(_("failed to write commit object"));
1618 goto out;
1621 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1622 msg, &err)) {
1623 res = error("%s", err.buf);
1624 goto out;
1627 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1628 if (flags & AMEND_MSG)
1629 commit_post_rewrite(r, current_head, oid);
1631 out:
1632 free_commit_extra_headers(extra);
1633 strbuf_release(&err);
1634 strbuf_release(&commit_msg);
1635 free(amend_author);
1637 return res;
1640 static int write_rebase_head(struct object_id *oid)
1642 if (update_ref("rebase", "REBASE_HEAD", oid,
1643 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1644 return error(_("could not update %s"), "REBASE_HEAD");
1646 return 0;
1649 static int do_commit(struct repository *r,
1650 const char *msg_file, const char *author,
1651 struct replay_opts *opts, unsigned int flags,
1652 struct object_id *oid)
1654 int res = 1;
1656 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1657 struct object_id oid;
1658 struct strbuf sb = STRBUF_INIT;
1660 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1661 return error_errno(_("unable to read commit message "
1662 "from '%s'"),
1663 msg_file);
1665 res = try_to_commit(r, msg_file ? &sb : NULL,
1666 author, opts, flags, &oid);
1667 strbuf_release(&sb);
1668 if (!res) {
1669 refs_delete_ref(get_main_ref_store(r), "",
1670 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1671 unlink(git_path_merge_msg(r));
1672 if (!is_rebase_i(opts))
1673 print_commit_summary(r, NULL, &oid,
1674 SUMMARY_SHOW_AUTHOR_DATE);
1675 return res;
1678 if (res == 1) {
1679 if (is_rebase_i(opts) && oid)
1680 if (write_rebase_head(oid))
1681 return -1;
1682 return run_git_commit(msg_file, opts, flags);
1685 return res;
1688 static int is_original_commit_empty(struct commit *commit)
1690 const struct object_id *ptree_oid;
1692 if (repo_parse_commit(the_repository, commit))
1693 return error(_("could not parse commit %s"),
1694 oid_to_hex(&commit->object.oid));
1695 if (commit->parents) {
1696 struct commit *parent = commit->parents->item;
1697 if (repo_parse_commit(the_repository, parent))
1698 return error(_("could not parse parent commit %s"),
1699 oid_to_hex(&parent->object.oid));
1700 ptree_oid = get_commit_tree_oid(parent);
1701 } else {
1702 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1705 return oideq(ptree_oid, get_commit_tree_oid(commit));
1709 * Should empty commits be allowed? Return status:
1710 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1711 * 0: Halt on empty commit
1712 * 1: Allow empty commit
1713 * 2: Drop empty commit
1715 static int allow_empty(struct repository *r,
1716 struct replay_opts *opts,
1717 struct commit *commit)
1719 int index_unchanged, originally_empty;
1722 * Four cases:
1724 * (1) we do not allow empty at all and error out.
1726 * (2) we allow ones that were initially empty, and
1727 * just drop the ones that become empty
1729 * (3) we allow ones that were initially empty, but
1730 * halt for the ones that become empty;
1732 * (4) we allow both.
1734 if (!opts->allow_empty)
1735 return 0; /* let "git commit" barf as necessary */
1737 index_unchanged = is_index_unchanged(r);
1738 if (index_unchanged < 0)
1739 return index_unchanged;
1740 if (!index_unchanged)
1741 return 0; /* we do not have to say --allow-empty */
1743 if (opts->keep_redundant_commits)
1744 return 1;
1746 originally_empty = is_original_commit_empty(commit);
1747 if (originally_empty < 0)
1748 return originally_empty;
1749 if (originally_empty)
1750 return 1;
1751 else if (opts->drop_redundant_commits)
1752 return 2;
1753 else
1754 return 0;
1757 static struct {
1758 char c;
1759 const char *str;
1760 } todo_command_info[] = {
1761 [TODO_PICK] = { 'p', "pick" },
1762 [TODO_REVERT] = { 0, "revert" },
1763 [TODO_EDIT] = { 'e', "edit" },
1764 [TODO_REWORD] = { 'r', "reword" },
1765 [TODO_FIXUP] = { 'f', "fixup" },
1766 [TODO_SQUASH] = { 's', "squash" },
1767 [TODO_EXEC] = { 'x', "exec" },
1768 [TODO_BREAK] = { 'b', "break" },
1769 [TODO_LABEL] = { 'l', "label" },
1770 [TODO_RESET] = { 't', "reset" },
1771 [TODO_MERGE] = { 'm', "merge" },
1772 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1773 [TODO_NOOP] = { 0, "noop" },
1774 [TODO_DROP] = { 'd', "drop" },
1775 [TODO_COMMENT] = { 0, NULL },
1778 static const char *command_to_string(const enum todo_command command)
1780 if (command < TODO_COMMENT)
1781 return todo_command_info[command].str;
1782 die(_("unknown command: %d"), command);
1785 static char command_to_char(const enum todo_command command)
1787 if (command < TODO_COMMENT)
1788 return todo_command_info[command].c;
1789 return comment_line_char;
1792 static int is_noop(const enum todo_command command)
1794 return TODO_NOOP <= command;
1797 static int is_fixup(enum todo_command command)
1799 return command == TODO_FIXUP || command == TODO_SQUASH;
1802 /* Does this command create a (non-merge) commit? */
1803 static int is_pick_or_similar(enum todo_command command)
1805 switch (command) {
1806 case TODO_PICK:
1807 case TODO_REVERT:
1808 case TODO_EDIT:
1809 case TODO_REWORD:
1810 case TODO_FIXUP:
1811 case TODO_SQUASH:
1812 return 1;
1813 default:
1814 return 0;
1818 enum todo_item_flags {
1819 TODO_EDIT_MERGE_MSG = (1 << 0),
1820 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1821 TODO_EDIT_FIXUP_MSG = (1 << 2),
1824 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1825 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1826 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1827 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1828 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1830 static int is_fixup_flag(enum todo_command command, unsigned flag)
1832 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1833 (flag & TODO_EDIT_FIXUP_MSG));
1837 * Wrapper around strbuf_add_commented_lines() which avoids double
1838 * commenting commit subjects.
1840 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1842 const char *s = str;
1843 while (len > 0 && s[0] == comment_line_char) {
1844 size_t count;
1845 const char *n = memchr(s, '\n', len);
1846 if (!n)
1847 count = len;
1848 else
1849 count = n - s + 1;
1850 strbuf_add(buf, s, count);
1851 s += count;
1852 len -= count;
1854 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1857 /* Does the current fixup chain contain a squash command? */
1858 static int seen_squash(struct replay_opts *opts)
1860 return starts_with(opts->current_fixups.buf, "squash") ||
1861 strstr(opts->current_fixups.buf, "\nsquash");
1864 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1866 strbuf_setlen(buf1, 2);
1867 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1868 strbuf_addch(buf1, '\n');
1869 strbuf_setlen(buf2, 2);
1870 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1871 strbuf_addch(buf2, '\n');
1875 * Comment out any un-commented commit messages, updating the message comments
1876 * to say they will be skipped but do not comment out the empty lines that
1877 * surround commit messages and their comments.
1879 static void update_squash_message_for_fixup(struct strbuf *msg)
1881 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1882 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1883 const char *s, *start;
1884 char *orig_msg;
1885 size_t orig_msg_len;
1886 int i = 1;
1888 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1889 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1890 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1891 while (s) {
1892 const char *next;
1893 size_t off;
1894 if (skip_prefix(s, buf1.buf, &next)) {
1896 * Copy the last message, preserving the blank line
1897 * preceding the current line
1899 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1900 copy_lines(msg, start, s - start - off);
1901 if (off)
1902 strbuf_addch(msg, '\n');
1904 * The next message needs to be commented out but the
1905 * message header is already commented out so just copy
1906 * it and the blank line that follows it.
1908 strbuf_addbuf(msg, &buf2);
1909 if (*next == '\n')
1910 strbuf_addch(msg, *next++);
1911 start = s = next;
1912 copy_lines = add_commented_lines;
1913 update_comment_bufs(&buf1, &buf2, ++i);
1914 } else if (skip_prefix(s, buf2.buf, &next)) {
1915 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1916 copy_lines(msg, start, s - start - off);
1917 start = s - off;
1918 s = next;
1919 copy_lines = strbuf_add;
1920 update_comment_bufs(&buf1, &buf2, ++i);
1921 } else {
1922 s = strchr(s, '\n');
1923 if (s)
1924 s++;
1927 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1928 free(orig_msg);
1929 strbuf_release(&buf1);
1930 strbuf_release(&buf2);
1933 static int append_squash_message(struct strbuf *buf, const char *body,
1934 enum todo_command command, struct replay_opts *opts,
1935 unsigned flag)
1937 const char *fixup_msg;
1938 size_t commented_len = 0, fixup_off;
1940 * amend is non-interactive and not normally used with fixup!
1941 * or squash! commits, so only comment out those subjects when
1942 * squashing commit messages.
1944 if (starts_with(body, "amend!") ||
1945 ((command == TODO_SQUASH || seen_squash(opts)) &&
1946 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1947 commented_len = commit_subject_length(body);
1949 strbuf_addf(buf, "\n%c ", comment_line_char);
1950 strbuf_addf(buf, _(nth_commit_msg_fmt),
1951 ++opts->current_fixup_count + 1);
1952 strbuf_addstr(buf, "\n\n");
1953 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1954 /* buf->buf may be reallocated so store an offset into the buffer */
1955 fixup_off = buf->len;
1956 strbuf_addstr(buf, body + commented_len);
1958 /* fixup -C after squash behaves like squash */
1959 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1961 * We're replacing the commit message so we need to
1962 * append the Signed-off-by: trailer if the user
1963 * requested '--signoff'.
1965 if (opts->signoff)
1966 append_signoff(buf, 0, 0);
1968 if ((command == TODO_FIXUP) &&
1969 (flag & TODO_REPLACE_FIXUP_MSG) &&
1970 (file_exists(rebase_path_fixup_msg()) ||
1971 !file_exists(rebase_path_squash_msg()))) {
1972 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1973 if (write_message(fixup_msg, strlen(fixup_msg),
1974 rebase_path_fixup_msg(), 0) < 0)
1975 return error(_("cannot write '%s'"),
1976 rebase_path_fixup_msg());
1977 } else {
1978 unlink(rebase_path_fixup_msg());
1980 } else {
1981 unlink(rebase_path_fixup_msg());
1984 return 0;
1987 static int update_squash_messages(struct repository *r,
1988 enum todo_command command,
1989 struct commit *commit,
1990 struct replay_opts *opts,
1991 unsigned flag)
1993 struct strbuf buf = STRBUF_INIT;
1994 int res = 0;
1995 const char *message, *body;
1996 const char *encoding = get_commit_output_encoding();
1998 if (opts->current_fixup_count > 0) {
1999 struct strbuf header = STRBUF_INIT;
2000 char *eol;
2002 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2003 return error(_("could not read '%s'"),
2004 rebase_path_squash_msg());
2006 eol = buf.buf[0] != comment_line_char ?
2007 buf.buf : strchrnul(buf.buf, '\n');
2009 strbuf_addf(&header, "%c ", comment_line_char);
2010 strbuf_addf(&header, _(combined_commit_msg_fmt),
2011 opts->current_fixup_count + 2);
2012 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2013 strbuf_release(&header);
2014 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2015 update_squash_message_for_fixup(&buf);
2016 } else {
2017 struct object_id head;
2018 struct commit *head_commit;
2019 const char *head_message, *body;
2021 if (repo_get_oid(r, "HEAD", &head))
2022 return error(_("need a HEAD to fixup"));
2023 if (!(head_commit = lookup_commit_reference(r, &head)))
2024 return error(_("could not read HEAD"));
2025 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2026 encoding)))
2027 return error(_("could not read HEAD's commit message"));
2029 find_commit_subject(head_message, &body);
2030 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2031 rebase_path_fixup_msg(), 0) < 0) {
2032 repo_unuse_commit_buffer(r, head_commit, head_message);
2033 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2035 strbuf_addf(&buf, "%c ", comment_line_char);
2036 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2037 strbuf_addf(&buf, "\n%c ", comment_line_char);
2038 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2039 _(skip_first_commit_msg_str) :
2040 _(first_commit_msg_str));
2041 strbuf_addstr(&buf, "\n\n");
2042 if (is_fixup_flag(command, flag))
2043 strbuf_add_commented_lines(&buf, body, strlen(body),
2044 comment_line_char);
2045 else
2046 strbuf_addstr(&buf, body);
2048 repo_unuse_commit_buffer(r, head_commit, head_message);
2051 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2052 return error(_("could not read commit message of %s"),
2053 oid_to_hex(&commit->object.oid));
2054 find_commit_subject(message, &body);
2056 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2057 res = append_squash_message(&buf, body, command, opts, flag);
2058 } else if (command == TODO_FIXUP) {
2059 strbuf_addf(&buf, "\n%c ", comment_line_char);
2060 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2061 ++opts->current_fixup_count + 1);
2062 strbuf_addstr(&buf, "\n\n");
2063 strbuf_add_commented_lines(&buf, body, strlen(body),
2064 comment_line_char);
2065 } else
2066 return error(_("unknown command: %d"), command);
2067 repo_unuse_commit_buffer(r, commit, message);
2069 if (!res)
2070 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2072 strbuf_release(&buf);
2074 if (!res) {
2075 strbuf_addf(&opts->current_fixups, "%s%s %s",
2076 opts->current_fixups.len ? "\n" : "",
2077 command_to_string(command),
2078 oid_to_hex(&commit->object.oid));
2079 res = write_message(opts->current_fixups.buf,
2080 opts->current_fixups.len,
2081 rebase_path_current_fixups(), 0);
2084 return res;
2087 static void flush_rewritten_pending(void)
2089 struct strbuf buf = STRBUF_INIT;
2090 struct object_id newoid;
2091 FILE *out;
2093 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2094 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2095 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2096 char *bol = buf.buf, *eol;
2098 while (*bol) {
2099 eol = strchrnul(bol, '\n');
2100 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2101 bol, oid_to_hex(&newoid));
2102 if (!*eol)
2103 break;
2104 bol = eol + 1;
2106 fclose(out);
2107 unlink(rebase_path_rewritten_pending());
2109 strbuf_release(&buf);
2112 static void record_in_rewritten(struct object_id *oid,
2113 enum todo_command next_command)
2115 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2117 if (!out)
2118 return;
2120 fprintf(out, "%s\n", oid_to_hex(oid));
2121 fclose(out);
2123 if (!is_fixup(next_command))
2124 flush_rewritten_pending();
2127 static int should_edit(struct replay_opts *opts) {
2128 if (opts->edit < 0)
2130 * Note that we only handle the case of non-conflicted
2131 * commits; continue_single_pick() handles the conflicted
2132 * commits itself instead of calling this function.
2134 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2135 return opts->edit;
2138 static void refer_to_commit(struct replay_opts *opts,
2139 struct strbuf *msgbuf, struct commit *commit)
2141 if (opts->commit_use_reference) {
2142 struct pretty_print_context ctx = {
2143 .abbrev = DEFAULT_ABBREV,
2144 .date_mode.type = DATE_SHORT,
2146 repo_format_commit_message(the_repository, commit,
2147 "%h (%s, %ad)", msgbuf, &ctx);
2148 } else {
2149 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2153 static int do_pick_commit(struct repository *r,
2154 struct todo_item *item,
2155 struct replay_opts *opts,
2156 int final_fixup, int *check_todo)
2158 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2159 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2160 struct object_id head;
2161 struct commit *base, *next, *parent;
2162 const char *base_label, *next_label;
2163 char *author = NULL;
2164 struct commit_message msg = { NULL, NULL, NULL, NULL };
2165 struct strbuf msgbuf = STRBUF_INIT;
2166 int res, unborn = 0, reword = 0, allow, drop_commit;
2167 enum todo_command command = item->command;
2168 struct commit *commit = item->commit;
2170 if (opts->no_commit) {
2172 * We do not intend to commit immediately. We just want to
2173 * merge the differences in, so let's compute the tree
2174 * that represents the "current" state for the merge machinery
2175 * to work on.
2177 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2178 return error(_("your index file is unmerged."));
2179 } else {
2180 unborn = repo_get_oid(r, "HEAD", &head);
2181 /* Do we want to generate a root commit? */
2182 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2183 oideq(&head, &opts->squash_onto)) {
2184 if (is_fixup(command))
2185 return error(_("cannot fixup root commit"));
2186 flags |= CREATE_ROOT_COMMIT;
2187 unborn = 1;
2188 } else if (unborn)
2189 oidcpy(&head, the_hash_algo->empty_tree);
2190 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2191 NULL, 0))
2192 return error_dirty_index(r, opts);
2194 discard_index(r->index);
2196 if (!commit->parents)
2197 parent = NULL;
2198 else if (commit->parents->next) {
2199 /* Reverting or cherry-picking a merge commit */
2200 int cnt;
2201 struct commit_list *p;
2203 if (!opts->mainline)
2204 return error(_("commit %s is a merge but no -m option was given."),
2205 oid_to_hex(&commit->object.oid));
2207 for (cnt = 1, p = commit->parents;
2208 cnt != opts->mainline && p;
2209 cnt++)
2210 p = p->next;
2211 if (cnt != opts->mainline || !p)
2212 return error(_("commit %s does not have parent %d"),
2213 oid_to_hex(&commit->object.oid), opts->mainline);
2214 parent = p->item;
2215 } else if (1 < opts->mainline)
2217 * Non-first parent explicitly specified as mainline for
2218 * non-merge commit
2220 return error(_("commit %s does not have parent %d"),
2221 oid_to_hex(&commit->object.oid), opts->mainline);
2222 else
2223 parent = commit->parents->item;
2225 if (get_message(commit, &msg) != 0)
2226 return error(_("cannot get commit message for %s"),
2227 oid_to_hex(&commit->object.oid));
2229 if (opts->allow_ff && !is_fixup(command) &&
2230 ((parent && oideq(&parent->object.oid, &head)) ||
2231 (!parent && unborn))) {
2232 if (is_rebase_i(opts))
2233 write_author_script(msg.message);
2234 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2235 opts);
2236 if (res || command != TODO_REWORD)
2237 goto leave;
2238 reword = 1;
2239 msg_file = NULL;
2240 goto fast_forward_edit;
2242 if (parent && repo_parse_commit(r, parent) < 0)
2243 /* TRANSLATORS: The first %s will be a "todo" command like
2244 "revert" or "pick", the second %s a SHA1. */
2245 return error(_("%s: cannot parse parent commit %s"),
2246 command_to_string(command),
2247 oid_to_hex(&parent->object.oid));
2250 * "commit" is an existing commit. We would want to apply
2251 * the difference it introduces since its first parent "prev"
2252 * on top of the current HEAD if we are cherry-pick. Or the
2253 * reverse of it if we are revert.
2256 if (command == TODO_REVERT) {
2257 const char *orig_subject;
2259 base = commit;
2260 base_label = msg.label;
2261 next = parent;
2262 next_label = msg.parent_label;
2263 if (opts->commit_use_reference) {
2264 strbuf_addstr(&msgbuf,
2265 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2266 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2268 * We don't touch pre-existing repeated reverts, because
2269 * theoretically these can be nested arbitrarily deeply,
2270 * thus requiring excessive complexity to deal with.
2272 !starts_with(orig_subject, "Revert \"")) {
2273 strbuf_addstr(&msgbuf, "Reapply \"");
2274 strbuf_addstr(&msgbuf, orig_subject);
2275 } else {
2276 strbuf_addstr(&msgbuf, "Revert \"");
2277 strbuf_addstr(&msgbuf, msg.subject);
2278 strbuf_addstr(&msgbuf, "\"");
2280 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2281 refer_to_commit(opts, &msgbuf, commit);
2283 if (commit->parents && commit->parents->next) {
2284 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2285 refer_to_commit(opts, &msgbuf, parent);
2287 strbuf_addstr(&msgbuf, ".\n");
2288 } else {
2289 const char *p;
2291 base = parent;
2292 base_label = msg.parent_label;
2293 next = commit;
2294 next_label = msg.label;
2296 /* Append the commit log message to msgbuf. */
2297 if (find_commit_subject(msg.message, &p))
2298 strbuf_addstr(&msgbuf, p);
2300 if (opts->record_origin) {
2301 strbuf_complete_line(&msgbuf);
2302 if (!has_conforming_footer(&msgbuf, NULL, 0))
2303 strbuf_addch(&msgbuf, '\n');
2304 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2305 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2306 strbuf_addstr(&msgbuf, ")\n");
2308 if (!is_fixup(command))
2309 author = get_author(msg.message);
2312 if (command == TODO_REWORD)
2313 reword = 1;
2314 else if (is_fixup(command)) {
2315 if (update_squash_messages(r, command, commit,
2316 opts, item->flags)) {
2317 res = -1;
2318 goto leave;
2320 flags |= AMEND_MSG;
2321 if (!final_fixup)
2322 msg_file = rebase_path_squash_msg();
2323 else if (file_exists(rebase_path_fixup_msg())) {
2324 flags |= VERBATIM_MSG;
2325 msg_file = rebase_path_fixup_msg();
2326 } else {
2327 const char *dest = git_path_squash_msg(r);
2328 unlink(dest);
2329 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2330 res = error(_("could not copy '%s' to '%s'"),
2331 rebase_path_squash_msg(), dest);
2332 goto leave;
2334 unlink(git_path_merge_msg(r));
2335 msg_file = dest;
2336 flags |= EDIT_MSG;
2340 if (opts->signoff && !is_fixup(command))
2341 append_signoff(&msgbuf, 0, 0);
2343 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2344 res = -1;
2345 else if (!opts->strategy ||
2346 !strcmp(opts->strategy, "recursive") ||
2347 !strcmp(opts->strategy, "ort") ||
2348 command == TODO_REVERT) {
2349 res = do_recursive_merge(r, base, next, base_label, next_label,
2350 &head, &msgbuf, opts);
2351 if (res < 0)
2352 goto leave;
2354 res |= write_message(msgbuf.buf, msgbuf.len,
2355 git_path_merge_msg(r), 0);
2356 } else {
2357 struct commit_list *common = NULL;
2358 struct commit_list *remotes = NULL;
2360 res = write_message(msgbuf.buf, msgbuf.len,
2361 git_path_merge_msg(r), 0);
2363 commit_list_insert(base, &common);
2364 commit_list_insert(next, &remotes);
2365 res |= try_merge_command(r, opts->strategy,
2366 opts->xopts.nr, opts->xopts.v,
2367 common, oid_to_hex(&head), remotes);
2368 free_commit_list(common);
2369 free_commit_list(remotes);
2373 * If the merge was clean or if it failed due to conflict, we write
2374 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2375 * However, if the merge did not even start, then we don't want to
2376 * write it at all.
2378 if ((command == TODO_PICK || command == TODO_REWORD ||
2379 command == TODO_EDIT) && !opts->no_commit &&
2380 (res == 0 || res == 1) &&
2381 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2382 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2383 res = -1;
2384 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2385 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2386 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2387 res = -1;
2389 if (res) {
2390 error(command == TODO_REVERT
2391 ? _("could not revert %s... %s")
2392 : _("could not apply %s... %s"),
2393 short_commit_name(r, commit), msg.subject);
2394 print_advice(r, res == 1, opts);
2395 repo_rerere(r, opts->allow_rerere_auto);
2396 goto leave;
2399 drop_commit = 0;
2400 allow = allow_empty(r, opts, commit);
2401 if (allow < 0) {
2402 res = allow;
2403 goto leave;
2404 } else if (allow == 1) {
2405 flags |= ALLOW_EMPTY;
2406 } else if (allow == 2) {
2407 drop_commit = 1;
2408 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2409 NULL, REF_NO_DEREF);
2410 unlink(git_path_merge_msg(r));
2411 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2412 NULL, REF_NO_DEREF);
2413 fprintf(stderr,
2414 _("dropping %s %s -- patch contents already upstream\n"),
2415 oid_to_hex(&commit->object.oid), msg.subject);
2416 } /* else allow == 0 and there's nothing special to do */
2417 if (!opts->no_commit && !drop_commit) {
2418 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2419 res = do_commit(r, msg_file, author, opts, flags,
2420 commit? &commit->object.oid : NULL);
2421 else
2422 res = error(_("unable to parse commit author"));
2423 *check_todo = !!(flags & EDIT_MSG);
2424 if (!res && reword) {
2425 fast_forward_edit:
2426 res = run_git_commit(NULL, opts, EDIT_MSG |
2427 VERIFY_MSG | AMEND_MSG |
2428 (flags & ALLOW_EMPTY));
2429 *check_todo = 1;
2434 if (!res && final_fixup) {
2435 unlink(rebase_path_fixup_msg());
2436 unlink(rebase_path_squash_msg());
2437 unlink(rebase_path_current_fixups());
2438 strbuf_reset(&opts->current_fixups);
2439 opts->current_fixup_count = 0;
2442 leave:
2443 free_message(commit, &msg);
2444 free(author);
2445 strbuf_release(&msgbuf);
2446 update_abort_safety_file();
2448 return res;
2451 static int prepare_revs(struct replay_opts *opts)
2454 * picking (but not reverting) ranges (but not individual revisions)
2455 * should be done in reverse
2457 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2458 opts->revs->reverse ^= 1;
2460 if (prepare_revision_walk(opts->revs))
2461 return error(_("revision walk setup failed"));
2463 return 0;
2466 static int read_and_refresh_cache(struct repository *r,
2467 struct replay_opts *opts)
2469 struct lock_file index_lock = LOCK_INIT;
2470 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2471 if (repo_read_index(r) < 0) {
2472 rollback_lock_file(&index_lock);
2473 return error(_("git %s: failed to read the index"),
2474 action_name(opts));
2476 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2478 if (index_fd >= 0) {
2479 if (write_locked_index(r->index, &index_lock,
2480 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2481 return error(_("git %s: failed to refresh the index"),
2482 action_name(opts));
2487 * If we are resolving merges in any way other than "ort", then
2488 * expand the sparse index.
2490 if (opts->strategy && strcmp(opts->strategy, "ort"))
2491 ensure_full_index(r->index);
2492 return 0;
2495 void todo_list_release(struct todo_list *todo_list)
2497 strbuf_release(&todo_list->buf);
2498 FREE_AND_NULL(todo_list->items);
2499 todo_list->nr = todo_list->alloc = 0;
2502 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2504 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2505 return todo_list->items + todo_list->nr++;
2508 const char *todo_item_get_arg(struct todo_list *todo_list,
2509 struct todo_item *item)
2511 return todo_list->buf.buf + item->arg_offset;
2514 static int is_command(enum todo_command command, const char **bol)
2516 const char *str = todo_command_info[command].str;
2517 const char nick = todo_command_info[command].c;
2518 const char *p = *bol;
2520 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2521 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2522 (*bol = p);
2525 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2527 switch (command) {
2528 case TODO_LABEL:
2530 * '#' is not a valid label as the merge command uses it to
2531 * separate merge parents from the commit subject.
2533 if (!strcmp(arg, "#") ||
2534 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2535 return error(_("'%s' is not a valid label"), arg);
2536 break;
2538 case TODO_UPDATE_REF:
2539 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2540 return error(_("'%s' is not a valid refname"), arg);
2541 if (check_refname_format(arg, 0))
2542 return error(_("update-ref requires a fully qualified "
2543 "refname e.g. refs/heads/%s"), arg);
2544 break;
2546 default:
2547 BUG("unexpected todo_command");
2550 return 0;
2553 static int parse_insn_line(struct repository *r, struct todo_item *item,
2554 const char *buf, const char *bol, char *eol)
2556 struct object_id commit_oid;
2557 char *end_of_object_name;
2558 int i, saved, status, padding;
2560 item->flags = 0;
2562 /* left-trim */
2563 bol += strspn(bol, " \t");
2565 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2566 item->command = TODO_COMMENT;
2567 item->commit = NULL;
2568 item->arg_offset = bol - buf;
2569 item->arg_len = eol - bol;
2570 return 0;
2573 for (i = 0; i < TODO_COMMENT; i++)
2574 if (is_command(i, &bol)) {
2575 item->command = i;
2576 break;
2578 if (i >= TODO_COMMENT)
2579 return error(_("invalid command '%.*s'"),
2580 (int)strcspn(bol, " \t\r\n"), bol);
2582 /* Eat up extra spaces/ tabs before object name */
2583 padding = strspn(bol, " \t");
2584 bol += padding;
2586 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2587 if (bol != eol)
2588 return error(_("%s does not accept arguments: '%s'"),
2589 command_to_string(item->command), bol);
2590 item->commit = NULL;
2591 item->arg_offset = bol - buf;
2592 item->arg_len = eol - bol;
2593 return 0;
2596 if (!padding)
2597 return error(_("missing arguments for %s"),
2598 command_to_string(item->command));
2600 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2601 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2602 int ret = 0;
2604 item->commit = NULL;
2605 item->arg_offset = bol - buf;
2606 item->arg_len = (int)(eol - bol);
2607 if (item->command == TODO_LABEL ||
2608 item->command == TODO_UPDATE_REF) {
2609 saved = *eol;
2610 *eol = '\0';
2611 ret = check_label_or_ref_arg(item->command, bol);
2612 *eol = saved;
2614 return ret;
2617 if (item->command == TODO_FIXUP) {
2618 if (skip_prefix(bol, "-C", &bol)) {
2619 bol += strspn(bol, " \t");
2620 item->flags |= TODO_REPLACE_FIXUP_MSG;
2621 } else if (skip_prefix(bol, "-c", &bol)) {
2622 bol += strspn(bol, " \t");
2623 item->flags |= TODO_EDIT_FIXUP_MSG;
2627 if (item->command == TODO_MERGE) {
2628 if (skip_prefix(bol, "-C", &bol))
2629 bol += strspn(bol, " \t");
2630 else if (skip_prefix(bol, "-c", &bol)) {
2631 bol += strspn(bol, " \t");
2632 item->flags |= TODO_EDIT_MERGE_MSG;
2633 } else {
2634 item->flags |= TODO_EDIT_MERGE_MSG;
2635 item->commit = NULL;
2636 item->arg_offset = bol - buf;
2637 item->arg_len = (int)(eol - bol);
2638 return 0;
2642 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2643 saved = *end_of_object_name;
2644 *end_of_object_name = '\0';
2645 status = repo_get_oid(r, bol, &commit_oid);
2646 if (status < 0)
2647 error(_("could not parse '%s'"), bol); /* return later */
2648 *end_of_object_name = saved;
2650 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2651 item->arg_offset = bol - buf;
2652 item->arg_len = (int)(eol - bol);
2654 if (status < 0)
2655 return status;
2657 item->commit = lookup_commit_reference(r, &commit_oid);
2658 return item->commit ? 0 : -1;
2661 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2663 const char *todo_file, *bol;
2664 struct strbuf buf = STRBUF_INIT;
2665 int ret = 0;
2667 todo_file = git_path_todo_file();
2668 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2669 if (errno == ENOENT || errno == ENOTDIR)
2670 return -1;
2671 else
2672 return error_errno("unable to open '%s'", todo_file);
2674 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2675 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2676 *action = REPLAY_PICK;
2677 else if (is_command(TODO_REVERT, &bol) &&
2678 (*bol == ' ' || *bol == '\t'))
2679 *action = REPLAY_REVERT;
2680 else
2681 ret = -1;
2683 strbuf_release(&buf);
2685 return ret;
2688 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2689 struct todo_list *todo_list)
2691 struct todo_item *item;
2692 char *p = buf, *next_p;
2693 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2695 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2697 for (i = 1; *p; i++, p = next_p) {
2698 char *eol = strchrnul(p, '\n');
2700 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2702 if (p != eol && eol[-1] == '\r')
2703 eol--; /* strip Carriage Return */
2705 item = append_new_todo(todo_list);
2706 item->offset_in_buf = p - todo_list->buf.buf;
2707 if (parse_insn_line(r, item, buf, p, eol)) {
2708 res = error(_("invalid line %d: %.*s"),
2709 i, (int)(eol - p), p);
2710 item->command = TODO_COMMENT + 1;
2711 item->arg_offset = p - buf;
2712 item->arg_len = (int)(eol - p);
2713 item->commit = NULL;
2716 if (item->command != TODO_COMMENT)
2717 todo_list->total_nr++;
2719 if (fixup_okay)
2720 ; /* do nothing */
2721 else if (is_fixup(item->command))
2722 res = error(_("cannot '%s' without a previous commit"),
2723 command_to_string(item->command));
2724 else if (!is_noop(item->command))
2725 fixup_okay = 1;
2728 return res;
2731 static int count_commands(struct todo_list *todo_list)
2733 int count = 0, i;
2735 for (i = 0; i < todo_list->nr; i++)
2736 if (todo_list->items[i].command != TODO_COMMENT)
2737 count++;
2739 return count;
2742 static int get_item_line_offset(struct todo_list *todo_list, int index)
2744 return index < todo_list->nr ?
2745 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2748 static const char *get_item_line(struct todo_list *todo_list, int index)
2750 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2753 static int get_item_line_length(struct todo_list *todo_list, int index)
2755 return get_item_line_offset(todo_list, index + 1)
2756 - get_item_line_offset(todo_list, index);
2759 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2761 int fd;
2762 ssize_t len;
2764 fd = open(path, O_RDONLY);
2765 if (fd < 0)
2766 return error_errno(_("could not open '%s'"), path);
2767 len = strbuf_read(sb, fd, 0);
2768 close(fd);
2769 if (len < 0)
2770 return error(_("could not read '%s'."), path);
2771 return len;
2774 static int have_finished_the_last_pick(void)
2776 struct strbuf buf = STRBUF_INIT;
2777 const char *eol;
2778 const char *todo_path = git_path_todo_file();
2779 int ret = 0;
2781 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2782 if (errno == ENOENT) {
2783 return 0;
2784 } else {
2785 error_errno("unable to open '%s'", todo_path);
2786 return 0;
2789 /* If there is only one line then we are done */
2790 eol = strchr(buf.buf, '\n');
2791 if (!eol || !eol[1])
2792 ret = 1;
2794 strbuf_release(&buf);
2796 return ret;
2799 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2801 struct replay_opts opts = REPLAY_OPTS_INIT;
2802 int need_cleanup = 0;
2804 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2805 if (!refs_delete_ref(get_main_ref_store(r), "",
2806 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2807 verbose)
2808 warning(_("cancelling a cherry picking in progress"));
2809 opts.action = REPLAY_PICK;
2810 need_cleanup = 1;
2813 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2814 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2815 NULL, REF_NO_DEREF) &&
2816 verbose)
2817 warning(_("cancelling a revert in progress"));
2818 opts.action = REPLAY_REVERT;
2819 need_cleanup = 1;
2822 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2823 NULL, REF_NO_DEREF);
2825 if (!need_cleanup)
2826 return;
2828 if (!have_finished_the_last_pick())
2829 return;
2831 sequencer_remove_state(&opts);
2834 static void todo_list_write_total_nr(struct todo_list *todo_list)
2836 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2838 if (f) {
2839 fprintf(f, "%d\n", todo_list->total_nr);
2840 fclose(f);
2844 static int read_populate_todo(struct repository *r,
2845 struct todo_list *todo_list,
2846 struct replay_opts *opts)
2848 const char *todo_file = get_todo_path(opts);
2849 int res;
2851 strbuf_reset(&todo_list->buf);
2852 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2853 return -1;
2855 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2856 if (res) {
2857 if (is_rebase_i(opts))
2858 return error(_("please fix this using "
2859 "'git rebase --edit-todo'."));
2860 return error(_("unusable instruction sheet: '%s'"), todo_file);
2863 if (!todo_list->nr &&
2864 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2865 return error(_("no commits parsed."));
2867 if (!is_rebase_i(opts)) {
2868 enum todo_command valid =
2869 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2870 int i;
2872 for (i = 0; i < todo_list->nr; i++)
2873 if (valid == todo_list->items[i].command)
2874 continue;
2875 else if (valid == TODO_PICK)
2876 return error(_("cannot cherry-pick during a revert."));
2877 else
2878 return error(_("cannot revert during a cherry-pick."));
2881 if (is_rebase_i(opts)) {
2882 struct todo_list done = TODO_LIST_INIT;
2884 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2885 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2886 todo_list->done_nr = count_commands(&done);
2887 else
2888 todo_list->done_nr = 0;
2890 todo_list->total_nr = todo_list->done_nr
2891 + count_commands(todo_list);
2892 todo_list_release(&done);
2894 todo_list_write_total_nr(todo_list);
2897 return 0;
2900 static int git_config_string_dup(char **dest,
2901 const char *var, const char *value)
2903 if (!value)
2904 return config_error_nonbool(var);
2905 free(*dest);
2906 *dest = xstrdup(value);
2907 return 0;
2910 static int populate_opts_cb(const char *key, const char *value,
2911 const struct config_context *ctx,
2912 void *data)
2914 struct replay_opts *opts = data;
2915 int error_flag = 1;
2917 if (!value)
2918 error_flag = 0;
2919 else if (!strcmp(key, "options.no-commit"))
2920 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2921 else if (!strcmp(key, "options.edit"))
2922 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2923 else if (!strcmp(key, "options.allow-empty"))
2924 opts->allow_empty =
2925 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2926 else if (!strcmp(key, "options.allow-empty-message"))
2927 opts->allow_empty_message =
2928 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2929 else if (!strcmp(key, "options.keep-redundant-commits"))
2930 opts->keep_redundant_commits =
2931 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2932 else if (!strcmp(key, "options.signoff"))
2933 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2934 else if (!strcmp(key, "options.record-origin"))
2935 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2936 else if (!strcmp(key, "options.allow-ff"))
2937 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
2938 else if (!strcmp(key, "options.mainline"))
2939 opts->mainline = git_config_int(key, value, ctx->kvi);
2940 else if (!strcmp(key, "options.strategy"))
2941 git_config_string_dup(&opts->strategy, key, value);
2942 else if (!strcmp(key, "options.gpg-sign"))
2943 git_config_string_dup(&opts->gpg_sign, key, value);
2944 else if (!strcmp(key, "options.strategy-option")) {
2945 strvec_push(&opts->xopts, value);
2946 } else if (!strcmp(key, "options.allow-rerere-auto"))
2947 opts->allow_rerere_auto =
2948 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
2949 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2950 else if (!strcmp(key, "options.default-msg-cleanup")) {
2951 opts->explicit_cleanup = 1;
2952 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2953 } else
2954 return error(_("invalid key: %s"), key);
2956 if (!error_flag)
2957 return error(_("invalid value for '%s': '%s'"), key, value);
2959 return 0;
2962 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2964 int i;
2965 int count;
2966 const char **argv;
2967 char *strategy_opts_string = raw_opts;
2969 if (*strategy_opts_string == ' ')
2970 strategy_opts_string++;
2972 count = split_cmdline(strategy_opts_string, &argv);
2973 if (count < 0)
2974 BUG("could not split '%s': %s", strategy_opts_string,
2975 split_cmdline_strerror(count));
2976 for (i = 0; i < count; i++) {
2977 const char *arg = argv[i];
2979 skip_prefix(arg, "--", &arg);
2980 strvec_push(&opts->xopts, arg);
2982 free(argv);
2985 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2987 strbuf_reset(buf);
2988 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2989 return;
2990 opts->strategy = strbuf_detach(buf, NULL);
2991 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2992 return;
2994 parse_strategy_opts(opts, buf->buf);
2997 static int read_populate_opts(struct replay_opts *opts)
2999 if (is_rebase_i(opts)) {
3000 struct strbuf buf = STRBUF_INIT;
3001 int ret = 0;
3003 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3004 READ_ONELINER_SKIP_IF_EMPTY)) {
3005 if (!starts_with(buf.buf, "-S"))
3006 strbuf_reset(&buf);
3007 else {
3008 free(opts->gpg_sign);
3009 opts->gpg_sign = xstrdup(buf.buf + 2);
3011 strbuf_reset(&buf);
3014 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3015 READ_ONELINER_SKIP_IF_EMPTY)) {
3016 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3017 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3018 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3019 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3020 strbuf_reset(&buf);
3023 if (file_exists(rebase_path_verbose()))
3024 opts->verbose = 1;
3026 if (file_exists(rebase_path_quiet()))
3027 opts->quiet = 1;
3029 if (file_exists(rebase_path_signoff())) {
3030 opts->allow_ff = 0;
3031 opts->signoff = 1;
3034 if (file_exists(rebase_path_cdate_is_adate())) {
3035 opts->allow_ff = 0;
3036 opts->committer_date_is_author_date = 1;
3039 if (file_exists(rebase_path_ignore_date())) {
3040 opts->allow_ff = 0;
3041 opts->ignore_date = 1;
3044 if (file_exists(rebase_path_reschedule_failed_exec()))
3045 opts->reschedule_failed_exec = 1;
3046 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3047 opts->reschedule_failed_exec = 0;
3049 if (file_exists(rebase_path_drop_redundant_commits()))
3050 opts->drop_redundant_commits = 1;
3052 if (file_exists(rebase_path_keep_redundant_commits()))
3053 opts->keep_redundant_commits = 1;
3055 read_strategy_opts(opts, &buf);
3056 strbuf_reset(&buf);
3058 if (read_oneliner(&opts->current_fixups,
3059 rebase_path_current_fixups(),
3060 READ_ONELINER_SKIP_IF_EMPTY)) {
3061 const char *p = opts->current_fixups.buf;
3062 opts->current_fixup_count = 1;
3063 while ((p = strchr(p, '\n'))) {
3064 opts->current_fixup_count++;
3065 p++;
3069 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3070 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3071 ret = error(_("unusable squash-onto"));
3072 goto done_rebase_i;
3074 opts->have_squash_onto = 1;
3077 done_rebase_i:
3078 strbuf_release(&buf);
3079 return ret;
3082 if (!file_exists(git_path_opts_file()))
3083 return 0;
3085 * The function git_parse_source(), called from git_config_from_file(),
3086 * may die() in case of a syntactically incorrect file. We do not care
3087 * about this case, though, because we wrote that file ourselves, so we
3088 * are pretty certain that it is syntactically correct.
3090 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3091 return error(_("malformed options sheet: '%s'"),
3092 git_path_opts_file());
3093 return 0;
3096 static void write_strategy_opts(struct replay_opts *opts)
3098 struct strbuf buf = STRBUF_INIT;
3101 * Quote strategy options so that they can be read correctly
3102 * by split_cmdline().
3104 quote_cmdline(&buf, opts->xopts.v);
3105 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3106 strbuf_release(&buf);
3109 int write_basic_state(struct replay_opts *opts, const char *head_name,
3110 struct commit *onto, const struct object_id *orig_head)
3112 if (head_name)
3113 write_file(rebase_path_head_name(), "%s\n", head_name);
3114 if (onto)
3115 write_file(rebase_path_onto(), "%s\n",
3116 oid_to_hex(&onto->object.oid));
3117 if (orig_head)
3118 write_file(rebase_path_orig_head(), "%s\n",
3119 oid_to_hex(orig_head));
3121 if (opts->quiet)
3122 write_file(rebase_path_quiet(), "%s", "");
3123 if (opts->verbose)
3124 write_file(rebase_path_verbose(), "%s", "");
3125 if (opts->strategy)
3126 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3127 if (opts->xopts.nr > 0)
3128 write_strategy_opts(opts);
3130 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3131 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3132 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3133 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3135 if (opts->gpg_sign)
3136 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3137 if (opts->signoff)
3138 write_file(rebase_path_signoff(), "--signoff\n");
3139 if (opts->drop_redundant_commits)
3140 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3141 if (opts->keep_redundant_commits)
3142 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3143 if (opts->committer_date_is_author_date)
3144 write_file(rebase_path_cdate_is_adate(), "%s", "");
3145 if (opts->ignore_date)
3146 write_file(rebase_path_ignore_date(), "%s", "");
3147 if (opts->reschedule_failed_exec)
3148 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3149 else
3150 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3152 return 0;
3155 static int walk_revs_populate_todo(struct todo_list *todo_list,
3156 struct replay_opts *opts)
3158 enum todo_command command = opts->action == REPLAY_PICK ?
3159 TODO_PICK : TODO_REVERT;
3160 const char *command_string = todo_command_info[command].str;
3161 const char *encoding;
3162 struct commit *commit;
3164 if (prepare_revs(opts))
3165 return -1;
3167 encoding = get_log_output_encoding();
3169 while ((commit = get_revision(opts->revs))) {
3170 struct todo_item *item = append_new_todo(todo_list);
3171 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3172 commit, NULL,
3173 encoding);
3174 const char *subject;
3175 int subject_len;
3177 item->command = command;
3178 item->commit = commit;
3179 item->arg_offset = 0;
3180 item->arg_len = 0;
3181 item->offset_in_buf = todo_list->buf.len;
3182 subject_len = find_commit_subject(commit_buffer, &subject);
3183 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3184 short_commit_name(the_repository, commit),
3185 subject_len, subject);
3186 repo_unuse_commit_buffer(the_repository, commit,
3187 commit_buffer);
3190 if (!todo_list->nr)
3191 return error(_("empty commit set passed"));
3193 return 0;
3196 static int create_seq_dir(struct repository *r)
3198 enum replay_action action;
3199 const char *in_progress_error = NULL;
3200 const char *in_progress_advice = NULL;
3201 unsigned int advise_skip =
3202 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3203 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3205 if (!sequencer_get_last_command(r, &action)) {
3206 switch (action) {
3207 case REPLAY_REVERT:
3208 in_progress_error = _("revert is already in progress");
3209 in_progress_advice =
3210 _("try \"git revert (--continue | %s--abort | --quit)\"");
3211 break;
3212 case REPLAY_PICK:
3213 in_progress_error = _("cherry-pick is already in progress");
3214 in_progress_advice =
3215 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3216 break;
3217 default:
3218 BUG("unexpected action in create_seq_dir");
3221 if (in_progress_error) {
3222 error("%s", in_progress_error);
3223 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3224 advise(in_progress_advice,
3225 advise_skip ? "--skip | " : "");
3226 return -1;
3228 if (mkdir(git_path_seq_dir(), 0777) < 0)
3229 return error_errno(_("could not create sequencer directory '%s'"),
3230 git_path_seq_dir());
3232 return 0;
3235 static int save_head(const char *head)
3237 return write_message(head, strlen(head), git_path_head_file(), 1);
3240 static int rollback_is_safe(void)
3242 struct strbuf sb = STRBUF_INIT;
3243 struct object_id expected_head, actual_head;
3245 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3246 strbuf_trim(&sb);
3247 if (get_oid_hex(sb.buf, &expected_head)) {
3248 strbuf_release(&sb);
3249 die(_("could not parse %s"), git_path_abort_safety_file());
3251 strbuf_release(&sb);
3253 else if (errno == ENOENT)
3254 oidclr(&expected_head);
3255 else
3256 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3258 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3259 oidclr(&actual_head);
3261 return oideq(&actual_head, &expected_head);
3264 static int reset_merge(const struct object_id *oid)
3266 struct child_process cmd = CHILD_PROCESS_INIT;
3268 cmd.git_cmd = 1;
3269 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3271 if (!is_null_oid(oid))
3272 strvec_push(&cmd.args, oid_to_hex(oid));
3274 return run_command(&cmd);
3277 static int rollback_single_pick(struct repository *r)
3279 struct object_id head_oid;
3281 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3282 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3283 return error(_("no cherry-pick or revert in progress"));
3284 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3285 return error(_("cannot resolve HEAD"));
3286 if (is_null_oid(&head_oid))
3287 return error(_("cannot abort from a branch yet to be born"));
3288 return reset_merge(&head_oid);
3291 static int skip_single_pick(void)
3293 struct object_id head;
3295 if (read_ref_full("HEAD", 0, &head, NULL))
3296 return error(_("cannot resolve HEAD"));
3297 return reset_merge(&head);
3300 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3302 FILE *f;
3303 struct object_id oid;
3304 struct strbuf buf = STRBUF_INIT;
3305 const char *p;
3307 f = fopen(git_path_head_file(), "r");
3308 if (!f && errno == ENOENT) {
3310 * There is no multiple-cherry-pick in progress.
3311 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3312 * a single-cherry-pick in progress, abort that.
3314 return rollback_single_pick(r);
3316 if (!f)
3317 return error_errno(_("cannot open '%s'"), git_path_head_file());
3318 if (strbuf_getline_lf(&buf, f)) {
3319 error(_("cannot read '%s': %s"), git_path_head_file(),
3320 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3321 fclose(f);
3322 goto fail;
3324 fclose(f);
3325 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3326 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3327 git_path_head_file());
3328 goto fail;
3330 if (is_null_oid(&oid)) {
3331 error(_("cannot abort from a branch yet to be born"));
3332 goto fail;
3335 if (!rollback_is_safe()) {
3336 /* Do not error, just do not rollback */
3337 warning(_("You seem to have moved HEAD. "
3338 "Not rewinding, check your HEAD!"));
3339 } else
3340 if (reset_merge(&oid))
3341 goto fail;
3342 strbuf_release(&buf);
3343 return sequencer_remove_state(opts);
3344 fail:
3345 strbuf_release(&buf);
3346 return -1;
3349 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3351 enum replay_action action = -1;
3352 sequencer_get_last_command(r, &action);
3355 * Check whether the subcommand requested to skip the commit is actually
3356 * in progress and that it's safe to skip the commit.
3358 * opts->action tells us which subcommand requested to skip the commit.
3359 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3360 * action is in progress and we can skip the commit.
3362 * Otherwise we check that the last instruction was related to the
3363 * particular subcommand we're trying to execute and barf if that's not
3364 * the case.
3366 * Finally we check that the rollback is "safe", i.e., has the HEAD
3367 * moved? In this case, it doesn't make sense to "reset the merge" and
3368 * "skip the commit" as the user already handled this by committing. But
3369 * we'd not want to barf here, instead give advice on how to proceed. We
3370 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3371 * it gets removed when the user commits, so if it still exists we're
3372 * sure the user can't have committed before.
3374 switch (opts->action) {
3375 case REPLAY_REVERT:
3376 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3377 if (action != REPLAY_REVERT)
3378 return error(_("no revert in progress"));
3379 if (!rollback_is_safe())
3380 goto give_advice;
3382 break;
3383 case REPLAY_PICK:
3384 if (!refs_ref_exists(get_main_ref_store(r),
3385 "CHERRY_PICK_HEAD")) {
3386 if (action != REPLAY_PICK)
3387 return error(_("no cherry-pick in progress"));
3388 if (!rollback_is_safe())
3389 goto give_advice;
3391 break;
3392 default:
3393 BUG("unexpected action in sequencer_skip");
3396 if (skip_single_pick())
3397 return error(_("failed to skip the commit"));
3398 if (!is_directory(git_path_seq_dir()))
3399 return 0;
3401 return sequencer_continue(r, opts);
3403 give_advice:
3404 error(_("there is nothing to skip"));
3406 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3407 advise(_("have you committed already?\n"
3408 "try \"git %s --continue\""),
3409 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3411 return -1;
3414 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3415 int reschedule)
3417 struct lock_file todo_lock = LOCK_INIT;
3418 const char *todo_path = get_todo_path(opts);
3419 int next = todo_list->current, offset, fd;
3422 * rebase -i writes "git-rebase-todo" without the currently executing
3423 * command, appending it to "done" instead.
3425 if (is_rebase_i(opts) && !reschedule)
3426 next++;
3428 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3429 if (fd < 0)
3430 return error_errno(_("could not lock '%s'"), todo_path);
3431 offset = get_item_line_offset(todo_list, next);
3432 if (write_in_full(fd, todo_list->buf.buf + offset,
3433 todo_list->buf.len - offset) < 0)
3434 return error_errno(_("could not write to '%s'"), todo_path);
3435 if (commit_lock_file(&todo_lock) < 0)
3436 return error(_("failed to finalize '%s'"), todo_path);
3438 if (is_rebase_i(opts) && !reschedule && next > 0) {
3439 const char *done = rebase_path_done();
3440 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3441 int ret = 0;
3443 if (fd < 0)
3444 return 0;
3445 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3446 get_item_line_length(todo_list, next - 1))
3447 < 0)
3448 ret = error_errno(_("could not write to '%s'"), done);
3449 if (close(fd) < 0)
3450 ret = error_errno(_("failed to finalize '%s'"), done);
3451 return ret;
3453 return 0;
3456 static int save_opts(struct replay_opts *opts)
3458 const char *opts_file = git_path_opts_file();
3459 int res = 0;
3461 if (opts->no_commit)
3462 res |= git_config_set_in_file_gently(opts_file,
3463 "options.no-commit", "true");
3464 if (opts->edit >= 0)
3465 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3466 opts->edit ? "true" : "false");
3467 if (opts->allow_empty)
3468 res |= git_config_set_in_file_gently(opts_file,
3469 "options.allow-empty", "true");
3470 if (opts->allow_empty_message)
3471 res |= git_config_set_in_file_gently(opts_file,
3472 "options.allow-empty-message", "true");
3473 if (opts->keep_redundant_commits)
3474 res |= git_config_set_in_file_gently(opts_file,
3475 "options.keep-redundant-commits", "true");
3476 if (opts->signoff)
3477 res |= git_config_set_in_file_gently(opts_file,
3478 "options.signoff", "true");
3479 if (opts->record_origin)
3480 res |= git_config_set_in_file_gently(opts_file,
3481 "options.record-origin", "true");
3482 if (opts->allow_ff)
3483 res |= git_config_set_in_file_gently(opts_file,
3484 "options.allow-ff", "true");
3485 if (opts->mainline) {
3486 struct strbuf buf = STRBUF_INIT;
3487 strbuf_addf(&buf, "%d", opts->mainline);
3488 res |= git_config_set_in_file_gently(opts_file,
3489 "options.mainline", buf.buf);
3490 strbuf_release(&buf);
3492 if (opts->strategy)
3493 res |= git_config_set_in_file_gently(opts_file,
3494 "options.strategy", opts->strategy);
3495 if (opts->gpg_sign)
3496 res |= git_config_set_in_file_gently(opts_file,
3497 "options.gpg-sign", opts->gpg_sign);
3498 for (size_t i = 0; i < opts->xopts.nr; i++)
3499 res |= git_config_set_multivar_in_file_gently(opts_file,
3500 "options.strategy-option",
3501 opts->xopts.v[i], "^$", 0);
3502 if (opts->allow_rerere_auto)
3503 res |= git_config_set_in_file_gently(opts_file,
3504 "options.allow-rerere-auto",
3505 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3506 "true" : "false");
3508 if (opts->explicit_cleanup)
3509 res |= git_config_set_in_file_gently(opts_file,
3510 "options.default-msg-cleanup",
3511 describe_cleanup_mode(opts->default_msg_cleanup));
3512 return res;
3515 static int make_patch(struct repository *r,
3516 struct commit *commit,
3517 struct replay_opts *opts)
3519 struct rev_info log_tree_opt;
3520 const char *subject;
3521 char hex[GIT_MAX_HEXSZ + 1];
3522 int res = 0;
3524 if (!is_rebase_i(opts))
3525 BUG("make_patch should only be called when rebasing");
3527 oid_to_hex_r(hex, &commit->object.oid);
3528 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3529 return -1;
3530 res |= write_rebase_head(&commit->object.oid);
3532 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3533 repo_init_revisions(r, &log_tree_opt, NULL);
3534 log_tree_opt.abbrev = 0;
3535 log_tree_opt.diff = 1;
3536 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3537 log_tree_opt.disable_stdin = 1;
3538 log_tree_opt.no_commit_id = 1;
3539 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3540 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3541 if (!log_tree_opt.diffopt.file)
3542 res |= error_errno(_("could not open '%s'"),
3543 rebase_path_patch());
3544 else {
3545 res |= log_tree_commit(&log_tree_opt, commit);
3546 fclose(log_tree_opt.diffopt.file);
3549 if (!file_exists(rebase_path_message())) {
3550 const char *encoding = get_commit_output_encoding();
3551 const char *commit_buffer = repo_logmsg_reencode(r,
3552 commit, NULL,
3553 encoding);
3554 find_commit_subject(commit_buffer, &subject);
3555 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3556 repo_unuse_commit_buffer(r, commit,
3557 commit_buffer);
3559 release_revisions(&log_tree_opt);
3561 return res;
3564 static int intend_to_amend(void)
3566 struct object_id head;
3567 char *p;
3569 if (repo_get_oid(the_repository, "HEAD", &head))
3570 return error(_("cannot read HEAD"));
3572 p = oid_to_hex(&head);
3573 return write_message(p, strlen(p), rebase_path_amend(), 1);
3576 static int error_with_patch(struct repository *r,
3577 struct commit *commit,
3578 const char *subject, int subject_len,
3579 struct replay_opts *opts,
3580 int exit_code, int to_amend)
3582 if (commit) {
3583 if (make_patch(r, commit, opts))
3584 return -1;
3585 } else if (copy_file(rebase_path_message(),
3586 git_path_merge_msg(r), 0666))
3587 return error(_("unable to copy '%s' to '%s'"),
3588 git_path_merge_msg(r), rebase_path_message());
3590 if (to_amend) {
3591 if (intend_to_amend())
3592 return -1;
3594 fprintf(stderr,
3595 _("You can amend the commit now, with\n"
3596 "\n"
3597 " git commit --amend %s\n"
3598 "\n"
3599 "Once you are satisfied with your changes, run\n"
3600 "\n"
3601 " git rebase --continue\n"),
3602 gpg_sign_opt_quoted(opts));
3603 } else if (exit_code) {
3604 if (commit)
3605 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3606 short_commit_name(r, commit), subject_len, subject);
3607 else
3609 * We don't have the hash of the parent so
3610 * just print the line from the todo file.
3612 fprintf_ln(stderr, _("Could not merge %.*s"),
3613 subject_len, subject);
3616 return exit_code;
3619 static int error_failed_squash(struct repository *r,
3620 struct commit *commit,
3621 struct replay_opts *opts,
3622 int subject_len,
3623 const char *subject)
3625 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3626 return error(_("could not copy '%s' to '%s'"),
3627 rebase_path_squash_msg(), rebase_path_message());
3628 unlink(git_path_merge_msg(r));
3629 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3630 return error(_("could not copy '%s' to '%s'"),
3631 rebase_path_message(),
3632 git_path_merge_msg(r));
3633 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3636 static int do_exec(struct repository *r, const char *command_line)
3638 struct child_process cmd = CHILD_PROCESS_INIT;
3639 int dirty, status;
3641 fprintf(stderr, _("Executing: %s\n"), command_line);
3642 cmd.use_shell = 1;
3643 strvec_push(&cmd.args, command_line);
3644 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3645 status = run_command(&cmd);
3647 /* force re-reading of the cache */
3648 discard_index(r->index);
3649 if (repo_read_index(r) < 0)
3650 return error(_("could not read index"));
3652 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3654 if (status) {
3655 warning(_("execution failed: %s\n%s"
3656 "You can fix the problem, and then run\n"
3657 "\n"
3658 " git rebase --continue\n"
3659 "\n"),
3660 command_line,
3661 dirty ? _("and made changes to the index and/or the "
3662 "working tree.\n") : "");
3663 if (status == 127)
3664 /* command not found */
3665 status = 1;
3666 } else if (dirty) {
3667 warning(_("execution succeeded: %s\nbut "
3668 "left changes to the index and/or the working tree.\n"
3669 "Commit or stash your changes, and then run\n"
3670 "\n"
3671 " git rebase --continue\n"
3672 "\n"), command_line);
3673 status = 1;
3676 return status;
3679 __attribute__((format (printf, 2, 3)))
3680 static int safe_append(const char *filename, const char *fmt, ...)
3682 va_list ap;
3683 struct lock_file lock = LOCK_INIT;
3684 int fd = hold_lock_file_for_update(&lock, filename,
3685 LOCK_REPORT_ON_ERROR);
3686 struct strbuf buf = STRBUF_INIT;
3688 if (fd < 0)
3689 return -1;
3691 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3692 error_errno(_("could not read '%s'"), filename);
3693 rollback_lock_file(&lock);
3694 return -1;
3696 strbuf_complete(&buf, '\n');
3697 va_start(ap, fmt);
3698 strbuf_vaddf(&buf, fmt, ap);
3699 va_end(ap);
3701 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3702 error_errno(_("could not write to '%s'"), filename);
3703 strbuf_release(&buf);
3704 rollback_lock_file(&lock);
3705 return -1;
3707 if (commit_lock_file(&lock) < 0) {
3708 strbuf_release(&buf);
3709 return error(_("failed to finalize '%s'"), filename);
3712 strbuf_release(&buf);
3713 return 0;
3716 static int do_label(struct repository *r, const char *name, int len)
3718 struct ref_store *refs = get_main_ref_store(r);
3719 struct ref_transaction *transaction;
3720 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3721 struct strbuf msg = STRBUF_INIT;
3722 int ret = 0;
3723 struct object_id head_oid;
3725 if (len == 1 && *name == '#')
3726 return error(_("illegal label name: '%.*s'"), len, name);
3728 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3729 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3731 transaction = ref_store_transaction_begin(refs, &err);
3732 if (!transaction) {
3733 error("%s", err.buf);
3734 ret = -1;
3735 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3736 error(_("could not read HEAD"));
3737 ret = -1;
3738 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3739 NULL, 0, msg.buf, &err) < 0 ||
3740 ref_transaction_commit(transaction, &err)) {
3741 error("%s", err.buf);
3742 ret = -1;
3744 ref_transaction_free(transaction);
3745 strbuf_release(&err);
3746 strbuf_release(&msg);
3748 if (!ret)
3749 ret = safe_append(rebase_path_refs_to_delete(),
3750 "%s\n", ref_name.buf);
3751 strbuf_release(&ref_name);
3753 return ret;
3756 static const char *sequencer_reflog_action(struct replay_opts *opts)
3758 if (!opts->reflog_action) {
3759 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3760 opts->reflog_action =
3761 xstrdup(opts->reflog_action ? opts->reflog_action
3762 : action_name(opts));
3765 return opts->reflog_action;
3768 __attribute__((format (printf, 3, 4)))
3769 static const char *reflog_message(struct replay_opts *opts,
3770 const char *sub_action, const char *fmt, ...)
3772 va_list ap;
3773 static struct strbuf buf = STRBUF_INIT;
3775 va_start(ap, fmt);
3776 strbuf_reset(&buf);
3777 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3778 if (sub_action)
3779 strbuf_addf(&buf, " (%s)", sub_action);
3780 if (fmt) {
3781 strbuf_addstr(&buf, ": ");
3782 strbuf_vaddf(&buf, fmt, ap);
3784 va_end(ap);
3786 return buf.buf;
3789 static struct commit *lookup_label(struct repository *r, const char *label,
3790 int len, struct strbuf *buf)
3792 struct commit *commit;
3793 struct object_id oid;
3795 strbuf_reset(buf);
3796 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3797 if (!read_ref(buf->buf, &oid)) {
3798 commit = lookup_commit_object(r, &oid);
3799 } else {
3800 /* fall back to non-rewritten ref or commit */
3801 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3802 commit = lookup_commit_reference_by_name(buf->buf);
3805 if (!commit)
3806 error(_("could not resolve '%s'"), buf->buf);
3808 return commit;
3811 static int do_reset(struct repository *r,
3812 const char *name, int len,
3813 struct replay_opts *opts)
3815 struct strbuf ref_name = STRBUF_INIT;
3816 struct object_id oid;
3817 struct lock_file lock = LOCK_INIT;
3818 struct tree_desc desc = { 0 };
3819 struct tree *tree;
3820 struct unpack_trees_options unpack_tree_opts = { 0 };
3821 int ret = 0;
3823 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3824 return -1;
3826 if (len == 10 && !strncmp("[new root]", name, len)) {
3827 if (!opts->have_squash_onto) {
3828 const char *hex;
3829 if (commit_tree("", 0, the_hash_algo->empty_tree,
3830 NULL, &opts->squash_onto,
3831 NULL, NULL))
3832 return error(_("writing fake root commit"));
3833 opts->have_squash_onto = 1;
3834 hex = oid_to_hex(&opts->squash_onto);
3835 if (write_message(hex, strlen(hex),
3836 rebase_path_squash_onto(), 0))
3837 return error(_("writing squash-onto"));
3839 oidcpy(&oid, &opts->squash_onto);
3840 } else {
3841 int i;
3842 struct commit *commit;
3844 /* Determine the length of the label */
3845 for (i = 0; i < len; i++)
3846 if (isspace(name[i]))
3847 break;
3848 len = i;
3850 commit = lookup_label(r, name, len, &ref_name);
3851 if (!commit) {
3852 ret = -1;
3853 goto cleanup;
3855 oid = commit->object.oid;
3858 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3859 unpack_tree_opts.head_idx = 1;
3860 unpack_tree_opts.src_index = r->index;
3861 unpack_tree_opts.dst_index = r->index;
3862 unpack_tree_opts.fn = oneway_merge;
3863 unpack_tree_opts.merge = 1;
3864 unpack_tree_opts.update = 1;
3865 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3866 unpack_tree_opts.skip_cache_tree_update = 1;
3867 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3869 if (repo_read_index_unmerged(r)) {
3870 ret = error_resolve_conflict(action_name(opts));
3871 goto cleanup;
3874 if (!fill_tree_descriptor(r, &desc, &oid)) {
3875 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3876 goto cleanup;
3879 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3880 ret = -1;
3881 goto cleanup;
3884 tree = parse_tree_indirect(&oid);
3885 prime_cache_tree(r, r->index, tree);
3887 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3888 ret = error(_("could not write index"));
3890 if (!ret)
3891 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3892 len, name), "HEAD", &oid,
3893 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3894 cleanup:
3895 free((void *)desc.buffer);
3896 if (ret < 0)
3897 rollback_lock_file(&lock);
3898 strbuf_release(&ref_name);
3899 clear_unpack_trees_porcelain(&unpack_tree_opts);
3900 return ret;
3903 static int do_merge(struct repository *r,
3904 struct commit *commit,
3905 const char *arg, int arg_len,
3906 int flags, int *check_todo, struct replay_opts *opts)
3908 int run_commit_flags = 0;
3909 struct strbuf ref_name = STRBUF_INIT;
3910 struct commit *head_commit, *merge_commit, *i;
3911 struct commit_list *bases = NULL, *j;
3912 struct commit_list *to_merge = NULL, **tail = &to_merge;
3913 const char *strategy = !opts->xopts.nr &&
3914 (!opts->strategy ||
3915 !strcmp(opts->strategy, "recursive") ||
3916 !strcmp(opts->strategy, "ort")) ?
3917 NULL : opts->strategy;
3918 struct merge_options o;
3919 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3920 static struct lock_file lock;
3921 const char *p;
3923 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3924 ret = -1;
3925 goto leave_merge;
3928 head_commit = lookup_commit_reference_by_name("HEAD");
3929 if (!head_commit) {
3930 ret = error(_("cannot merge without a current revision"));
3931 goto leave_merge;
3935 * For octopus merges, the arg starts with the list of revisions to be
3936 * merged. The list is optionally followed by '#' and the oneline.
3938 merge_arg_len = oneline_offset = arg_len;
3939 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3940 if (!*p)
3941 break;
3942 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3943 p += 1 + strspn(p + 1, " \t\n");
3944 oneline_offset = p - arg;
3945 break;
3947 k = strcspn(p, " \t\n");
3948 if (!k)
3949 continue;
3950 merge_commit = lookup_label(r, p, k, &ref_name);
3951 if (!merge_commit) {
3952 ret = error(_("unable to parse '%.*s'"), k, p);
3953 goto leave_merge;
3955 tail = &commit_list_insert(merge_commit, tail)->next;
3956 p += k;
3957 merge_arg_len = p - arg;
3960 if (!to_merge) {
3961 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3962 goto leave_merge;
3965 if (opts->have_squash_onto &&
3966 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3968 * When the user tells us to "merge" something into a
3969 * "[new root]", let's simply fast-forward to the merge head.
3971 rollback_lock_file(&lock);
3972 if (to_merge->next)
3973 ret = error(_("octopus merge cannot be executed on "
3974 "top of a [new root]"));
3975 else
3976 ret = fast_forward_to(r, &to_merge->item->object.oid,
3977 &head_commit->object.oid, 0,
3978 opts);
3979 goto leave_merge;
3983 * If HEAD is not identical to the first parent of the original merge
3984 * commit, we cannot fast-forward.
3986 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3987 oideq(&commit->parents->item->object.oid,
3988 &head_commit->object.oid);
3991 * If any merge head is different from the original one, we cannot
3992 * fast-forward.
3994 if (can_fast_forward) {
3995 struct commit_list *p = commit->parents->next;
3997 for (j = to_merge; j && p; j = j->next, p = p->next)
3998 if (!oideq(&j->item->object.oid,
3999 &p->item->object.oid)) {
4000 can_fast_forward = 0;
4001 break;
4004 * If the number of merge heads differs from the original merge
4005 * commit, we cannot fast-forward.
4007 if (j || p)
4008 can_fast_forward = 0;
4011 if (can_fast_forward) {
4012 rollback_lock_file(&lock);
4013 ret = fast_forward_to(r, &commit->object.oid,
4014 &head_commit->object.oid, 0, opts);
4015 if (flags & TODO_EDIT_MERGE_MSG)
4016 goto fast_forward_edit;
4018 goto leave_merge;
4021 if (commit) {
4022 const char *encoding = get_commit_output_encoding();
4023 const char *message = repo_logmsg_reencode(r, commit, NULL,
4024 encoding);
4025 const char *body;
4026 int len;
4028 if (!message) {
4029 ret = error(_("could not get commit message of '%s'"),
4030 oid_to_hex(&commit->object.oid));
4031 goto leave_merge;
4033 write_author_script(message);
4034 find_commit_subject(message, &body);
4035 len = strlen(body);
4036 ret = write_message(body, len, git_path_merge_msg(r), 0);
4037 repo_unuse_commit_buffer(r, commit, message);
4038 if (ret) {
4039 error_errno(_("could not write '%s'"),
4040 git_path_merge_msg(r));
4041 goto leave_merge;
4043 } else {
4044 struct strbuf buf = STRBUF_INIT;
4045 int len;
4047 strbuf_addf(&buf, "author %s", git_author_info(0));
4048 write_author_script(buf.buf);
4049 strbuf_reset(&buf);
4051 if (oneline_offset < arg_len) {
4052 p = arg + oneline_offset;
4053 len = arg_len - oneline_offset;
4054 } else {
4055 strbuf_addf(&buf, "Merge %s '%.*s'",
4056 to_merge->next ? "branches" : "branch",
4057 merge_arg_len, arg);
4058 p = buf.buf;
4059 len = buf.len;
4062 ret = write_message(p, len, git_path_merge_msg(r), 0);
4063 strbuf_release(&buf);
4064 if (ret) {
4065 error_errno(_("could not write '%s'"),
4066 git_path_merge_msg(r));
4067 goto leave_merge;
4071 if (strategy || to_merge->next) {
4072 /* Octopus merge */
4073 struct child_process cmd = CHILD_PROCESS_INIT;
4075 if (read_env_script(&cmd.env)) {
4076 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4078 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4079 goto leave_merge;
4082 if (opts->committer_date_is_author_date)
4083 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4084 opts->ignore_date ?
4085 "" :
4086 author_date_from_env(&cmd.env));
4087 if (opts->ignore_date)
4088 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4090 cmd.git_cmd = 1;
4091 strvec_push(&cmd.args, "merge");
4092 strvec_push(&cmd.args, "-s");
4093 if (!strategy)
4094 strvec_push(&cmd.args, "octopus");
4095 else {
4096 strvec_push(&cmd.args, strategy);
4097 for (k = 0; k < opts->xopts.nr; k++)
4098 strvec_pushf(&cmd.args,
4099 "-X%s", opts->xopts.v[k]);
4101 if (!(flags & TODO_EDIT_MERGE_MSG))
4102 strvec_push(&cmd.args, "--no-edit");
4103 else
4104 strvec_push(&cmd.args, "--edit");
4105 strvec_push(&cmd.args, "--no-ff");
4106 strvec_push(&cmd.args, "--no-log");
4107 strvec_push(&cmd.args, "--no-stat");
4108 strvec_push(&cmd.args, "-F");
4109 strvec_push(&cmd.args, git_path_merge_msg(r));
4110 if (opts->gpg_sign)
4111 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4112 else
4113 strvec_push(&cmd.args, "--no-gpg-sign");
4115 /* Add the tips to be merged */
4116 for (j = to_merge; j; j = j->next)
4117 strvec_push(&cmd.args,
4118 oid_to_hex(&j->item->object.oid));
4120 strbuf_release(&ref_name);
4121 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4122 NULL, REF_NO_DEREF);
4123 rollback_lock_file(&lock);
4125 ret = run_command(&cmd);
4127 /* force re-reading of the cache */
4128 if (!ret) {
4129 discard_index(r->index);
4130 if (repo_read_index(r) < 0)
4131 ret = error(_("could not read index"));
4133 goto leave_merge;
4136 merge_commit = to_merge->item;
4137 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4138 ret = -1;
4139 goto leave_merge;
4142 if (bases && oideq(&merge_commit->object.oid,
4143 &bases->item->object.oid)) {
4144 ret = 0;
4145 /* skip merging an ancestor of HEAD */
4146 goto leave_merge;
4149 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4150 git_path_merge_head(r), 0);
4151 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4153 bases = reverse_commit_list(bases);
4155 repo_read_index(r);
4156 init_merge_options(&o, r);
4157 o.branch1 = "HEAD";
4158 o.branch2 = ref_name.buf;
4159 o.buffer_output = 2;
4161 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4163 * TODO: Should use merge_incore_recursive() and
4164 * merge_switch_to_result(), skipping the call to
4165 * merge_switch_to_result() when we don't actually need to
4166 * update the index and working copy immediately.
4168 ret = merge_ort_recursive(&o,
4169 head_commit, merge_commit, bases,
4170 &i);
4171 } else {
4172 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4173 &i);
4175 if (ret <= 0)
4176 fputs(o.obuf.buf, stdout);
4177 strbuf_release(&o.obuf);
4178 if (ret < 0) {
4179 error(_("could not even attempt to merge '%.*s'"),
4180 merge_arg_len, arg);
4181 unlink(git_path_merge_msg(r));
4182 goto leave_merge;
4185 * The return value of merge_recursive() is 1 on clean, and 0 on
4186 * unclean merge.
4188 * Let's reverse that, so that do_merge() returns 0 upon success and
4189 * 1 upon failed merge (keeping the return value -1 for the cases where
4190 * we will want to reschedule the `merge` command).
4192 ret = !ret;
4194 if (r->index->cache_changed &&
4195 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4196 ret = error(_("merge: Unable to write new index file"));
4197 goto leave_merge;
4200 rollback_lock_file(&lock);
4201 if (ret)
4202 repo_rerere(r, opts->allow_rerere_auto);
4203 else
4205 * In case of problems, we now want to return a positive
4206 * value (a negative one would indicate that the `merge`
4207 * command needs to be rescheduled).
4209 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4210 run_commit_flags);
4212 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4213 fast_forward_edit:
4214 *check_todo = 1;
4215 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4216 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4220 leave_merge:
4221 strbuf_release(&ref_name);
4222 rollback_lock_file(&lock);
4223 free_commit_list(to_merge);
4224 return ret;
4227 static int write_update_refs_state(struct string_list *refs_to_oids)
4229 int result = 0;
4230 struct lock_file lock = LOCK_INIT;
4231 FILE *fp = NULL;
4232 struct string_list_item *item;
4233 char *path;
4235 path = rebase_path_update_refs(the_repository->gitdir);
4237 if (!refs_to_oids->nr) {
4238 if (unlink(path) && errno != ENOENT)
4239 result = error_errno(_("could not unlink: %s"), path);
4240 goto cleanup;
4243 if (safe_create_leading_directories(path)) {
4244 result = error(_("unable to create leading directories of %s"),
4245 path);
4246 goto cleanup;
4249 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4250 result = error(_("another 'rebase' process appears to be running; "
4251 "'%s.lock' already exists"),
4252 path);
4253 goto cleanup;
4256 fp = fdopen_lock_file(&lock, "w");
4257 if (!fp) {
4258 result = error_errno(_("could not open '%s' for writing"), path);
4259 rollback_lock_file(&lock);
4260 goto cleanup;
4263 for_each_string_list_item(item, refs_to_oids) {
4264 struct update_ref_record *rec = item->util;
4265 fprintf(fp, "%s\n%s\n%s\n", item->string,
4266 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4269 result = commit_lock_file(&lock);
4271 cleanup:
4272 free(path);
4273 return result;
4277 * Parse the update-refs file for the current rebase, then remove the
4278 * refs that do not appear in the todo_list (and have not had updated
4279 * values stored) and add refs that are in the todo_list but not
4280 * represented in the update-refs file.
4282 * If there are changes to the update-refs list, then write the new state
4283 * to disk.
4285 void todo_list_filter_update_refs(struct repository *r,
4286 struct todo_list *todo_list)
4288 int i;
4289 int updated = 0;
4290 struct string_list update_refs = STRING_LIST_INIT_DUP;
4292 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4295 * For each item in the update_refs list, if it has no updated
4296 * value and does not appear in the todo_list, then remove it
4297 * from the update_refs list.
4299 for (i = 0; i < update_refs.nr; i++) {
4300 int j;
4301 int found = 0;
4302 const char *ref = update_refs.items[i].string;
4303 size_t reflen = strlen(ref);
4304 struct update_ref_record *rec = update_refs.items[i].util;
4306 /* OID already stored as updated. */
4307 if (!is_null_oid(&rec->after))
4308 continue;
4310 for (j = 0; !found && j < todo_list->nr; j++) {
4311 struct todo_item *item = &todo_list->items[j];
4312 const char *arg = todo_list->buf.buf + item->arg_offset;
4314 if (item->command != TODO_UPDATE_REF)
4315 continue;
4317 if (item->arg_len != reflen ||
4318 strncmp(arg, ref, reflen))
4319 continue;
4321 found = 1;
4324 if (!found) {
4325 free(update_refs.items[i].string);
4326 free(update_refs.items[i].util);
4328 update_refs.nr--;
4329 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4331 updated = 1;
4332 i--;
4337 * For each todo_item, check if its ref is in the update_refs list.
4338 * If not, then add it as an un-updated ref.
4340 for (i = 0; i < todo_list->nr; i++) {
4341 struct todo_item *item = &todo_list->items[i];
4342 const char *arg = todo_list->buf.buf + item->arg_offset;
4343 int j, found = 0;
4345 if (item->command != TODO_UPDATE_REF)
4346 continue;
4348 for (j = 0; !found && j < update_refs.nr; j++) {
4349 const char *ref = update_refs.items[j].string;
4351 found = strlen(ref) == item->arg_len &&
4352 !strncmp(ref, arg, item->arg_len);
4355 if (!found) {
4356 struct string_list_item *inserted;
4357 struct strbuf argref = STRBUF_INIT;
4359 strbuf_add(&argref, arg, item->arg_len);
4360 inserted = string_list_insert(&update_refs, argref.buf);
4361 inserted->util = init_update_ref_record(argref.buf);
4362 strbuf_release(&argref);
4363 updated = 1;
4367 if (updated)
4368 write_update_refs_state(&update_refs);
4369 string_list_clear(&update_refs, 1);
4372 static int do_update_ref(struct repository *r, const char *refname)
4374 struct string_list_item *item;
4375 struct string_list list = STRING_LIST_INIT_DUP;
4377 if (sequencer_get_update_refs_state(r->gitdir, &list))
4378 return -1;
4380 for_each_string_list_item(item, &list) {
4381 if (!strcmp(item->string, refname)) {
4382 struct update_ref_record *rec = item->util;
4383 if (read_ref("HEAD", &rec->after))
4384 return -1;
4385 break;
4389 write_update_refs_state(&list);
4390 string_list_clear(&list, 1);
4391 return 0;
4394 static int do_update_refs(struct repository *r, int quiet)
4396 int res = 0;
4397 struct string_list_item *item;
4398 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4399 struct ref_store *refs = get_main_ref_store(r);
4400 struct strbuf update_msg = STRBUF_INIT;
4401 struct strbuf error_msg = STRBUF_INIT;
4403 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4404 return res;
4406 for_each_string_list_item(item, &refs_to_oids) {
4407 struct update_ref_record *rec = item->util;
4408 int loop_res;
4410 loop_res = refs_update_ref(refs, "rewritten during rebase",
4411 item->string,
4412 &rec->after, &rec->before,
4413 0, UPDATE_REFS_MSG_ON_ERR);
4414 res |= loop_res;
4416 if (quiet)
4417 continue;
4419 if (loop_res)
4420 strbuf_addf(&error_msg, "\t%s\n", item->string);
4421 else
4422 strbuf_addf(&update_msg, "\t%s\n", item->string);
4425 if (!quiet &&
4426 (update_msg.len || error_msg.len)) {
4427 fprintf(stderr,
4428 _("Updated the following refs with %s:\n%s"),
4429 "--update-refs",
4430 update_msg.buf);
4432 if (res)
4433 fprintf(stderr,
4434 _("Failed to update the following refs with %s:\n%s"),
4435 "--update-refs",
4436 error_msg.buf);
4439 string_list_clear(&refs_to_oids, 1);
4440 strbuf_release(&update_msg);
4441 strbuf_release(&error_msg);
4442 return res;
4445 static int is_final_fixup(struct todo_list *todo_list)
4447 int i = todo_list->current;
4449 if (!is_fixup(todo_list->items[i].command))
4450 return 0;
4452 while (++i < todo_list->nr)
4453 if (is_fixup(todo_list->items[i].command))
4454 return 0;
4455 else if (!is_noop(todo_list->items[i].command))
4456 break;
4457 return 1;
4460 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4462 int i;
4464 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4465 if (!is_noop(todo_list->items[i].command))
4466 return todo_list->items[i].command;
4468 return -1;
4471 static void create_autostash_internal(struct repository *r,
4472 const char *path,
4473 const char *refname)
4475 struct strbuf buf = STRBUF_INIT;
4476 struct lock_file lock_file = LOCK_INIT;
4477 int fd;
4479 if (path && refname)
4480 BUG("can only pass path or refname");
4482 fd = repo_hold_locked_index(r, &lock_file, 0);
4483 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4484 if (0 <= fd)
4485 repo_update_index_if_able(r, &lock_file);
4486 rollback_lock_file(&lock_file);
4488 if (has_unstaged_changes(r, 1) ||
4489 has_uncommitted_changes(r, 1)) {
4490 struct child_process stash = CHILD_PROCESS_INIT;
4491 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4492 struct object_id oid;
4494 strvec_pushl(&stash.args,
4495 "stash", "create", "autostash", NULL);
4496 stash.git_cmd = 1;
4497 stash.no_stdin = 1;
4498 strbuf_reset(&buf);
4499 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4500 die(_("Cannot autostash"));
4501 strbuf_trim_trailing_newline(&buf);
4502 if (repo_get_oid(r, buf.buf, &oid))
4503 die(_("Unexpected stash response: '%s'"),
4504 buf.buf);
4505 strbuf_reset(&buf);
4506 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4508 if (path) {
4509 if (safe_create_leading_directories_const(path))
4510 die(_("Could not create directory for '%s'"),
4511 path);
4512 write_file(path, "%s", oid_to_hex(&oid));
4513 } else {
4514 refs_update_ref(get_main_ref_store(r), "", refname,
4515 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4518 printf(_("Created autostash: %s\n"), buf.buf);
4519 if (reset_head(r, &ropts) < 0)
4520 die(_("could not reset --hard"));
4521 discard_index(r->index);
4522 if (repo_read_index(r) < 0)
4523 die(_("could not read index"));
4525 strbuf_release(&buf);
4528 void create_autostash(struct repository *r, const char *path)
4530 create_autostash_internal(r, path, NULL);
4533 void create_autostash_ref(struct repository *r, const char *refname)
4535 create_autostash_internal(r, NULL, refname);
4538 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4540 struct child_process child = CHILD_PROCESS_INIT;
4541 int ret = 0;
4543 if (attempt_apply) {
4544 child.git_cmd = 1;
4545 child.no_stdout = 1;
4546 child.no_stderr = 1;
4547 strvec_push(&child.args, "stash");
4548 strvec_push(&child.args, "apply");
4549 strvec_push(&child.args, stash_oid);
4550 ret = run_command(&child);
4553 if (attempt_apply && !ret)
4554 fprintf(stderr, _("Applied autostash.\n"));
4555 else {
4556 struct child_process store = CHILD_PROCESS_INIT;
4558 store.git_cmd = 1;
4559 strvec_push(&store.args, "stash");
4560 strvec_push(&store.args, "store");
4561 strvec_push(&store.args, "-m");
4562 strvec_push(&store.args, "autostash");
4563 strvec_push(&store.args, "-q");
4564 strvec_push(&store.args, stash_oid);
4565 if (run_command(&store))
4566 ret = error(_("cannot store %s"), stash_oid);
4567 else
4568 fprintf(stderr,
4569 _("%s\n"
4570 "Your changes are safe in the stash.\n"
4571 "You can run \"git stash pop\" or"
4572 " \"git stash drop\" at any time.\n"),
4573 attempt_apply ?
4574 _("Applying autostash resulted in conflicts.") :
4575 _("Autostash exists; creating a new stash entry."));
4578 return ret;
4581 static int apply_save_autostash(const char *path, int attempt_apply)
4583 struct strbuf stash_oid = STRBUF_INIT;
4584 int ret = 0;
4586 if (!read_oneliner(&stash_oid, path,
4587 READ_ONELINER_SKIP_IF_EMPTY)) {
4588 strbuf_release(&stash_oid);
4589 return 0;
4591 strbuf_trim(&stash_oid);
4593 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4595 unlink(path);
4596 strbuf_release(&stash_oid);
4597 return ret;
4600 int save_autostash(const char *path)
4602 return apply_save_autostash(path, 0);
4605 int apply_autostash(const char *path)
4607 return apply_save_autostash(path, 1);
4610 int apply_autostash_oid(const char *stash_oid)
4612 return apply_save_autostash_oid(stash_oid, 1);
4615 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4616 int attempt_apply)
4618 struct object_id stash_oid;
4619 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4620 int flag, ret;
4622 if (!refs_ref_exists(get_main_ref_store(r), refname))
4623 return 0;
4625 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4626 RESOLVE_REF_READING, &stash_oid, &flag))
4627 return -1;
4628 if (flag & REF_ISSYMREF)
4629 return error(_("autostash reference is a symref"));
4631 oid_to_hex_r(stash_oid_hex, &stash_oid);
4632 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4634 refs_delete_ref(get_main_ref_store(r), "", refname,
4635 &stash_oid, REF_NO_DEREF);
4637 return ret;
4640 int save_autostash_ref(struct repository *r, const char *refname)
4642 return apply_save_autostash_ref(r, refname, 0);
4645 int apply_autostash_ref(struct repository *r, const char *refname)
4647 return apply_save_autostash_ref(r, refname, 1);
4650 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4651 const char *onto_name, const struct object_id *onto,
4652 const struct object_id *orig_head)
4654 struct reset_head_opts ropts = {
4655 .oid = onto,
4656 .orig_head = orig_head,
4657 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4658 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4659 .head_msg = reflog_message(opts, "start", "checkout %s",
4660 onto_name),
4661 .default_reflog_action = sequencer_reflog_action(opts)
4663 if (reset_head(r, &ropts)) {
4664 apply_autostash(rebase_path_autostash());
4665 sequencer_remove_state(opts);
4666 return error(_("could not detach HEAD"));
4669 return 0;
4672 static int stopped_at_head(struct repository *r)
4674 struct object_id head;
4675 struct commit *commit;
4676 struct commit_message message;
4678 if (repo_get_oid(r, "HEAD", &head) ||
4679 !(commit = lookup_commit(r, &head)) ||
4680 repo_parse_commit(r, commit) || get_message(commit, &message))
4681 fprintf(stderr, _("Stopped at HEAD\n"));
4682 else {
4683 fprintf(stderr, _("Stopped at %s\n"), message.label);
4684 free_message(commit, &message);
4686 return 0;
4690 static int reread_todo_if_changed(struct repository *r,
4691 struct todo_list *todo_list,
4692 struct replay_opts *opts)
4694 int offset;
4695 struct strbuf buf = STRBUF_INIT;
4697 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4698 return -1;
4699 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4700 if (buf.len != todo_list->buf.len - offset ||
4701 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4702 /* Reread the todo file if it has changed. */
4703 todo_list_release(todo_list);
4704 if (read_populate_todo(r, todo_list, opts))
4705 return -1; /* message was printed */
4706 /* `current` will be incremented on return */
4707 todo_list->current = -1;
4709 strbuf_release(&buf);
4711 return 0;
4714 static const char rescheduled_advice[] =
4715 N_("Could not execute the todo command\n"
4716 "\n"
4717 " %.*s"
4718 "\n"
4719 "It has been rescheduled; To edit the command before continuing, please\n"
4720 "edit the todo list first:\n"
4721 "\n"
4722 " git rebase --edit-todo\n"
4723 " git rebase --continue\n");
4725 static int pick_one_commit(struct repository *r,
4726 struct todo_list *todo_list,
4727 struct replay_opts *opts,
4728 int *check_todo, int* reschedule)
4730 int res;
4731 struct todo_item *item = todo_list->items + todo_list->current;
4732 const char *arg = todo_item_get_arg(todo_list, item);
4733 if (is_rebase_i(opts))
4734 opts->reflog_message = reflog_message(
4735 opts, command_to_string(item->command), NULL);
4737 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4738 check_todo);
4739 if (is_rebase_i(opts) && res < 0) {
4740 /* Reschedule */
4741 *reschedule = 1;
4742 return -1;
4744 if (item->command == TODO_EDIT) {
4745 struct commit *commit = item->commit;
4746 if (!res) {
4747 if (!opts->verbose)
4748 term_clear_line();
4749 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4750 short_commit_name(r, commit), item->arg_len, arg);
4752 return error_with_patch(r, commit,
4753 arg, item->arg_len, opts, res, !res);
4755 if (is_rebase_i(opts) && !res)
4756 record_in_rewritten(&item->commit->object.oid,
4757 peek_command(todo_list, 1));
4758 if (res && is_fixup(item->command)) {
4759 if (res == 1)
4760 intend_to_amend();
4761 return error_failed_squash(r, item->commit, opts,
4762 item->arg_len, arg);
4763 } else if (res && is_rebase_i(opts) && item->commit) {
4764 int to_amend = 0;
4765 struct object_id oid;
4768 * If we are rewording and have either
4769 * fast-forwarded already, or are about to
4770 * create a new root commit, we want to amend,
4771 * otherwise we do not.
4773 if (item->command == TODO_REWORD &&
4774 !repo_get_oid(r, "HEAD", &oid) &&
4775 (oideq(&item->commit->object.oid, &oid) ||
4776 (opts->have_squash_onto &&
4777 oideq(&opts->squash_onto, &oid))))
4778 to_amend = 1;
4780 return res | error_with_patch(r, item->commit,
4781 arg, item->arg_len, opts,
4782 res, to_amend);
4784 return res;
4787 static int pick_commits(struct repository *r,
4788 struct todo_list *todo_list,
4789 struct replay_opts *opts)
4791 int res = 0, reschedule = 0;
4793 opts->reflog_message = sequencer_reflog_action(opts);
4794 if (opts->allow_ff)
4795 assert(!(opts->signoff || opts->no_commit ||
4796 opts->record_origin || should_edit(opts) ||
4797 opts->committer_date_is_author_date ||
4798 opts->ignore_date));
4799 if (read_and_refresh_cache(r, opts))
4800 return -1;
4802 unlink(rebase_path_message());
4803 unlink(rebase_path_stopped_sha());
4804 unlink(rebase_path_amend());
4805 unlink(rebase_path_patch());
4807 while (todo_list->current < todo_list->nr) {
4808 struct todo_item *item = todo_list->items + todo_list->current;
4809 const char *arg = todo_item_get_arg(todo_list, item);
4810 int check_todo = 0;
4812 if (save_todo(todo_list, opts, reschedule))
4813 return -1;
4814 if (is_rebase_i(opts)) {
4815 if (item->command != TODO_COMMENT) {
4816 FILE *f = fopen(rebase_path_msgnum(), "w");
4818 todo_list->done_nr++;
4820 if (f) {
4821 fprintf(f, "%d\n", todo_list->done_nr);
4822 fclose(f);
4824 if (!opts->quiet)
4825 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4826 todo_list->done_nr,
4827 todo_list->total_nr,
4828 opts->verbose ? "\n" : "\r");
4830 unlink(rebase_path_author_script());
4831 unlink(git_path_merge_head(r));
4832 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4833 NULL, REF_NO_DEREF);
4834 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4835 NULL, REF_NO_DEREF);
4837 if (item->command == TODO_BREAK) {
4838 if (!opts->verbose)
4839 term_clear_line();
4840 return stopped_at_head(r);
4843 if (item->command <= TODO_SQUASH) {
4844 res = pick_one_commit(r, todo_list, opts, &check_todo,
4845 &reschedule);
4846 if (!res && item->command == TODO_EDIT)
4847 return 0;
4848 } else if (item->command == TODO_EXEC) {
4849 char *end_of_arg = (char *)(arg + item->arg_len);
4850 int saved = *end_of_arg;
4852 if (!opts->verbose)
4853 term_clear_line();
4854 *end_of_arg = '\0';
4855 res = do_exec(r, arg);
4856 *end_of_arg = saved;
4858 if (res) {
4859 if (opts->reschedule_failed_exec)
4860 reschedule = 1;
4862 check_todo = 1;
4863 } else if (item->command == TODO_LABEL) {
4864 if ((res = do_label(r, arg, item->arg_len)))
4865 reschedule = 1;
4866 } else if (item->command == TODO_RESET) {
4867 if ((res = do_reset(r, arg, item->arg_len, opts)))
4868 reschedule = 1;
4869 } else if (item->command == TODO_MERGE) {
4870 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4871 item->flags, &check_todo, opts)) < 0)
4872 reschedule = 1;
4873 else if (item->commit)
4874 record_in_rewritten(&item->commit->object.oid,
4875 peek_command(todo_list, 1));
4876 if (res > 0)
4877 /* failed with merge conflicts */
4878 return error_with_patch(r, item->commit,
4879 arg, item->arg_len,
4880 opts, res, 0);
4881 } else if (item->command == TODO_UPDATE_REF) {
4882 struct strbuf ref = STRBUF_INIT;
4883 strbuf_add(&ref, arg, item->arg_len);
4884 if ((res = do_update_ref(r, ref.buf)))
4885 reschedule = 1;
4886 strbuf_release(&ref);
4887 } else if (!is_noop(item->command))
4888 return error(_("unknown command %d"), item->command);
4890 if (reschedule) {
4891 advise(_(rescheduled_advice),
4892 get_item_line_length(todo_list,
4893 todo_list->current),
4894 get_item_line(todo_list, todo_list->current));
4895 if (save_todo(todo_list, opts, reschedule))
4896 return -1;
4897 if (item->commit)
4898 write_rebase_head(&item->commit->object.oid);
4899 } else if (is_rebase_i(opts) && check_todo && !res &&
4900 reread_todo_if_changed(r, todo_list, opts)) {
4901 return -1;
4904 if (res)
4905 return res;
4907 todo_list->current++;
4910 if (is_rebase_i(opts)) {
4911 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4912 struct stat st;
4914 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4915 starts_with(head_ref.buf, "refs/")) {
4916 const char *msg;
4917 struct object_id head, orig;
4918 int res;
4920 if (repo_get_oid(r, "HEAD", &head)) {
4921 res = error(_("cannot read HEAD"));
4922 cleanup_head_ref:
4923 strbuf_release(&head_ref);
4924 strbuf_release(&buf);
4925 return res;
4927 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4928 get_oid_hex(buf.buf, &orig)) {
4929 res = error(_("could not read orig-head"));
4930 goto cleanup_head_ref;
4932 strbuf_reset(&buf);
4933 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4934 res = error(_("could not read 'onto'"));
4935 goto cleanup_head_ref;
4937 msg = reflog_message(opts, "finish", "%s onto %s",
4938 head_ref.buf, buf.buf);
4939 if (update_ref(msg, head_ref.buf, &head, &orig,
4940 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4941 res = error(_("could not update %s"),
4942 head_ref.buf);
4943 goto cleanup_head_ref;
4945 msg = reflog_message(opts, "finish", "returning to %s",
4946 head_ref.buf);
4947 if (create_symref("HEAD", head_ref.buf, msg)) {
4948 res = error(_("could not update HEAD to %s"),
4949 head_ref.buf);
4950 goto cleanup_head_ref;
4952 strbuf_reset(&buf);
4955 if (opts->verbose) {
4956 struct rev_info log_tree_opt;
4957 struct object_id orig, head;
4959 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4960 repo_init_revisions(r, &log_tree_opt, NULL);
4961 log_tree_opt.diff = 1;
4962 log_tree_opt.diffopt.output_format =
4963 DIFF_FORMAT_DIFFSTAT;
4964 log_tree_opt.disable_stdin = 1;
4966 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4967 !repo_get_oid(r, buf.buf, &orig) &&
4968 !repo_get_oid(r, "HEAD", &head)) {
4969 diff_tree_oid(&orig, &head, "",
4970 &log_tree_opt.diffopt);
4971 log_tree_diff_flush(&log_tree_opt);
4973 release_revisions(&log_tree_opt);
4975 flush_rewritten_pending();
4976 if (!stat(rebase_path_rewritten_list(), &st) &&
4977 st.st_size > 0) {
4978 struct child_process child = CHILD_PROCESS_INIT;
4979 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4981 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4982 child.git_cmd = 1;
4983 strvec_push(&child.args, "notes");
4984 strvec_push(&child.args, "copy");
4985 strvec_push(&child.args, "--for-rewrite=rebase");
4986 /* we don't care if this copying failed */
4987 run_command(&child);
4989 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4990 strvec_push(&hook_opt.args, "rebase");
4991 run_hooks_opt("post-rewrite", &hook_opt);
4993 apply_autostash(rebase_path_autostash());
4995 if (!opts->quiet) {
4996 if (!opts->verbose)
4997 term_clear_line();
4998 fprintf(stderr,
4999 _("Successfully rebased and updated %s.\n"),
5000 head_ref.buf);
5003 strbuf_release(&buf);
5004 strbuf_release(&head_ref);
5006 if (do_update_refs(r, opts->quiet))
5007 return -1;
5011 * Sequence of picks finished successfully; cleanup by
5012 * removing the .git/sequencer directory
5014 return sequencer_remove_state(opts);
5017 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5019 struct child_process cmd = CHILD_PROCESS_INIT;
5021 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5022 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5023 return error(_("no cherry-pick or revert in progress"));
5025 cmd.git_cmd = 1;
5026 strvec_push(&cmd.args, "commit");
5029 * continue_single_pick() handles the case of recovering from a
5030 * conflict. should_edit() doesn't handle that case; for a conflict,
5031 * we want to edit if the user asked for it, or if they didn't specify
5032 * and stdin is a tty.
5034 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5036 * Include --cleanup=strip as well because we don't want the
5037 * "# Conflicts:" messages.
5039 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5041 return run_command(&cmd);
5044 static int commit_staged_changes(struct repository *r,
5045 struct replay_opts *opts,
5046 struct todo_list *todo_list)
5048 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5049 unsigned int final_fixup = 0, is_clean;
5051 if (has_unstaged_changes(r, 1))
5052 return error(_("cannot rebase: You have unstaged changes."));
5054 is_clean = !has_uncommitted_changes(r, 0);
5056 if (!is_clean && !file_exists(rebase_path_message())) {
5057 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5059 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5061 if (file_exists(rebase_path_amend())) {
5062 struct strbuf rev = STRBUF_INIT;
5063 struct object_id head, to_amend;
5065 if (repo_get_oid(r, "HEAD", &head))
5066 return error(_("cannot amend non-existing commit"));
5067 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5068 return error(_("invalid file: '%s'"), rebase_path_amend());
5069 if (get_oid_hex(rev.buf, &to_amend))
5070 return error(_("invalid contents: '%s'"),
5071 rebase_path_amend());
5072 if (!is_clean && !oideq(&head, &to_amend))
5073 return error(_("\nYou have uncommitted changes in your "
5074 "working tree. Please, commit them\n"
5075 "first and then run 'git rebase "
5076 "--continue' again."));
5078 * When skipping a failed fixup/squash, we need to edit the
5079 * commit message, the current fixup list and count, and if it
5080 * was the last fixup/squash in the chain, we need to clean up
5081 * the commit message and if there was a squash, let the user
5082 * edit it.
5084 if (!is_clean || !opts->current_fixup_count)
5085 ; /* this is not the final fixup */
5086 else if (!oideq(&head, &to_amend) ||
5087 !file_exists(rebase_path_stopped_sha())) {
5088 /* was a final fixup or squash done manually? */
5089 if (!is_fixup(peek_command(todo_list, 0))) {
5090 unlink(rebase_path_fixup_msg());
5091 unlink(rebase_path_squash_msg());
5092 unlink(rebase_path_current_fixups());
5093 strbuf_reset(&opts->current_fixups);
5094 opts->current_fixup_count = 0;
5096 } else {
5097 /* we are in a fixup/squash chain */
5098 const char *p = opts->current_fixups.buf;
5099 int len = opts->current_fixups.len;
5101 opts->current_fixup_count--;
5102 if (!len)
5103 BUG("Incorrect current_fixups:\n%s", p);
5104 while (len && p[len - 1] != '\n')
5105 len--;
5106 strbuf_setlen(&opts->current_fixups, len);
5107 if (write_message(p, len, rebase_path_current_fixups(),
5108 0) < 0)
5109 return error(_("could not write file: '%s'"),
5110 rebase_path_current_fixups());
5113 * If a fixup/squash in a fixup/squash chain failed, the
5114 * commit message is already correct, no need to commit
5115 * it again.
5117 * Only if it is the final command in the fixup/squash
5118 * chain, and only if the chain is longer than a single
5119 * fixup/squash command (which was just skipped), do we
5120 * actually need to re-commit with a cleaned up commit
5121 * message.
5123 if (opts->current_fixup_count > 0 &&
5124 !is_fixup(peek_command(todo_list, 0))) {
5125 final_fixup = 1;
5127 * If there was not a single "squash" in the
5128 * chain, we only need to clean up the commit
5129 * message, no need to bother the user with
5130 * opening the commit message in the editor.
5132 if (!starts_with(p, "squash ") &&
5133 !strstr(p, "\nsquash "))
5134 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5135 } else if (is_fixup(peek_command(todo_list, 0))) {
5137 * We need to update the squash message to skip
5138 * the latest commit message.
5140 int res = 0;
5141 struct commit *commit;
5142 const char *msg;
5143 const char *path = rebase_path_squash_msg();
5144 const char *encoding = get_commit_output_encoding();
5146 if (parse_head(r, &commit))
5147 return error(_("could not parse HEAD"));
5149 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5150 if (!p) {
5151 res = error(_("could not parse commit %s"),
5152 oid_to_hex(&commit->object.oid));
5153 goto unuse_commit_buffer;
5155 find_commit_subject(p, &msg);
5156 if (write_message(msg, strlen(msg), path, 0)) {
5157 res = error(_("could not write file: "
5158 "'%s'"), path);
5159 goto unuse_commit_buffer;
5161 unuse_commit_buffer:
5162 repo_unuse_commit_buffer(r, commit, p);
5163 if (res)
5164 return res;
5168 strbuf_release(&rev);
5169 flags |= AMEND_MSG;
5172 if (is_clean) {
5173 if (refs_ref_exists(get_main_ref_store(r),
5174 "CHERRY_PICK_HEAD") &&
5175 refs_delete_ref(get_main_ref_store(r), "",
5176 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5177 return error(_("could not remove CHERRY_PICK_HEAD"));
5178 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5179 return error_errno(_("could not remove '%s'"),
5180 git_path_merge_msg(r));
5181 if (!final_fixup)
5182 return 0;
5185 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5186 opts, flags))
5187 return error(_("could not commit staged changes."));
5188 unlink(rebase_path_amend());
5189 unlink(git_path_merge_head(r));
5190 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5191 NULL, REF_NO_DEREF);
5192 if (final_fixup) {
5193 unlink(rebase_path_fixup_msg());
5194 unlink(rebase_path_squash_msg());
5196 if (opts->current_fixup_count > 0) {
5198 * Whether final fixup or not, we just cleaned up the commit
5199 * message...
5201 unlink(rebase_path_current_fixups());
5202 strbuf_reset(&opts->current_fixups);
5203 opts->current_fixup_count = 0;
5205 return 0;
5208 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5210 struct todo_list todo_list = TODO_LIST_INIT;
5211 int res;
5213 if (read_and_refresh_cache(r, opts))
5214 return -1;
5216 if (read_populate_opts(opts))
5217 return -1;
5218 if (is_rebase_i(opts)) {
5219 if ((res = read_populate_todo(r, &todo_list, opts)))
5220 goto release_todo_list;
5222 if (file_exists(rebase_path_dropped())) {
5223 if ((res = todo_list_check_against_backup(r, &todo_list)))
5224 goto release_todo_list;
5226 unlink(rebase_path_dropped());
5229 opts->reflog_message = reflog_message(opts, "continue", NULL);
5230 if (commit_staged_changes(r, opts, &todo_list)) {
5231 res = -1;
5232 goto release_todo_list;
5234 } else if (!file_exists(get_todo_path(opts)))
5235 return continue_single_pick(r, opts);
5236 else if ((res = read_populate_todo(r, &todo_list, opts)))
5237 goto release_todo_list;
5239 if (!is_rebase_i(opts)) {
5240 /* Verify that the conflict has been resolved */
5241 if (refs_ref_exists(get_main_ref_store(r),
5242 "CHERRY_PICK_HEAD") ||
5243 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5244 res = continue_single_pick(r, opts);
5245 if (res)
5246 goto release_todo_list;
5248 if (index_differs_from(r, "HEAD", NULL, 0)) {
5249 res = error_dirty_index(r, opts);
5250 goto release_todo_list;
5252 todo_list.current++;
5253 } else if (file_exists(rebase_path_stopped_sha())) {
5254 struct strbuf buf = STRBUF_INIT;
5255 struct object_id oid;
5257 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5258 READ_ONELINER_SKIP_IF_EMPTY) &&
5259 !get_oid_hex(buf.buf, &oid))
5260 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5261 strbuf_release(&buf);
5264 res = pick_commits(r, &todo_list, opts);
5265 release_todo_list:
5266 todo_list_release(&todo_list);
5267 return res;
5270 static int single_pick(struct repository *r,
5271 struct commit *cmit,
5272 struct replay_opts *opts)
5274 int check_todo;
5275 struct todo_item item;
5277 item.command = opts->action == REPLAY_PICK ?
5278 TODO_PICK : TODO_REVERT;
5279 item.commit = cmit;
5281 opts->reflog_message = sequencer_reflog_action(opts);
5282 return do_pick_commit(r, &item, opts, 0, &check_todo);
5285 int sequencer_pick_revisions(struct repository *r,
5286 struct replay_opts *opts)
5288 struct todo_list todo_list = TODO_LIST_INIT;
5289 struct object_id oid;
5290 int i, res;
5292 assert(opts->revs);
5293 if (read_and_refresh_cache(r, opts))
5294 return -1;
5296 for (i = 0; i < opts->revs->pending.nr; i++) {
5297 struct object_id oid;
5298 const char *name = opts->revs->pending.objects[i].name;
5300 /* This happens when using --stdin. */
5301 if (!strlen(name))
5302 continue;
5304 if (!repo_get_oid(r, name, &oid)) {
5305 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5306 enum object_type type = oid_object_info(r,
5307 &oid,
5308 NULL);
5309 return error(_("%s: can't cherry-pick a %s"),
5310 name, type_name(type));
5312 } else
5313 return error(_("%s: bad revision"), name);
5317 * If we were called as "git cherry-pick <commit>", just
5318 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5319 * REVERT_HEAD, and don't touch the sequencer state.
5320 * This means it is possible to cherry-pick in the middle
5321 * of a cherry-pick sequence.
5323 if (opts->revs->cmdline.nr == 1 &&
5324 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5325 opts->revs->no_walk &&
5326 !opts->revs->cmdline.rev->flags) {
5327 struct commit *cmit;
5328 if (prepare_revision_walk(opts->revs))
5329 return error(_("revision walk setup failed"));
5330 cmit = get_revision(opts->revs);
5331 if (!cmit)
5332 return error(_("empty commit set passed"));
5333 if (get_revision(opts->revs))
5334 BUG("unexpected extra commit from walk");
5335 return single_pick(r, cmit, opts);
5339 * Start a new cherry-pick/ revert sequence; but
5340 * first, make sure that an existing one isn't in
5341 * progress
5344 if (walk_revs_populate_todo(&todo_list, opts) ||
5345 create_seq_dir(r) < 0)
5346 return -1;
5347 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5348 return error(_("can't revert as initial commit"));
5349 if (save_head(oid_to_hex(&oid)))
5350 return -1;
5351 if (save_opts(opts))
5352 return -1;
5353 update_abort_safety_file();
5354 res = pick_commits(r, &todo_list, opts);
5355 todo_list_release(&todo_list);
5356 return res;
5359 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5361 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5362 struct strbuf sob = STRBUF_INIT;
5363 int has_footer;
5365 strbuf_addstr(&sob, sign_off_header);
5366 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5367 strbuf_addch(&sob, '\n');
5369 if (!ignore_footer)
5370 strbuf_complete_line(msgbuf);
5373 * If the whole message buffer is equal to the sob, pretend that we
5374 * found a conforming footer with a matching sob
5376 if (msgbuf->len - ignore_footer == sob.len &&
5377 !strncmp(msgbuf->buf, sob.buf, sob.len))
5378 has_footer = 3;
5379 else
5380 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5382 if (!has_footer) {
5383 const char *append_newlines = NULL;
5384 size_t len = msgbuf->len - ignore_footer;
5386 if (!len) {
5388 * The buffer is completely empty. Leave foom for
5389 * the title and body to be filled in by the user.
5391 append_newlines = "\n\n";
5392 } else if (len == 1) {
5394 * Buffer contains a single newline. Add another
5395 * so that we leave room for the title and body.
5397 append_newlines = "\n";
5398 } else if (msgbuf->buf[len - 2] != '\n') {
5400 * Buffer ends with a single newline. Add another
5401 * so that there is an empty line between the message
5402 * body and the sob.
5404 append_newlines = "\n";
5405 } /* else, the buffer already ends with two newlines. */
5407 if (append_newlines)
5408 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5409 append_newlines, strlen(append_newlines));
5412 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5413 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5414 sob.buf, sob.len);
5416 strbuf_release(&sob);
5419 struct labels_entry {
5420 struct hashmap_entry entry;
5421 char label[FLEX_ARRAY];
5424 static int labels_cmp(const void *fndata UNUSED,
5425 const struct hashmap_entry *eptr,
5426 const struct hashmap_entry *entry_or_key, const void *key)
5428 const struct labels_entry *a, *b;
5430 a = container_of(eptr, const struct labels_entry, entry);
5431 b = container_of(entry_or_key, const struct labels_entry, entry);
5433 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5436 struct string_entry {
5437 struct oidmap_entry entry;
5438 char string[FLEX_ARRAY];
5441 struct label_state {
5442 struct oidmap commit2label;
5443 struct hashmap labels;
5444 struct strbuf buf;
5445 int max_label_length;
5448 static const char *label_oid(struct object_id *oid, const char *label,
5449 struct label_state *state)
5451 struct labels_entry *labels_entry;
5452 struct string_entry *string_entry;
5453 struct object_id dummy;
5454 int i;
5456 string_entry = oidmap_get(&state->commit2label, oid);
5457 if (string_entry)
5458 return string_entry->string;
5461 * For "uninteresting" commits, i.e. commits that are not to be
5462 * rebased, and which can therefore not be labeled, we use a unique
5463 * abbreviation of the commit name. This is slightly more complicated
5464 * than calling repo_find_unique_abbrev() because we also need to make
5465 * sure that the abbreviation does not conflict with any other
5466 * label.
5468 * We disallow "interesting" commits to be labeled by a string that
5469 * is a valid full-length hash, to ensure that we always can find an
5470 * abbreviation for any uninteresting commit's names that does not
5471 * clash with any other label.
5473 strbuf_reset(&state->buf);
5474 if (!label) {
5475 char *p;
5477 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5478 label = p = state->buf.buf;
5480 repo_find_unique_abbrev_r(the_repository, p, oid,
5481 default_abbrev);
5484 * We may need to extend the abbreviated hash so that there is
5485 * no conflicting label.
5487 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5488 size_t i = strlen(p) + 1;
5490 oid_to_hex_r(p, oid);
5491 for (; i < the_hash_algo->hexsz; i++) {
5492 char save = p[i];
5493 p[i] = '\0';
5494 if (!hashmap_get_from_hash(&state->labels,
5495 strihash(p), p))
5496 break;
5497 p[i] = save;
5500 } else {
5501 struct strbuf *buf = &state->buf;
5502 int label_is_utf8 = 1; /* start with this assumption */
5503 size_t max_len = buf->len + state->max_label_length;
5506 * Sanitize labels by replacing non-alpha-numeric characters
5507 * (including white-space ones) by dashes, as they might be
5508 * illegal in file names (and hence in ref names).
5510 * Note that we retain non-ASCII UTF-8 characters (identified
5511 * via the most significant bit). They should be all acceptable
5512 * in file names.
5514 * As we will use the labels as names of (loose) refs, it is
5515 * vital that the name not be longer than the maximum component
5516 * size of the file system (`NAME_MAX`). We are careful to
5517 * truncate the label accordingly, allowing for the `.lock`
5518 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5519 * truncating in the middle of a character).
5521 for (; *label && buf->len + 1 < max_len; label++)
5522 if (isalnum(*label) ||
5523 (!label_is_utf8 && (*label & 0x80)))
5524 strbuf_addch(buf, *label);
5525 else if (*label & 0x80) {
5526 const char *p = label;
5528 utf8_width(&p, NULL);
5529 if (p) {
5530 if (buf->len + (p - label) > max_len)
5531 break;
5532 strbuf_add(buf, label, p - label);
5533 label = p - 1;
5534 } else {
5535 label_is_utf8 = 0;
5536 strbuf_addch(buf, *label);
5538 /* avoid leading dash and double-dashes */
5539 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5540 strbuf_addch(buf, '-');
5541 if (!buf->len) {
5542 strbuf_addstr(buf, "rev-");
5543 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5545 label = buf->buf;
5547 if ((buf->len == the_hash_algo->hexsz &&
5548 !get_oid_hex(label, &dummy)) ||
5549 (buf->len == 1 && *label == '#') ||
5550 hashmap_get_from_hash(&state->labels,
5551 strihash(label), label)) {
5553 * If the label already exists, or if the label is a
5554 * valid full OID, or the label is a '#' (which we use
5555 * as a separator between merge heads and oneline), we
5556 * append a dash and a number to make it unique.
5558 size_t len = buf->len;
5560 for (i = 2; ; i++) {
5561 strbuf_setlen(buf, len);
5562 strbuf_addf(buf, "-%d", i);
5563 if (!hashmap_get_from_hash(&state->labels,
5564 strihash(buf->buf),
5565 buf->buf))
5566 break;
5569 label = buf->buf;
5573 FLEX_ALLOC_STR(labels_entry, label, label);
5574 hashmap_entry_init(&labels_entry->entry, strihash(label));
5575 hashmap_add(&state->labels, &labels_entry->entry);
5577 FLEX_ALLOC_STR(string_entry, string, label);
5578 oidcpy(&string_entry->entry.oid, oid);
5579 oidmap_put(&state->commit2label, string_entry);
5581 return string_entry->string;
5584 static int make_script_with_merges(struct pretty_print_context *pp,
5585 struct rev_info *revs, struct strbuf *out,
5586 unsigned flags)
5588 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5589 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5590 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5591 int skipped_commit = 0;
5592 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5593 struct strbuf label = STRBUF_INIT;
5594 struct commit_list *commits = NULL, **tail = &commits, *iter;
5595 struct commit_list *tips = NULL, **tips_tail = &tips;
5596 struct commit *commit;
5597 struct oidmap commit2todo = OIDMAP_INIT;
5598 struct string_entry *entry;
5599 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5600 shown = OIDSET_INIT;
5601 struct label_state state =
5602 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5604 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5605 const char *cmd_pick = abbr ? "p" : "pick",
5606 *cmd_label = abbr ? "l" : "label",
5607 *cmd_reset = abbr ? "t" : "reset",
5608 *cmd_merge = abbr ? "m" : "merge";
5610 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5612 oidmap_init(&commit2todo, 0);
5613 oidmap_init(&state.commit2label, 0);
5614 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5615 strbuf_init(&state.buf, 32);
5617 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5618 struct labels_entry *onto_label_entry;
5619 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5620 FLEX_ALLOC_STR(entry, string, "onto");
5621 oidcpy(&entry->entry.oid, oid);
5622 oidmap_put(&state.commit2label, entry);
5624 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5625 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5626 hashmap_add(&state.labels, &onto_label_entry->entry);
5630 * First phase:
5631 * - get onelines for all commits
5632 * - gather all branch tips (i.e. 2nd or later parents of merges)
5633 * - label all branch tips
5635 while ((commit = get_revision(revs))) {
5636 struct commit_list *to_merge;
5637 const char *p1, *p2;
5638 struct object_id *oid;
5639 int is_empty;
5641 tail = &commit_list_insert(commit, tail)->next;
5642 oidset_insert(&interesting, &commit->object.oid);
5644 is_empty = is_original_commit_empty(commit);
5645 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5646 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5647 warning(_("skipped previously applied commit %s"),
5648 short_commit_name(the_repository, commit));
5649 skipped_commit = 1;
5650 continue;
5652 if (is_empty && !keep_empty)
5653 continue;
5655 strbuf_reset(&oneline);
5656 pretty_print_commit(pp, commit, &oneline);
5658 to_merge = commit->parents ? commit->parents->next : NULL;
5659 if (!to_merge) {
5660 /* non-merge commit: easy case */
5661 strbuf_reset(&buf);
5662 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5663 oid_to_hex(&commit->object.oid),
5664 oneline.buf);
5665 if (is_empty)
5666 strbuf_addf(&buf, " %c empty",
5667 comment_line_char);
5669 FLEX_ALLOC_STR(entry, string, buf.buf);
5670 oidcpy(&entry->entry.oid, &commit->object.oid);
5671 oidmap_put(&commit2todo, entry);
5673 continue;
5676 /* Create a label */
5677 strbuf_reset(&label);
5678 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5679 (p1 = strchr(p1, '\'')) &&
5680 (p2 = strchr(++p1, '\'')))
5681 strbuf_add(&label, p1, p2 - p1);
5682 else if (skip_prefix(oneline.buf, "Merge pull request ",
5683 &p1) &&
5684 (p1 = strstr(p1, " from ")))
5685 strbuf_addstr(&label, p1 + strlen(" from "));
5686 else
5687 strbuf_addbuf(&label, &oneline);
5689 strbuf_reset(&buf);
5690 strbuf_addf(&buf, "%s -C %s",
5691 cmd_merge, oid_to_hex(&commit->object.oid));
5693 /* label the tips of merged branches */
5694 for (; to_merge; to_merge = to_merge->next) {
5695 oid = &to_merge->item->object.oid;
5696 strbuf_addch(&buf, ' ');
5698 if (!oidset_contains(&interesting, oid)) {
5699 strbuf_addstr(&buf, label_oid(oid, NULL,
5700 &state));
5701 continue;
5704 tips_tail = &commit_list_insert(to_merge->item,
5705 tips_tail)->next;
5707 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5709 strbuf_addf(&buf, " # %s", oneline.buf);
5711 FLEX_ALLOC_STR(entry, string, buf.buf);
5712 oidcpy(&entry->entry.oid, &commit->object.oid);
5713 oidmap_put(&commit2todo, entry);
5715 if (skipped_commit)
5716 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5717 _("use --reapply-cherry-picks to include skipped commits"));
5720 * Second phase:
5721 * - label branch points
5722 * - add HEAD to the branch tips
5724 for (iter = commits; iter; iter = iter->next) {
5725 struct commit_list *parent = iter->item->parents;
5726 for (; parent; parent = parent->next) {
5727 struct object_id *oid = &parent->item->object.oid;
5728 if (!oidset_contains(&interesting, oid))
5729 continue;
5730 if (oidset_insert(&child_seen, oid))
5731 label_oid(oid, "branch-point", &state);
5734 /* Add HEAD as implicit "tip of branch" */
5735 if (!iter->next)
5736 tips_tail = &commit_list_insert(iter->item,
5737 tips_tail)->next;
5741 * Third phase: output the todo list. This is a bit tricky, as we
5742 * want to avoid jumping back and forth between revisions. To
5743 * accomplish that goal, we walk backwards from the branch tips,
5744 * gathering commits not yet shown, reversing the list on the fly,
5745 * then outputting that list (labeling revisions as needed).
5747 strbuf_addf(out, "%s onto\n", cmd_label);
5748 for (iter = tips; iter; iter = iter->next) {
5749 struct commit_list *list = NULL, *iter2;
5751 commit = iter->item;
5752 if (oidset_contains(&shown, &commit->object.oid))
5753 continue;
5754 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5756 if (entry)
5757 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5758 else
5759 strbuf_addch(out, '\n');
5761 while (oidset_contains(&interesting, &commit->object.oid) &&
5762 !oidset_contains(&shown, &commit->object.oid)) {
5763 commit_list_insert(commit, &list);
5764 if (!commit->parents) {
5765 commit = NULL;
5766 break;
5768 commit = commit->parents->item;
5771 if (!commit)
5772 strbuf_addf(out, "%s %s\n", cmd_reset,
5773 rebase_cousins || root_with_onto ?
5774 "onto" : "[new root]");
5775 else {
5776 const char *to = NULL;
5778 entry = oidmap_get(&state.commit2label,
5779 &commit->object.oid);
5780 if (entry)
5781 to = entry->string;
5782 else if (!rebase_cousins)
5783 to = label_oid(&commit->object.oid, NULL,
5784 &state);
5786 if (!to || !strcmp(to, "onto"))
5787 strbuf_addf(out, "%s onto\n", cmd_reset);
5788 else {
5789 strbuf_reset(&oneline);
5790 pretty_print_commit(pp, commit, &oneline);
5791 strbuf_addf(out, "%s %s # %s\n",
5792 cmd_reset, to, oneline.buf);
5796 for (iter2 = list; iter2; iter2 = iter2->next) {
5797 struct object_id *oid = &iter2->item->object.oid;
5798 entry = oidmap_get(&commit2todo, oid);
5799 /* only show if not already upstream */
5800 if (entry)
5801 strbuf_addf(out, "%s\n", entry->string);
5802 entry = oidmap_get(&state.commit2label, oid);
5803 if (entry)
5804 strbuf_addf(out, "%s %s\n",
5805 cmd_label, entry->string);
5806 oidset_insert(&shown, oid);
5809 free_commit_list(list);
5812 free_commit_list(commits);
5813 free_commit_list(tips);
5815 strbuf_release(&label);
5816 strbuf_release(&oneline);
5817 strbuf_release(&buf);
5819 oidmap_free(&commit2todo, 1);
5820 oidmap_free(&state.commit2label, 1);
5821 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5822 strbuf_release(&state.buf);
5824 return 0;
5827 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5828 const char **argv, unsigned flags)
5830 char *format = NULL;
5831 struct pretty_print_context pp = {0};
5832 struct rev_info revs;
5833 struct commit *commit;
5834 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5835 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5836 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5837 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5838 int skipped_commit = 0;
5839 int ret = 0;
5841 repo_init_revisions(r, &revs, NULL);
5842 revs.verbose_header = 1;
5843 if (!rebase_merges)
5844 revs.max_parents = 1;
5845 revs.cherry_mark = !reapply_cherry_picks;
5846 revs.limited = 1;
5847 revs.reverse = 1;
5848 revs.right_only = 1;
5849 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5850 revs.topo_order = 1;
5852 revs.pretty_given = 1;
5853 git_config_get_string("rebase.instructionFormat", &format);
5854 if (!format || !*format) {
5855 free(format);
5856 format = xstrdup("%s");
5858 get_commit_format(format, &revs);
5859 free(format);
5860 pp.fmt = revs.commit_format;
5861 pp.output_encoding = get_log_output_encoding();
5863 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5864 ret = error(_("make_script: unhandled options"));
5865 goto cleanup;
5868 if (prepare_revision_walk(&revs) < 0) {
5869 ret = error(_("make_script: error preparing revisions"));
5870 goto cleanup;
5873 if (rebase_merges) {
5874 ret = make_script_with_merges(&pp, &revs, out, flags);
5875 goto cleanup;
5878 while ((commit = get_revision(&revs))) {
5879 int is_empty = is_original_commit_empty(commit);
5881 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5882 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5883 warning(_("skipped previously applied commit %s"),
5884 short_commit_name(r, commit));
5885 skipped_commit = 1;
5886 continue;
5888 if (is_empty && !keep_empty)
5889 continue;
5890 strbuf_addf(out, "%s %s ", insn,
5891 oid_to_hex(&commit->object.oid));
5892 pretty_print_commit(&pp, commit, out);
5893 if (is_empty)
5894 strbuf_addf(out, " %c empty", comment_line_char);
5895 strbuf_addch(out, '\n');
5897 if (skipped_commit)
5898 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5899 _("use --reapply-cherry-picks to include skipped commits"));
5900 cleanup:
5901 release_revisions(&revs);
5902 return ret;
5906 * Add commands after pick and (series of) squash/fixup commands
5907 * in the todo list.
5909 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5910 struct string_list *commands)
5912 struct strbuf *buf = &todo_list->buf;
5913 size_t base_offset = buf->len;
5914 int i, insert, nr = 0, alloc = 0;
5915 struct todo_item *items = NULL, *base_items = NULL;
5917 CALLOC_ARRAY(base_items, commands->nr);
5918 for (i = 0; i < commands->nr; i++) {
5919 size_t command_len = strlen(commands->items[i].string);
5921 strbuf_addstr(buf, commands->items[i].string);
5922 strbuf_addch(buf, '\n');
5924 base_items[i].command = TODO_EXEC;
5925 base_items[i].offset_in_buf = base_offset;
5926 base_items[i].arg_offset = base_offset;
5927 base_items[i].arg_len = command_len;
5929 base_offset += command_len + 1;
5933 * Insert <commands> after every pick. Here, fixup/squash chains
5934 * are considered part of the pick, so we insert the commands *after*
5935 * those chains if there are any.
5937 * As we insert the exec commands immediately after rearranging
5938 * any fixups and before the user edits the list, a fixup chain
5939 * can never contain comments (any comments are empty picks that
5940 * have been commented out because the user did not specify
5941 * --keep-empty). So, it is safe to insert an exec command
5942 * without looking at the command following a comment.
5944 insert = 0;
5945 for (i = 0; i < todo_list->nr; i++) {
5946 enum todo_command command = todo_list->items[i].command;
5947 if (insert && !is_fixup(command)) {
5948 ALLOC_GROW(items, nr + commands->nr, alloc);
5949 COPY_ARRAY(items + nr, base_items, commands->nr);
5950 nr += commands->nr;
5952 insert = 0;
5955 ALLOC_GROW(items, nr + 1, alloc);
5956 items[nr++] = todo_list->items[i];
5958 if (command == TODO_PICK || command == TODO_MERGE)
5959 insert = 1;
5962 /* insert or append final <commands> */
5963 if (insert) {
5964 ALLOC_GROW(items, nr + commands->nr, alloc);
5965 COPY_ARRAY(items + nr, base_items, commands->nr);
5966 nr += commands->nr;
5969 free(base_items);
5970 FREE_AND_NULL(todo_list->items);
5971 todo_list->items = items;
5972 todo_list->nr = nr;
5973 todo_list->alloc = alloc;
5976 static void todo_list_to_strbuf(struct repository *r,
5977 struct todo_list *todo_list,
5978 struct strbuf *buf, int num, unsigned flags)
5980 struct todo_item *item;
5981 int i, max = todo_list->nr;
5983 if (num > 0 && num < max)
5984 max = num;
5986 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5987 char cmd;
5989 /* if the item is not a command write it and continue */
5990 if (item->command >= TODO_COMMENT) {
5991 strbuf_addf(buf, "%.*s\n", item->arg_len,
5992 todo_item_get_arg(todo_list, item));
5993 continue;
5996 /* add command to the buffer */
5997 cmd = command_to_char(item->command);
5998 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5999 strbuf_addch(buf, cmd);
6000 else
6001 strbuf_addstr(buf, command_to_string(item->command));
6003 /* add commit id */
6004 if (item->commit) {
6005 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6006 short_commit_name(r, item->commit) :
6007 oid_to_hex(&item->commit->object.oid);
6009 if (item->command == TODO_FIXUP) {
6010 if (item->flags & TODO_EDIT_FIXUP_MSG)
6011 strbuf_addstr(buf, " -c");
6012 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6013 strbuf_addstr(buf, " -C");
6017 if (item->command == TODO_MERGE) {
6018 if (item->flags & TODO_EDIT_MERGE_MSG)
6019 strbuf_addstr(buf, " -c");
6020 else
6021 strbuf_addstr(buf, " -C");
6024 strbuf_addf(buf, " %s", oid);
6027 /* add all the rest */
6028 if (!item->arg_len)
6029 strbuf_addch(buf, '\n');
6030 else
6031 strbuf_addf(buf, " %.*s\n", item->arg_len,
6032 todo_item_get_arg(todo_list, item));
6036 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6037 const char *file, const char *shortrevisions,
6038 const char *shortonto, int num, unsigned flags)
6040 int res;
6041 struct strbuf buf = STRBUF_INIT;
6043 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6044 if (flags & TODO_LIST_APPEND_TODO_HELP)
6045 append_todo_help(count_commands(todo_list),
6046 shortrevisions, shortonto, &buf);
6048 res = write_message(buf.buf, buf.len, file, 0);
6049 strbuf_release(&buf);
6051 return res;
6054 /* skip picking commits whose parents are unchanged */
6055 static int skip_unnecessary_picks(struct repository *r,
6056 struct todo_list *todo_list,
6057 struct object_id *base_oid)
6059 struct object_id *parent_oid;
6060 int i;
6062 for (i = 0; i < todo_list->nr; i++) {
6063 struct todo_item *item = todo_list->items + i;
6065 if (item->command >= TODO_NOOP)
6066 continue;
6067 if (item->command != TODO_PICK)
6068 break;
6069 if (repo_parse_commit(r, item->commit)) {
6070 return error(_("could not parse commit '%s'"),
6071 oid_to_hex(&item->commit->object.oid));
6073 if (!item->commit->parents)
6074 break; /* root commit */
6075 if (item->commit->parents->next)
6076 break; /* merge commit */
6077 parent_oid = &item->commit->parents->item->object.oid;
6078 if (!oideq(parent_oid, base_oid))
6079 break;
6080 oidcpy(base_oid, &item->commit->object.oid);
6082 if (i > 0) {
6083 const char *done_path = rebase_path_done();
6085 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6086 error_errno(_("could not write to '%s'"), done_path);
6087 return -1;
6090 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6091 todo_list->nr -= i;
6092 todo_list->current = 0;
6093 todo_list->done_nr += i;
6095 if (is_fixup(peek_command(todo_list, 0)))
6096 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6099 return 0;
6102 struct todo_add_branch_context {
6103 struct todo_item *items;
6104 size_t items_nr;
6105 size_t items_alloc;
6106 struct strbuf *buf;
6107 struct commit *commit;
6108 struct string_list refs_to_oids;
6111 static int add_decorations_to_list(const struct commit *commit,
6112 struct todo_add_branch_context *ctx)
6114 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6115 const char *head_ref = resolve_ref_unsafe("HEAD",
6116 RESOLVE_REF_READING,
6117 NULL,
6118 NULL);
6120 while (decoration) {
6121 struct todo_item *item;
6122 const char *path;
6123 size_t base_offset = ctx->buf->len;
6126 * If the branch is the current HEAD, then it will be
6127 * updated by the default rebase behavior.
6129 if (head_ref && !strcmp(head_ref, decoration->name)) {
6130 decoration = decoration->next;
6131 continue;
6134 ALLOC_GROW(ctx->items,
6135 ctx->items_nr + 1,
6136 ctx->items_alloc);
6137 item = &ctx->items[ctx->items_nr];
6138 memset(item, 0, sizeof(*item));
6140 /* If the branch is checked out, then leave a comment instead. */
6141 if ((path = branch_checked_out(decoration->name))) {
6142 item->command = TODO_COMMENT;
6143 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6144 decoration->name, path);
6145 } else {
6146 struct string_list_item *sti;
6147 item->command = TODO_UPDATE_REF;
6148 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6150 sti = string_list_insert(&ctx->refs_to_oids,
6151 decoration->name);
6152 sti->util = init_update_ref_record(decoration->name);
6155 item->offset_in_buf = base_offset;
6156 item->arg_offset = base_offset;
6157 item->arg_len = ctx->buf->len - base_offset;
6158 ctx->items_nr++;
6160 decoration = decoration->next;
6163 return 0;
6167 * For each 'pick' command, find out if the commit has a decoration in
6168 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6170 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6172 int i, res;
6173 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6174 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6175 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6176 struct decoration_filter decoration_filter = {
6177 .include_ref_pattern = &decorate_refs_include,
6178 .exclude_ref_pattern = &decorate_refs_exclude,
6179 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6181 struct todo_add_branch_context ctx = {
6182 .buf = &todo_list->buf,
6183 .refs_to_oids = STRING_LIST_INIT_DUP,
6186 ctx.items_alloc = 2 * todo_list->nr + 1;
6187 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6189 string_list_append(&decorate_refs_include, "refs/heads/");
6190 load_ref_decorations(&decoration_filter, 0);
6192 for (i = 0; i < todo_list->nr; ) {
6193 struct todo_item *item = &todo_list->items[i];
6195 /* insert ith item into new list */
6196 ALLOC_GROW(ctx.items,
6197 ctx.items_nr + 1,
6198 ctx.items_alloc);
6200 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6202 if (item->commit) {
6203 ctx.commit = item->commit;
6204 add_decorations_to_list(item->commit, &ctx);
6208 res = write_update_refs_state(&ctx.refs_to_oids);
6210 string_list_clear(&ctx.refs_to_oids, 1);
6212 if (res) {
6213 /* we failed, so clean up the new list. */
6214 free(ctx.items);
6215 return res;
6218 free(todo_list->items);
6219 todo_list->items = ctx.items;
6220 todo_list->nr = ctx.items_nr;
6221 todo_list->alloc = ctx.items_alloc;
6223 return 0;
6226 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6227 const char *shortrevisions, const char *onto_name,
6228 struct commit *onto, const struct object_id *orig_head,
6229 struct string_list *commands, unsigned autosquash,
6230 unsigned update_refs,
6231 struct todo_list *todo_list)
6233 char shortonto[GIT_MAX_HEXSZ + 1];
6234 const char *todo_file = rebase_path_todo();
6235 struct todo_list new_todo = TODO_LIST_INIT;
6236 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6237 struct object_id oid = onto->object.oid;
6238 int res;
6240 repo_find_unique_abbrev_r(r, shortonto, &oid,
6241 DEFAULT_ABBREV);
6243 if (buf->len == 0) {
6244 struct todo_item *item = append_new_todo(todo_list);
6245 item->command = TODO_NOOP;
6246 item->commit = NULL;
6247 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6250 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6251 return -1;
6253 if (autosquash && todo_list_rearrange_squash(todo_list))
6254 return -1;
6256 if (commands->nr)
6257 todo_list_add_exec_commands(todo_list, commands);
6259 if (count_commands(todo_list) == 0) {
6260 apply_autostash(rebase_path_autostash());
6261 sequencer_remove_state(opts);
6263 return error(_("nothing to do"));
6266 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6267 shortonto, flags);
6268 if (res == -1)
6269 return -1;
6270 else if (res == -2) {
6271 apply_autostash(rebase_path_autostash());
6272 sequencer_remove_state(opts);
6274 return -1;
6275 } else if (res == -3) {
6276 apply_autostash(rebase_path_autostash());
6277 sequencer_remove_state(opts);
6278 todo_list_release(&new_todo);
6280 return error(_("nothing to do"));
6281 } else if (res == -4) {
6282 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6283 todo_list_release(&new_todo);
6285 return -1;
6288 /* Expand the commit IDs */
6289 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6290 strbuf_swap(&new_todo.buf, &buf2);
6291 strbuf_release(&buf2);
6292 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6293 new_todo.total_nr = 0;
6294 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6295 BUG("invalid todo list after expanding IDs:\n%s",
6296 new_todo.buf.buf);
6298 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6299 todo_list_release(&new_todo);
6300 return error(_("could not skip unnecessary pick commands"));
6303 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6304 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6305 todo_list_release(&new_todo);
6306 return error_errno(_("could not write '%s'"), todo_file);
6309 res = -1;
6311 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6312 goto cleanup;
6314 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6315 goto cleanup;
6317 todo_list_write_total_nr(&new_todo);
6318 res = pick_commits(r, &new_todo, opts);
6320 cleanup:
6321 todo_list_release(&new_todo);
6323 return res;
6326 struct subject2item_entry {
6327 struct hashmap_entry entry;
6328 int i;
6329 char subject[FLEX_ARRAY];
6332 static int subject2item_cmp(const void *fndata UNUSED,
6333 const struct hashmap_entry *eptr,
6334 const struct hashmap_entry *entry_or_key,
6335 const void *key)
6337 const struct subject2item_entry *a, *b;
6339 a = container_of(eptr, const struct subject2item_entry, entry);
6340 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6342 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6345 define_commit_slab(commit_todo_item, struct todo_item *);
6347 static int skip_fixupish(const char *subject, const char **p) {
6348 return skip_prefix(subject, "fixup! ", p) ||
6349 skip_prefix(subject, "amend! ", p) ||
6350 skip_prefix(subject, "squash! ", p);
6354 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6355 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6356 * after the former, and change "pick" to "fixup"/"squash".
6358 * Note that if the config has specified a custom instruction format, each log
6359 * message will have to be retrieved from the commit (as the oneline in the
6360 * script cannot be trusted) in order to normalize the autosquash arrangement.
6362 int todo_list_rearrange_squash(struct todo_list *todo_list)
6364 struct hashmap subject2item;
6365 int rearranged = 0, *next, *tail, i, nr = 0;
6366 char **subjects;
6367 struct commit_todo_item commit_todo;
6368 struct todo_item *items = NULL;
6370 init_commit_todo_item(&commit_todo);
6372 * The hashmap maps onelines to the respective todo list index.
6374 * If any items need to be rearranged, the next[i] value will indicate
6375 * which item was moved directly after the i'th.
6377 * In that case, last[i] will indicate the index of the latest item to
6378 * be moved to appear after the i'th.
6380 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6381 ALLOC_ARRAY(next, todo_list->nr);
6382 ALLOC_ARRAY(tail, todo_list->nr);
6383 ALLOC_ARRAY(subjects, todo_list->nr);
6384 for (i = 0; i < todo_list->nr; i++) {
6385 struct strbuf buf = STRBUF_INIT;
6386 struct todo_item *item = todo_list->items + i;
6387 const char *commit_buffer, *subject, *p;
6388 size_t subject_len;
6389 int i2 = -1;
6390 struct subject2item_entry *entry;
6392 next[i] = tail[i] = -1;
6393 if (!item->commit || item->command == TODO_DROP) {
6394 subjects[i] = NULL;
6395 continue;
6398 if (is_fixup(item->command)) {
6399 clear_commit_todo_item(&commit_todo);
6400 return error(_("the script was already rearranged."));
6403 repo_parse_commit(the_repository, item->commit);
6404 commit_buffer = repo_logmsg_reencode(the_repository,
6405 item->commit, NULL,
6406 "UTF-8");
6407 find_commit_subject(commit_buffer, &subject);
6408 format_subject(&buf, subject, " ");
6409 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6410 repo_unuse_commit_buffer(the_repository, item->commit,
6411 commit_buffer);
6412 if (skip_fixupish(subject, &p)) {
6413 struct commit *commit2;
6415 for (;;) {
6416 while (isspace(*p))
6417 p++;
6418 if (!skip_fixupish(p, &p))
6419 break;
6422 entry = hashmap_get_entry_from_hash(&subject2item,
6423 strhash(p), p,
6424 struct subject2item_entry,
6425 entry);
6426 if (entry)
6427 /* found by title */
6428 i2 = entry->i;
6429 else if (!strchr(p, ' ') &&
6430 (commit2 =
6431 lookup_commit_reference_by_name(p)) &&
6432 *commit_todo_item_at(&commit_todo, commit2))
6433 /* found by commit name */
6434 i2 = *commit_todo_item_at(&commit_todo, commit2)
6435 - todo_list->items;
6436 else {
6437 /* copy can be a prefix of the commit subject */
6438 for (i2 = 0; i2 < i; i2++)
6439 if (subjects[i2] &&
6440 starts_with(subjects[i2], p))
6441 break;
6442 if (i2 == i)
6443 i2 = -1;
6446 if (i2 >= 0) {
6447 rearranged = 1;
6448 if (starts_with(subject, "fixup!")) {
6449 todo_list->items[i].command = TODO_FIXUP;
6450 } else if (starts_with(subject, "amend!")) {
6451 todo_list->items[i].command = TODO_FIXUP;
6452 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6453 } else {
6454 todo_list->items[i].command = TODO_SQUASH;
6456 if (tail[i2] < 0) {
6457 next[i] = next[i2];
6458 next[i2] = i;
6459 } else {
6460 next[i] = next[tail[i2]];
6461 next[tail[i2]] = i;
6463 tail[i2] = i;
6464 } else if (!hashmap_get_from_hash(&subject2item,
6465 strhash(subject), subject)) {
6466 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6467 entry->i = i;
6468 hashmap_entry_init(&entry->entry,
6469 strhash(entry->subject));
6470 hashmap_put(&subject2item, &entry->entry);
6473 *commit_todo_item_at(&commit_todo, item->commit) = item;
6476 if (rearranged) {
6477 ALLOC_ARRAY(items, todo_list->nr);
6479 for (i = 0; i < todo_list->nr; i++) {
6480 enum todo_command command = todo_list->items[i].command;
6481 int cur = i;
6484 * Initially, all commands are 'pick's. If it is a
6485 * fixup or a squash now, we have rearranged it.
6487 if (is_fixup(command))
6488 continue;
6490 while (cur >= 0) {
6491 items[nr++] = todo_list->items[cur];
6492 cur = next[cur];
6496 assert(nr == todo_list->nr);
6497 todo_list->alloc = nr;
6498 FREE_AND_NULL(todo_list->items);
6499 todo_list->items = items;
6502 free(next);
6503 free(tail);
6504 for (i = 0; i < todo_list->nr; i++)
6505 free(subjects[i]);
6506 free(subjects);
6507 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6509 clear_commit_todo_item(&commit_todo);
6511 return 0;
6514 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6516 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6517 struct object_id cherry_pick_head, rebase_head;
6519 if (file_exists(git_path_seq_dir()))
6520 *whence = FROM_CHERRY_PICK_MULTI;
6521 if (file_exists(rebase_path()) &&
6522 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6523 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6524 oideq(&rebase_head, &cherry_pick_head))
6525 *whence = FROM_REBASE_PICK;
6526 else
6527 *whence = FROM_CHERRY_PICK_SINGLE;
6529 return 1;
6532 return 0;
6535 int sequencer_get_update_refs_state(const char *wt_dir,
6536 struct string_list *refs)
6538 int result = 0;
6539 FILE *fp = NULL;
6540 struct strbuf ref = STRBUF_INIT;
6541 struct strbuf hash = STRBUF_INIT;
6542 struct update_ref_record *rec = NULL;
6544 char *path = rebase_path_update_refs(wt_dir);
6546 fp = fopen(path, "r");
6547 if (!fp)
6548 goto cleanup;
6550 while (strbuf_getline(&ref, fp) != EOF) {
6551 struct string_list_item *item;
6553 CALLOC_ARRAY(rec, 1);
6555 if (strbuf_getline(&hash, fp) == EOF ||
6556 get_oid_hex(hash.buf, &rec->before)) {
6557 warning(_("update-refs file at '%s' is invalid"),
6558 path);
6559 result = -1;
6560 goto cleanup;
6563 if (strbuf_getline(&hash, fp) == EOF ||
6564 get_oid_hex(hash.buf, &rec->after)) {
6565 warning(_("update-refs file at '%s' is invalid"),
6566 path);
6567 result = -1;
6568 goto cleanup;
6571 item = string_list_insert(refs, ref.buf);
6572 item->util = rec;
6573 rec = NULL;
6576 cleanup:
6577 if (fp)
6578 fclose(fp);
6579 free(path);
6580 free(rec);
6581 strbuf_release(&ref);
6582 strbuf_release(&hash);
6583 return result;